<?php
require_once __DIR__ . '/../../../includes/auth.php';
requireLogin();
requirePermission('manage_operations');

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

// Force CSV download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=operations_report.csv');

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

// CSV Header Row
fputcsv($output, ['Ticket #', 'Status', 'Priority', 'Assigned To', 'Created At']);

// Fetch ticket data
$stmt = $pdo->prepare("
    SELECT t.ticket_number,
           t.status,
           t.priority,
           u.full_name,
           t.created_at
    FROM operations_tickets t
    LEFT JOIN users u ON t.assigned_to = u.id
    WHERE t.tenant_id = ?
    ORDER BY t.created_at DESC
");

$stmt->execute([$_SESSION['tenant_id'] ?? 1]);

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    fputcsv($output, $row);
}

fclose($output);
exit;