<?php
session_start();
require_once 'db.php';
require_once '../vendor/autoload.php';
require_once 'report_functions.php';

if (!isset($_SESSION['user_id'])) {
    die("Unauthorized");
}

$type = $_GET['type'] ?? 'reorder';
$category_id = $_GET['category_id'] ?? null;
$settings = get_report_settings($pdo);
$currency = $settings['company_currency_code'] ?? 'USD';

$html = '';
$title = '';
$meta = [
    'Date' => date('d M Y'),
    'Generated By' => $_SESSION['username'] ?? 'System Admin'
];

if ($type === 'reorder') {
    $title = "Critical Reorder List";
    $stmt = $pdo->query("SELECT p.*, c.name as category_name 
                         FROM products p 
                         LEFT JOIN categories c ON p.category_id = c.id 
                         WHERE p.stock_quantity <= p.min_stock_level 
                         ORDER BY p.stock_quantity ASC");
    $items = $stmt->fetchAll();
    
    $meta['Total Items'] = count($items);
    
    ob_start();
    ?>
    <table class="table">
        <thead>
            <tr>
                <th>Product Description</th>
                <th class="text-center">Category</th>
                <th class="text-center">Safety Threshold</th>
                <th class="text-center">Current Qty</th>
                <th class="text-right">Unit Cost</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($items as $item): ?>
                <tr>
                    <td>
                        <strong><?php echo $item['name']; ?></strong><br>
                        <small style="color: #666;">SKU: <?php echo $item['sku']; ?> | Barcode: <?php echo $item['barcode'] ?: 'N/A'; ?></small>
                    </td>
                    <td class="text-center"><?php echo $item['category_name'] ?: 'N/A'; ?></td>
                    <td class="text-center"><?php echo $item['min_stock_level']; ?></td>
                    <td class="text-center fw-bold <?php echo $item['stock_quantity'] <= 0 ? 'text-danger' : ''; ?>">
                        <?php echo $item['stock_quantity']; ?>
                    </td>
                    <td class="text-right"><?php echo $currency . ' ' . format_amount($item['cost_price']); ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($items)): ?>
                <tr><td colspan="5" class="text-center">No low stock items found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
    <?php
    $html = ob_get_clean();

} elseif ($type === 'valuation') {
    $catName = 'All Categories';
    $where = "";
    $params = [];
    
    if ($category_id) {
        $stmt = $pdo->prepare("SELECT name FROM categories WHERE id = ?");
        $stmt->execute([$category_id]);
        $catName = $stmt->fetchColumn() ?: 'Unknown Category';
        $where = "WHERE p.category_id = ?";
        $params = [$category_id];
    }
    
    $title = "Stock Valuation: " . $catName;
    $stmt = $pdo->prepare("SELECT p.*, c.name as category_name 
                           FROM products p 
                           LEFT JOIN categories c ON p.category_id = c.id 
                           $where 
                           ORDER BY (p.stock_quantity * p.cost_price) DESC");
    $stmt->execute($params);
    $items = $stmt->fetchAll();
    
    $totalValue = 0;
    foreach($items as $item) {
        $totalValue += ($item['stock_quantity'] * $item['cost_price']);
    }
    
    $meta['Total SKUs'] = count($items);
    $meta['Portfolio Value'] = $currency . ' ' . format_amount($totalValue);

    ob_start();
    ?>
    <table class="table">
        <thead>
            <tr>
                <th>Product / SKU</th>
                <th class="text-right">Unit Cost</th>
                <th class="text-center">Qty on Hand</th>
                <th class="text-right">Total Value</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($items as $item): ?>
                <?php $val = $item['stock_quantity'] * $item['cost_price']; ?>
                <tr>
                    <td>
                        <strong><?php echo $item['name']; ?></strong><br>
                        <small style="color: #666;">SKU: <?php echo $item['sku']; ?></small>
                    </td>
                    <td class="text-right"><?php echo format_amount($item['cost_price']); ?></td>
                    <td class="text-center"><?php echo $item['stock_quantity']; ?></td>
                    <td class="text-right fw-bold text-primary"><?php echo format_amount($val); ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr>
                <th colspan="3" class="text-right">GRAND TOTAL</th>
                <th class="text-right"><?php echo $currency . ' ' . format_amount($totalValue); ?></th>
            </tr>
        </tfoot>
    </table>
    <?php
    $html = ob_get_clean();
}

$header = render_report_header($title, $settings, 'pdf', $meta);
$footer = render_report_footer($settings);

$attachment = isset($_GET['download']) && $_GET['download'] == '1';
export_to_pdf($header . $html . $footer, str_replace(' ', '_', $title) . ".pdf", 'portrait', true, $attachment);
