<?php
session_start();

if (!isset($_SESSION['role_id']) || !in_array($_SESSION['role_id'], [1, 2])) {
    die("Unauthorized access.");
}

require_once '../../includes/config.php';

$role_id = $_SESSION['role_id'];
$user_id = $_SESSION['user_id'];

$type = $_GET['type'] ?? 'csv';
$filter_product = $_GET['product_id'] ?? '';
$filter_store = $_GET['store_id'] ?? '';
$filter_supplier = $_GET['supplier_id'] ?? '';
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';

// For managers, get their assigned store_id from users table
$manager_store_id = null;
if ($role_id == 2) {
    $stmt = $conn->prepare("SELECT store_id FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->bind_result($manager_store_id);
    $stmt->fetch();
    $stmt->close();
}

// Build filters with role-based store restriction
$conditions = [];
$params = [];
$types = '';

// Managers restricted to their store only
if ($role_id == 2) {
    $conditions[] = "se.store_id = ?";
    $params[] = $manager_store_id;
    $types .= 'i';
} else {
    // Admin can filter by store or all
    if ($filter_store !== '') {
        $conditions[] = "se.store_id = ?";
        $params[] = $filter_store;
        $types .= 'i';
    }
}

if ($filter_product !== '') {
    $conditions[] = "se.product_id = ?";
    $params[] = $filter_product;
    $types .= 'i';
}

if ($filter_supplier !== '') {
    $conditions[] = "se.supplier_id = ?";
    $params[] = $filter_supplier;
    $types .= 'i';
}

if ($start_date && $end_date) {
    $conditions[] = "se.purchase_date BETWEEN ? AND ?";
    $params[] = $start_date;
    $params[] = $end_date;
    $types .= 'ss';
}

$where = $conditions ? 'WHERE ' . implode(' AND ', $conditions) : '';

$sql = "
    SELECT se.*, 
           p.product_name,
           s.store_name,
           u.username AS added_by_user,
           su.supplier_name
    FROM stock_entries se
    JOIN products p ON se.product_id = p.id
    JOIN stores s ON se.store_id = s.id
    LEFT JOIN users u ON se.added_by = u.id
    LEFT JOIN suppliers su ON se.supplier_id = su.id
    $where
    ORDER BY se.created_at DESC
";

$stmt = $conn->prepare($sql);
if ($params) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

$entries = [];
while ($row = $result->fetch_assoc()) {
    $entries[] = $row;
}

if ($type === 'csv') {
    // Output BOM for UTF-8 Excel compatibility
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="stock_entries_export.csv"');
    echo "\xEF\xBB\xBF"; // BOM

    $output = fopen('php://output', 'w');
    fputcsv($output, [
        'ID', 'Product', 'Store', 'Supplier', 'Quantity', 'Cost Price',
        'Purchase Date', 'Remarks', 'Added By', 'Created At'
    ]);

    foreach ($entries as $row) {
        fputcsv($output, [
            $row['id'],
            $row['product_name'],
            $row['store_name'],
            $row['supplier_name'] ?? '-',
            $row['quantity'],
            $row['cost_price'],
            $row['purchase_date'],
            $row['remarks'] ?? '',
            $row['added_by_user'] ?? '-',
            $row['created_at']
        ]);
    }

    fclose($output);
    exit();
}

if ($type === 'pdf') {
    // Check if TCPDF is installed, else fallback to CSV
    if (!class_exists('TCPDF')) {
        die('TCPDF library not found. Please install TCPDF or export as CSV.');
    }

    require_once '../../vendor/tcpdf/tcpdf.php';

    $pdf = new TCPDF('L', 'mm', 'A4', true, 'UTF-8', false);
    $pdf->SetCreator('Digital POS');
    $pdf->SetAuthor('System');
    $pdf->SetTitle('Stock Entries Export');
    $pdf->SetHeaderData('', 0, 'Stock Entries Report', date('d M Y'));
    $pdf->setHeaderFont(['helvetica', '', 10]);
    $pdf->setFooterFont(['helvetica', '', 8]);
    $pdf->SetMargins(10, 25, 10);
    $pdf->SetHeaderMargin(5);
    $pdf->SetFooterMargin(10);
    $pdf->SetAutoPageBreak(TRUE, 15);
    $pdf->AddPage();

    $html = '<style>table{border-collapse:collapse;width:100%;}th,td{border:1px solid #000;padding:4px;font-size:10px;}</style>';
    $html .= '<h2>Stock Entries Export</h2>';
    $html .= '<table><thead><tr>
                <th>ID</th><th>Product</th><th>Store</th><th>Supplier</th><th>Qty</th><th>Cost</th>
                <th>Date</th><th>Remarks</th><th>Added By</th><th>Created</th>
              </tr></thead><tbody>';

    foreach ($entries as $row) {
        $html .= '<tr>
                    <td>' . $row['id'] . '</td>
                    <td>' . htmlspecialchars($row['product_name']) . '</td>
                    <td>' . htmlspecialchars($row['store_name']) . '</td>
                    <td>' . htmlspecialchars($row['supplier_name'] ?? '-') . '</td>
                    <td>' . $row['quantity'] . '</td>
                    <td>MK' . number_format($row['cost_price'], 2) . '</td>
                    <td>' . $row['purchase_date'] . '</td>
                    <td>' . htmlspecialchars($row['remarks'] ?? '-') . '</td>
                    <td>' . htmlspecialchars($row['added_by_user'] ?? '-') . '</td>
                    <td>' . $row['created_at'] . '</td>
                  </tr>';
    }

    $html .= '</tbody></table>';
    $pdf->writeHTML($html, true, false, true, false, '');
    $pdf->Output('stock_entries_export.pdf', 'D');
    exit();
}

// Fallback if unknown type
echo "Invalid export type.";
exit;
