<?php
include 'auth_check.php';

if (!isAdmin()) {
    header("Location: sale.php");
    exit();
}

header("Content-Type: application/vnd.ms-excel");

$type = isset($_GET['type']) ? $_GET['type'] : 'stock';

if ($type == 'purchasing') {
    header("Content-Disposition: attachment; filename=all_purchasing_product_data.xls");

    $result = $conn->query("SELECT * FROM all_purchasing_product_data ORDER BY id DESC");

    echo "Product Name\tPurchasing Value\tPrimary Selling Price\tMode 1 Name\tMode 1 Qty\tMode 1 Price\tMode 2 Name\tMode 2 Qty\tMode 2 Price\tPurchased Qty\tUnit\tInvoice Number\tExpiry Date\tTotal Purchasing Price\tDate\tTime\tUser\n";
    while($row = $result->fetch_assoc()) {
        echo $row['product_name']."\t".$row['purchasing_price']."\t".$row['selling_price']."\t".($row['dual_mode_name_1'] ?? '')."\t".($row['dual_mode_qty_1'] ?? '')."\t".($row['dual_mode_price_1'] ?? '')."\t".($row['dual_mode_name_2'] ?? '')."\t".($row['dual_mode_qty_2'] ?? '')."\t".($row['dual_mode_price_2'] ?? '')."\t".$row['purchased_qty']."\t".$row['unit']."\t".$row['invoice_number']."\t".$row['expiry_date']."\t".$row['total_purchasing_price']."\t".$row['entered_date']."\t".$row['entered_time']."\t".$row['entered_user']."\n";
    }
} elseif ($type == 'returned') {
    header("Content-Disposition: attachment; filename=returned_product_data.xls");

    $result = $conn->query("SELECT * FROM returned_product_data ORDER BY id DESC");

    echo "Bill Number\tProduct Name\tUnit\tSelling Mode\tSelling Price\tReturned Qty\tDiscount\tLine Total\tOriginal Date\tOriginal Time\tOriginal User\tReturned Date\tReturned Time\tReturned User\n";
    while($row = $result->fetch_assoc()) {
        echo $row['bill_number']."\t".$row['product_name']."\t".$row['unit']."\t".($row['selling_mode'] ?? '')."\t".$row['selling_price']."\t".$row['qty']."\t".$row['discount']."\t".$row['line_total']."\t".$row['entered_date']."\t".$row['entered_time']."\t".$row['entered_user']."\t".$row['returned_date']."\t".$row['returned_time']."\t".$row['returned_user']."\n";
    }
} else {
    header("Content-Disposition: attachment; filename=stock_data.xls");

    $result = $conn->query("SELECT * FROM stock ORDER BY product_name ASC");

    echo "Product Name\tPurchasing Value\tPrimary Selling Price\tMode 1 Name\tMode 1 Qty\tMode 1 Price\tMode 2 Name\tMode 2 Qty\tMode 2 Price\tQty\tUnit\tInvoice Number\tExpiry Date\tDate\tTime\tUser\n";
    while($row = $result->fetch_assoc()) {
        echo $row['product_name']."\t".$row['purchasing_price']."\t".$row['selling_price']."\t".($row['dual_mode_name_1'] ?? '')."\t".($row['dual_mode_qty_1'] ?? '')."\t".($row['dual_mode_price_1'] ?? '')."\t".($row['dual_mode_name_2'] ?? '')."\t".($row['dual_mode_qty_2'] ?? '')."\t".($row['dual_mode_price_2'] ?? '')."\t".$row['purchased_qty']."\t".$row['unit']."\t".$row['invoice_number']."\t".$row['expiry_date']."\t".$row['entered_date']."\t".$row['entered_time']."\t".$row['entered_user']."\n";
    }
}
exit;
?>