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

// Suraksha jaanch
if (!userHasRole(['Admin', 'Manager'])) {
    header("HTTP/1.1 403 Forbidden");
    exit("You do not have permission to access this page.");
}

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

// Output stream open karein
$output = fopen('php://output', 'w');

// CSV ka header row likhein
fputcsv($output, ['Date', 'Client Name', 'Transaction Type', 'Description / Ad Account', 'Debit (₹)', 'Credit (₹)']);

$all_data = [];

// 1. Saare Ad Spends (Debits) fetch karein
$spends_query = "SELECT 
                    ad.ad_date AS `date`,
                    c.name AS client_name,
                    'Ad Spend' AS transaction_type,
                    ac.name AS description,
                    ad.ad_amount AS debit,
                    0 AS credit
                FROM 
                    ad_spends ad
                JOIN 
                    clients c ON ad.client_id = c.id
                JOIN 
                    ad_accounts ac ON ad.ad_account_id = ac.id";

if ($result = $conn->query($spends_query)) {
    while ($row = $result->fetch_assoc()) {
        $all_data[] = $row;
    }
    $result->free();
}

// 2. Saare Agency Fund Additions (Credits) fetch karein
$agency_funds_query = "SELECT 
                            mwt.transaction_date AS `date`,
                            'Digify Agency' AS client_name,
                            'Funds Added' AS transaction_type,
                            CONCAT(aa.name, ' - ', mwt.description) AS description,
                            0 AS debit,
                            mwt.amount AS credit
                        FROM 
                            main_wallet_transactions mwt
                        JOIN 
                            ad_accounts aa ON mwt.ad_account_id = aa.id";

if ($result = $conn->query($agency_funds_query)) {
    while ($row = $result->fetch_assoc()) {
        $all_data[] = $row;
    }
    $result->free();
}

// Note: Client fund additions ka alag se transaction log nahi hai, isliye unhe yahan shaamil nahi kiya ja sakta.

// Data ko date ke hisab se sort karein
usort($all_data, function($a, $b) {
    return strtotime($a['date']) - strtotime($b['date']);
});

// Saare data ko CSV mein likhein
foreach ($all_data as $row) {
    fputcsv($output, [
        $row['date'],
        $row['client_name'],
        $row['transaction_type'],
        $row['description'],
        $row['debit'],
        $row['credit']
    ]);
}

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