<?php
// config.php ko shaamil karein
require_once 'config.php';

// Suraksha jaanch
if (!userHasRole(['Admin', 'Manager'])) {
    die("Access Denied.");
}

// Filters ko GET request se lein
$filter_client = $_GET['filter_client'] ?? 'all';
$filter_account = $_GET['filter_account'] ?? 'all';
$filter_start_date = $_GET['filter_start_date'] ?? '';
$filter_end_date = $_GET['filter_end_date'] ?? '';

// CSV file ke liye headers set karein
$filename = "Ad_Spend_Report_" . date('Y-m-d') . ".csv";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');

// Output ke liye file pointer banayein
$output = fopen('php://output', 'w');

// CSV ka header likhein
fputcsv($output, ['Ad Date', 'Client Name', 'Account Used', 'Amount', 'Duration (Days)', 'Ad Link']);

// Database se data fetch karein
$params = [];
$param_types = '';
$sql = "SELECT ad.ad_date, c.name as client_name, ac.name as account_name, ad.ad_amount, ad.duration_days, ad.ad_link 
        FROM ad_spends ad 
        JOIN clients c ON ad.client_id = c.id 
        JOIN ad_accounts ac ON ad.ad_account_id = ac.id 
        WHERE 1=1";

if($filter_client != 'all'){ $sql .= " AND ad.client_id = ?"; $params[] = $filter_client; $param_types .= 'i'; }
if($filter_account != 'all'){ $sql .= " AND ad.ad_account_id = ?"; $params[] = $filter_account; $param_types .= 'i'; }
if(!empty($filter_start_date)){ $sql .= " AND ad.ad_date >= ?"; $params[] = $filter_start_date; $param_types .= 's'; }
if(!empty($filter_end_date)){ $sql .= " AND ad.ad_date <= ?"; $params[] = $filter_end_date; $param_types .= 's'; }
$sql .= " ORDER BY ad.ad_date DESC";

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

// Data ko CSV file mein likhein
while ($row = $result->fetch_assoc()) {
    fputcsv($output, $row);
}

$stmt->close();
$conn->close();
fclose($output);
exit();
?>