<?php

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../includes/auth.php';
requireLogin();
requirePermission('view_inventory');

require_once __DIR__ . '/../../config/database.php';

$company_id = $_SESSION['company_id'] ?? 0;

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="items.csv"');

$output = fopen("php://output", "w");

fputcsv($output, [
'category',
'item_type',
'product_name',
'brand',
'model',
'sku',
'cost_price',
'selling_price',
'description',
'track_inventory',
'stock_qty',
'status'
]);

$stmt = $pdo->prepare("
SELECT p.*, c.category_name
FROM inventory_products p
LEFT JOIN inventory_categories c
ON p.category_id = c.id
WHERE p.company_id = ?
ORDER BY p.product_name
");
$stmt->execute([$company_id]);

while($row = $stmt->fetch(PDO::FETCH_ASSOC)){

    fputcsv($output, [
        $row['category_name'],
        $row['item_type'] ?? 'PRODUCT',
        $row['product_name'],
        $row['brand'],
        $row['model'],
        $row['sku'],
        $row['cost_price'],
        $row['selling_price'],
        $row['description'],
        $row['track_inventory'] ?? 0,
        $row['stock_qty'] ?? 0,
        $row['status']
    ]);
}

fclose($output);
exit;