<?php
include 'includes/auth.php';
include 'db.php';
require 'dompdf/vendor/autoload.php';

use Dompdf\Dompdf;

$type = $_GET['type'] ?? 'pdf';
$type = strtolower($type);

// Fetch products
$products = $conn->query("SELECT p.*, c.name AS category_name 
                          FROM products p 
                          LEFT JOIN categories c ON p.category_id=c.id 
                          ORDER BY p.name ASC");

// --- PDF Export ---
if($type=='pdf'){
    $html = '<h3 style="text-align:center;">Products Report</h3>';
    $html .= '<table border="1" cellpadding="5" cellspacing="0" width="100%">';
    $html .= '<tr style="background:#000;color:#fff;">
                <th>SKU</th>
                <th>Name</th>
                <th>Category</th>
                <th>Buying Price</th>
                <th>Selling Price</th>
                <th>VAT</th>
                <th>Quantity</th>
                <th>Min Level</th>
                <th>Can Sell OOS</th>
              </tr>';

    while($row=$products->fetch_assoc()){
        $html .= "<tr>
                    <td>{$row['sku']}</td>
                    <td>{$row['name']}</td>
                    <td>{$row['category_name']}</td>
                    <td>".number_format($row['buying_price'],2)."</td>
                    <td>".number_format($row['selling_price'],2)."</td>
                    <td>{$row['vat_rate']}</td>
                    <td>{$row['quantity']}</td>
                    <td>{$row['min_level']}</td>
                    <td>".($row['can_sell_when_out_of_stock']?'Yes':'No')."</td>
                  </tr>";
    }
    $html .= '</table>';

    $dompdf = new Dompdf();
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4','landscape');
    $dompdf->render();
    $dompdf->stream("products_report.pdf", ["Attachment"=>true]);
    exit;
}

// --- Excel (CSV) Export ---
elseif($type=='excel'){
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="products_report.csv"');
    header('Cache-Control: max-age=0');

    $output = fopen('php://output', 'w');
    // Headers
    fputcsv($output, ['SKU','Name','Category','Buying Price','Selling Price','VAT','Quantity','Min Level','Can Sell OOS']);

    // Data
    while($row=$products->fetch_assoc()){
        fputcsv($output, [
            $row['sku'],
            $row['name'],
            $row['category_name'],
            number_format($row['buying_price'],2),
            number_format($row['selling_price'],2),
            $row['vat_rate'],
            $row['quantity'],
            $row['min_level'],
            $row['can_sell_when_out_of_stock']?'Yes':'No'
        ]);
    }

    fclose($output);
    exit;
}
else{
    echo "Invalid export type";
}
