<?php
// init.php ko shaamil karein, jo sab kuch setup karega
require_once 'init.php';

// Suraksha jaanch
if (!userHasRole(['Admin', 'Manager'])) {
    header("Location: dashboard.php");
    exit();
}

$is_admin = userHasRole(['Admin']);

// Session se message prapt karein
$message = $_SESSION['message'] ?? '';
$message_type = $_SESSION['message_type'] ?? '';
unset($_SESSION['message'], $_SESSION['message_type']);

// --- FORM SUBMISSION LOGIC (PRG Pattern ke saath) ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // 1. Naya Ad Spend Add Karein
    if (isset($_POST['add_spend'])) {
        try {
            $conn->begin_transaction();
            $client_id = (int)$_POST['client_id'];
            $ad_account_id = (int)$_POST['ad_account_id'];
            $ad_amount = (float)$_POST['ad_amount'];
            $remark = !empty($_POST['remark']) ? trim($_POST['remark']) : NULL;

            $stmt1 = $conn->prepare("INSERT INTO ad_spends (client_id, ad_account_id, ad_date, ad_amount, ad_link, duration_days, remark) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $duration_days_val = !empty($_POST['duration_days']) ? (int)$_POST['duration_days'] : NULL;
            $stmt1->bind_param("iisdsis", $client_id, $ad_account_id, $_POST['ad_date'], $ad_amount, $_POST['ad_link'], $duration_days_val, $remark);
            if (!$stmt1->execute()) { throw new Exception($stmt1->error); }
            $stmt1->close();

            $acc_stmt = $conn->prepare("SELECT account_type FROM ad_accounts WHERE id = ?");
            $acc_stmt->bind_param("i", $ad_account_id);
            $acc_stmt->execute();
            $account = $acc_stmt->get_result()->fetch_assoc();
            $acc_stmt->close();
            
            if ($account && $account['account_type'] == 'Client Wallet') {
                $stmt = $conn->prepare("UPDATE clients SET wallet_balance = wallet_balance - ? WHERE id = ?");
                $stmt->bind_param("di", $ad_amount, $client_id);
                if (!$stmt->execute()) { throw new Exception($stmt->error); }
                $stmt->close();
            } else {
                $stmt_agency = $conn->prepare("UPDATE ad_accounts SET main_balance = main_balance - ? WHERE id = ?");
                $stmt_agency->bind_param("di", $ad_amount, $ad_account_id);
                if (!$stmt_agency->execute()) { throw new Exception($stmt_agency->error); }
                $stmt_agency->close();
                
                $stmt_client = $conn->prepare("UPDATE clients SET wallet_balance = wallet_balance - ? WHERE id = ?");
                $stmt_client->bind_param("di", $ad_amount, $client_id);
                if (!$stmt_client->execute()) { throw new Exception($stmt_client->error); }
                $stmt_client->close();
            }

            $conn->commit();
            $_SESSION['message'] = "Ad spend of ₹" . number_format($ad_amount, 2) . " recorded successfully!";
            $_SESSION['message_type'] = 'success';

        } catch (Exception $e) {
            $conn->rollback();
            $_SESSION['message'] = "Error: " . $e->getMessage();
            $_SESSION['message_type'] = 'error';
        }
    }

    // 2. & 3. Agency ya Client Wallet mein Funds Add Karein
    elseif (isset($_POST['fund_type']) && ($_POST['fund_type'] === 'agency' || $_POST['fund_type'] === 'client')) {
        $fund_type = $_POST['fund_type'];
        $amount = (float)$_POST['amount'];

        if ($fund_type === 'agency') {
            $ad_account_id = (int)$_POST['ad_account_id'];
            $transaction_date = $_POST['transaction_date'];
            $description = $_POST['description'];

            $conn->begin_transaction();
            try {
                $stmt1 = $conn->prepare("INSERT INTO main_wallet_transactions (ad_account_id, transaction_date, amount, description) VALUES (?, ?, ?, ?)");
                $stmt1->bind_param("isds", $ad_account_id, $transaction_date, $amount, $description);
                if (!$stmt1->execute()) { throw new Exception($stmt1->error); }
                $stmt1->close();

                $stmt2 = $conn->prepare("UPDATE ad_accounts SET main_balance = main_balance + ? WHERE id = ?");
                $stmt2->bind_param("di", $amount, $ad_account_id);
                if (!$stmt2->execute()) { throw new Exception($stmt2->error); }
                $stmt2->close();
                
                $conn->commit();
                $_SESSION['message'] = "Successfully added ₹" . number_format($amount, 2) . " to the agency wallet.";
                $_SESSION['message_type'] = 'success';
            } catch (Exception $e) {
                $conn->rollback();
                $_SESSION['message'] = "Error adding funds: " . $e->getMessage();
                $_SESSION['message_type'] = 'error';
            }

        } elseif ($fund_type === 'client') {
            $client_id = (int)$_POST['client_id'];
            
            $stmt = $conn->prepare("UPDATE clients SET wallet_balance = wallet_balance + ? WHERE id = ?");
            $stmt->bind_param("di", $amount, $client_id);

            if ($stmt->execute()) {
                $_SESSION['message'] = "Successfully added ₹" . number_format($amount, 2) . " to the client's budget.";
                $_SESSION['message_type'] = 'success';
            } else {
                $_SESSION['message'] = "Error updating client budget: " . $stmt->error;
                $_SESSION['message_type'] = 'error';
            }
            $stmt->close();
        }
    }
    
    // 4. DELETE AD SPEND (Sirf Admin, with password check)
    elseif (isset($_POST['delete_spend']) && $is_admin) {
        $spend_id = $_POST['spend_id'];
        $admin_password = $_POST['admin_password'];
        $admin_id = $_SESSION['user_id'];

        // Admin password ko verify karein
        $stmt_pass = $conn->prepare("SELECT password FROM users WHERE id = ?");
        $stmt_pass->bind_param("i", $admin_id);
        $stmt_pass->execute();
        $result = $stmt_pass->get_result()->fetch_assoc();
        $hashed_password = $result['password'];
        $stmt_pass->close();

        if (password_verify($admin_password, $hashed_password)) {
            $conn->begin_transaction();
            try {
                // Spend ki details prapt karein
                $stmt_get = $conn->prepare("SELECT client_id, ad_account_id, ad_amount FROM ad_spends WHERE id = ?");
                $stmt_get->bind_param("i", $spend_id);
                $stmt_get->execute();
                $spend = $stmt_get->get_result()->fetch_assoc();
                $stmt_get->close();

                if($spend){
                    $client_id = $spend['client_id'];
                    $ad_account_id = $spend['ad_account_id'];
                    $ad_amount = $spend['ad_amount'];
                    
                    $acc_stmt = $conn->prepare("SELECT account_type FROM ad_accounts WHERE id = ?");
                    $acc_stmt->bind_param("i", $ad_account_id);
                    $acc_stmt->execute();
                    $account = $acc_stmt->get_result()->fetch_assoc();
                    $acc_stmt->close();

                    if ($account && $account['account_type'] == 'Client Wallet') {
                        $conn->query("UPDATE clients SET wallet_balance = wallet_balance + $ad_amount WHERE id = $client_id");
                    } else {
                        $conn->query("UPDATE ad_accounts SET main_balance = main_balance + $ad_amount WHERE id = $ad_account_id");
                    }

                    $stmt_delete = $conn->prepare("DELETE FROM ad_spends WHERE id = ?");
                    $stmt_delete->bind_param("i", $spend_id);
                    $stmt_delete->execute();
                    $stmt_delete->close();
                    
                    $conn->commit();
                    $_SESSION['message'] = "Ad spend deleted successfully and balance was adjusted.";
                    $_SESSION['message_type'] = 'success';
                } else {
                     throw new Exception("Ad spend record not found.");
                }
            } catch (Exception $e) {
                $conn->rollback();
                $_SESSION['message'] = "Error deleting spend: " . $e->getMessage();
                $_SESSION['message_type'] = 'error';
            }
        } else {
            $_SESSION['message'] = "Incorrect admin password. Deletion aborted.";
            $_SESSION['message_type'] = 'error';
        }
    }

    header("Location: manage_ads.php");
    exit();
}

// --- DATA FETCHING ---
$stats_start_date = $_GET['stats_start_date'] ?? date('Y-m-01');
$stats_end_date = $_GET['stats_end_date'] ?? date('Y-m-t');

$ad_accounts_result = $conn->query("SELECT * FROM ad_accounts");
$ad_accounts = [];
while($row = $ad_accounts_result->fetch_assoc()){
    $account_id = $row['id'];
    
    $spends_stmt = $conn->prepare("SELECT SUM(ad_amount) as total FROM ad_spends WHERE ad_account_id = ? AND ad_date BETWEEN ? AND ?");
    $spends_stmt->bind_param("iss", $account_id, $stats_start_date, $stats_end_date);
    $spends_stmt->execute();
    $row['total_spends'] = $spends_stmt->get_result()->fetch_assoc()['total'] ?? 0;
    $spends_stmt->close();

    $funds_stmt = $conn->prepare("SELECT SUM(amount) as total FROM main_wallet_transactions WHERE ad_account_id = ? AND transaction_date BETWEEN ? AND ?");
    $funds_stmt->bind_param("iss", $account_id, $stats_start_date, $stats_end_date);
    $funds_stmt->execute();
    $row['funds_added'] = $funds_stmt->get_result()->fetch_assoc()['total'] ?? 0;
    $funds_stmt->close();
    
    $ad_accounts[] = $row;
}

$all_clients_result = $conn->query("SELECT id, name, contact_person, wallet_balance FROM clients WHERE is_active = TRUE ORDER BY name ASC");
$all_clients = [];
$client_balances = [];
while ($row = $all_clients_result->fetch_assoc()) { 
    $all_clients[] = $row;
    $client_balances[$row['id']] = $row['wallet_balance'];
}
$client_balances_json = json_encode($client_balances);

$selected_client_wallet_id = $_GET['selected_client_wallet'] ?? 'all';
$client_wallet_stats = ['total_balance' => 0, 'total_spends' => 0];
if($selected_client_wallet_id != 'all' && is_numeric($selected_client_wallet_id)){
    $client_wallet_stats_stmt = $conn->prepare("SELECT wallet_balance FROM clients WHERE id = ?");
    $client_wallet_stats_stmt->bind_param("i", $selected_client_wallet_id);
    $client_wallet_stats_stmt->execute();
    $client_wallet_stats['total_balance'] = $client_wallet_stats_stmt->get_result()->fetch_assoc()['wallet_balance'] ?? 0;
    $client_wallet_stats_stmt->close();

    $client_account_id_result = $conn->query("SELECT id FROM ad_accounts WHERE account_type = 'Client Wallet' LIMIT 1");
    $client_account_id = $client_account_id_result->fetch_assoc()['id'];

    $client_spends_stmt = $conn->prepare("SELECT SUM(ad_amount) as total_spends FROM ad_spends WHERE ad_account_id = ? AND client_id = ? AND ad_date BETWEEN ? AND ?");
    $client_spends_stmt->bind_param("iiss", $client_account_id, $selected_client_wallet_id, $stats_start_date, $stats_end_date);
    $client_spends_stmt->execute();
    $client_wallet_stats['total_spends'] = $client_spends_stmt->get_result()->fetch_assoc()['total_spends'] ?? 0;
    $client_spends_stmt->close();
}

$page = $_GET['page'] ?? 1;
$page = is_numeric($page) ? (int)$page : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$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'] ?? '';

$params = [];
$param_types = '';
$count_sql = "SELECT COUNT(ad.id) FROM ad_spends ad WHERE 1=1";
$sql = "SELECT ad.*, c.name as client_name, ac.name as account_name 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 = ?";
    $count_sql .= " AND ad.client_id = ?";
    $params[] = $filter_client;
    $param_types .= 'i';
}
if($filter_account != 'all'){
    $sql .= " AND ad.ad_account_id = ?";
    $count_sql .= " AND ad.ad_account_id = ?";
    $params[] = $filter_account;
    $param_types .= 'i';
}
if(!empty($filter_start_date)){
    $sql .= " AND ad.ad_date >= ?";
    $count_sql .= " AND ad.ad_date >= ?";
    $params[] = $filter_start_date;
    $param_types .= 's';
}
if(!empty($filter_end_date)){
    $sql .= " AND ad.ad_date <= ?";
    $count_sql .= " AND ad.ad_date <= ?";
    $params[] = $filter_end_date;
    $param_types .= 's';
}

$count_stmt = $conn->prepare($count_sql);
if(!empty($params)){ $count_stmt->bind_param($param_types, ...$params); }
$count_stmt->execute();
$total_records = $count_stmt->get_result()->fetch_row()[0];
$total_pages = ceil($total_records / $limit);
$count_stmt->close();

$sql .= " ORDER BY ad.ad_date DESC, ad.id DESC LIMIT ? OFFSET ?";
$params_with_limit = $params;
$params_with_limit[] = $limit;
$params_with_limit[] = $offset;
$param_types_with_limit = $param_types . 'ii';

$stmt = $conn->prepare($sql);
if(!empty($params_with_limit)){ $stmt->bind_param($param_types_with_limit, ...$params_with_limit); }
$stmt->execute();
$ad_spends = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$total_spend_sum_query = "SELECT SUM(ad_amount) FROM ad_spends ad WHERE 1=1";
if($filter_client != 'all'){ $total_spend_sum_query .= " AND ad.client_id = " . (int)$filter_client; }
if($filter_account != 'all'){ $total_spend_sum_query .= " AND ad.ad_account_id = " . (int)$filter_account; }
if(!empty($filter_start_date)){ $total_spend_sum_query .= " AND ad.ad_date >= '" . $conn->real_escape_string($filter_start_date) . "'"; }
if(!empty($filter_end_date)){ $total_spend_sum_query .= " AND ad.ad_date <= '" . $conn->real_escape_string($filter_end_date) . "'"; }
$total_spend_sum = $conn->query($total_spend_sum_query)->fetch_row()[0] ?? 0;

$conn->close();

require_once 'header.php';
?>

<title>Ads Management - Digify OS</title>

<main class="p-6 md:p-10" x-data="adsManagement()">
    <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold text-gray-800">Ads Management Dashboard</h2>
    </div>
    
    <?php if (!empty($message)): ?>
        <div class="mb-6 p-4 rounded-lg <?php echo ($message_type == 'success') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <div class="bg-white p-6 rounded-lg shadow-lg mb-8">
        <div class="flex flex-col md:flex-row justify-between items-center mb-4">
            <h3 class="text-xl font-bold">Accounts Overview</h3>
            <form method="GET" action="manage_ads.php" class="flex items-center gap-2 mt-4 md:mt-0">
                <input type="hidden" name="selected_client_wallet" value="<?php echo htmlspecialchars($selected_client_wallet_id); ?>">
                <input type="date" name="stats_start_date" value="<?php echo htmlspecialchars($stats_start_date); ?>" class="border-gray-300 rounded-md shadow-sm text-sm">
                <input type="date" name="stats_end_date" value="<?php echo htmlspecialchars($stats_end_date); ?>" class="border-gray-300 rounded-md shadow-sm text-sm">
                <button type="submit" class="px-4 py-2 bg-indigo-600 text-white text-sm rounded-md">Filter</button>
            </form>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <?php foreach($ad_accounts as $account): ?>
                <?php if($account['account_type'] == 'Client Wallet') continue; ?>
                <div class="border rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-gray-800"><?php echo htmlspecialchars($account['name']); ?></h4>
                    
                    <?php if($account['account_type'] == 'Prepaid'): ?>
                        <p class="text-3xl font-bold text-green-600 mt-2">₹<?php echo number_format($account['main_balance'], 2); ?></p>
                        <p class="text-sm text-gray-500">Current Wallet Balance</p>
                        <div class="mt-4 pt-4 border-t space-y-2">
                            <div class="flex justify-between text-sm"><span class="text-gray-600">Funds Added:</span><span class="font-semibold text-green-700">+ ₹<?php echo number_format($account['funds_added'], 2); ?></span></div>
                            <div class="flex justify-between text-sm"><span class="text-gray-600">Total Spends:</span><span class="font-semibold text-red-700">- ₹<?php echo number_format($account['total_spends'], 2); ?></span></div>
                        </div>
                    <?php else: // Postpaid Account ?>
                        <p class="text-3xl font-bold text-red-600 mt-2">₹<?php echo number_format($account['total_spends'], 2); ?></p>
                        <p class="text-sm text-gray-500">Total Spends (<?php echo date('M d', strtotime($stats_start_date)) . ' - ' . date('M d', strtotime($stats_end_date)); ?>)</p>
                        <div class="mt-4 pt-4 border-t space-y-2">
                            <div class="flex justify-between text-sm"><span class="text-gray-600">Payments Made:</span><span class="font-semibold text-green-700">+ ₹<?php echo number_format($account['funds_added'], 2); ?></span></div>
                            <div class="flex justify-between text-sm"><span class="text-gray-600">Current Outstanding Due:</span><span class="font-semibold text-red-700">₹<?php echo number_format(abs($account['main_balance']), 2); ?></span></div>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
             <div class="border rounded-lg p-4">
                <h4 class="text-lg font-semibold text-gray-800">Client Wallet/Budget</h4>
                <form method="GET" action="manage_ads.php" class="mt-2">
                    <input type="hidden" name="stats_start_date" value="<?php echo htmlspecialchars($stats_start_date); ?>">
                    <input type="hidden" name="stats_end_date" value="<?php echo htmlspecialchars($stats_end_date); ?>">
                    <select name="selected_client_wallet" class="w-full border-gray-300 rounded-md shadow-sm text-sm" onchange="this.form.submit()">
                        <option value="all">-- Select a Client to View Budget --</option>
                        <?php foreach($all_clients as $c): ?>
                            <option value="<?php echo $c['id']; ?>" <?php if($selected_client_wallet_id == $c['id']) echo 'selected'; ?>><?php echo htmlspecialchars($c['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </form>
                <?php if($selected_client_wallet_id != 'all'): ?>
                    <p class="text-3xl font-bold text-blue-600 mt-2">₹<?php echo number_format($client_wallet_stats['total_balance'] ?? 0, 2); ?></p>
                    <p class="text-sm text-gray-500">Available Budget</p>
                    <div class="mt-4 pt-4 border-t space-y-2">
                        <div class="flex justify-between text-sm"><span class="text-gray-600">Total Spends from Wallet:</span><span class="font-semibold text-red-700">- ₹<?php echo number_format($client_wallet_stats['total_spends'] ?? 0, 2); ?></span></div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="bg-white p-6 rounded-lg shadow-lg mb-8">
        <div class="border-b border-gray-200 mb-6">
            <nav class="-mb-px flex space-x-8" aria-label="Tabs">
                <a href="#" @click.prevent="activeTab = 'addSpend'" :class="{ 'border-indigo-500 text-indigo-600': activeTab === 'addSpend', 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300': activeTab !== 'addSpend' }" class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">Add New Ad Spend</a>
                <a href="#" @click.prevent="activeTab = 'addFunds'" :class="{ 'border-indigo-500 text-indigo-600': activeTab === 'addFunds', 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300': activeTab !== 'addFunds' }" class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">Add Funds / Budget</a>
            </nav>
        </div>

        <div x-show="activeTab === 'addSpend'">
            <div class="bg-white" x-data="{ submitting: false, clientBalances: <?php echo $client_balances_json; ?>, selectedClient: '', get balance() { return this.selectedClient ? this.clientBalances[this.selectedClient] : '0.00' } }">
                <h3 class="text-xl font-bold mb-4">Record a New Ad Spend</h3>
                <form method="POST" action="manage_ads.php" @submit="submitting = true" class="space-y-4">
                    <div>
                        <div class="flex justify-between items-center">
                            <label class="text-sm font-medium text-gray-700">Client</label>
                            <span class="text-sm font-semibold text-green-600" x-show="selectedClient">Available Budget: ₹<span x-text="parseFloat(balance).toFixed(2)"></span></span>
                        </div>
                        <select name="client_id" required class="mt-1 w-full border-gray-300 rounded-md shadow-sm" x-model="selectedClient">
                            <option value="">-- Select Client --</option>
                            <?php foreach($all_clients as $c): ?>
                                <option value="<?php echo $c['id']; ?>"><?php echo htmlspecialchars($c['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div><label class="text-sm font-medium text-gray-700">Ad Account Used</label><select name="ad_account_id" required class="mt-1 w-full border-gray-300 rounded-md shadow-sm"><option value="">-- Select Account --</option><?php foreach($ad_accounts as $a): ?><option value="<?php echo $a['id']; ?>"><?php echo htmlspecialchars($a['name']); ?></option><?php endforeach; ?></select></div>
                    <div class="grid grid-cols-2 gap-4">
                        <div><label class="text-sm font-medium text-gray-700">Ad Date</label><input type="date" name="ad_date" required class="mt-1 w-full border-gray-300 rounded-md shadow-sm" value="<?php echo date('Y-m-d'); ?>"></div>
                        <div><label class="text-sm font-medium text-gray-700">Amount (₹)</label><input type="number" step="0.01" name="ad_amount" required class="mt-1 w-full border-gray-300 rounded-md shadow-sm"></div>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div><label class="text-sm font-medium text-gray-700">Ad Link</label><input type="url" name="ad_link" class="mt-1 w-full border-gray-300 rounded-md shadow-sm"></div>
                        <div><label class="text-sm font-medium text-gray-700">Duration (Days)</label><input type="number" name="duration_days" class="mt-1 w-full border-gray-300 rounded-md shadow-sm"></div>
                    </div>
                    <div>
                        <label class="text-sm font-medium text-gray-700">Remark</label>
                        <textarea name="remark" class="mt-1 w-full border-gray-300 rounded-md shadow-sm" rows="2" placeholder="Add any remark here..."></textarea>
                    </div>
                    <div class="flex justify-end"><button type="submit" name="add_spend" :disabled="submitting" class="px-6 py-2 bg-blue-600 text-white font-semibold rounded-lg shadow-md disabled:bg-gray-400"><span x-show="!submitting">Add Spend</span><span x-show="submitting">Saving...</span></button></div>
                </form>
            </div>
        </div>

        <div x-show="activeTab === 'addFunds'">
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                <div x-data="{ submitting: false }">
                    <h3 class="text-xl font-bold mb-4">Add Funds (Agency Wallet)</h3>
                    <form method="POST" action="manage_ads.php" @submit="submitting = true" class="space-y-4">
                        <input type="hidden" name="fund_type" value="agency">
                        <div><label>Ad Account</label><select name="ad_account_id" required class="mt-1 w-full border-gray-300 rounded-md shadow-sm"><?php foreach($ad_accounts as $a): ?><?php if($a['account_type'] != 'Client Wallet'): ?><option value="<?php echo $a['id']; ?>"><?php echo htmlspecialchars($a['name']); ?></option><?php endif; ?><?php endforeach; ?></select></div>
                        <div class="grid grid-cols-2 gap-4">
                            <div><label>Amount (₹)</label><input type="number" step="0.01" name="amount" required class="mt-1 w-full border-gray-300 rounded-md shadow-sm"></div>
                            <div><label>Date</label><input type="date" name="transaction_date" required class="mt-1 w-full border-gray-300 rounded-md shadow-sm" value="<?php echo date('Y-m-d'); ?>"></div>
                        </div>
                        <div><label>Description</label><input type="text" name="description" placeholder="e.g., Credit Card Top-up" class="mt-1 w-full border-gray-300 rounded-md shadow-sm"></div>
                        <div class="flex justify-end"><button type="submit" name="add_funds" :disabled="submitting" class="px-6 py-2 bg-green-600 text-white rounded-lg disabled:bg-gray-400"><span x-show="!submitting">Add Funds/Payment</span><span x-show="submitting">Saving...</span></button></div>
                    </form>
                </div>
                <div class="border-t lg:border-t-0 lg:border-l lg:pl-8" x-data="{ submitting: false }">
                    <h3 class="text-xl font-bold mb-4">Add Funds (Client Wallet/Budget)</h3>
                    <form method="POST" action="manage_ads.php" @submit="submitting = true" class="space-y-4">
                        <input type="hidden" name="fund_type" value="client">
                        <div><label class="text-sm font-medium text-gray-700">Client</label><select name="client_id" required class="mt-1 w-full border-gray-300 rounded-md shadow-sm"><option value="">-- Select Client --</option><?php foreach($all_clients as $c): ?><option value="<?php echo $c['id']; ?>"><?php echo htmlspecialchars($c['name']); ?></option><?php endforeach; ?></select></div>
                        <div><label class="text-sm font-medium text-gray-700">Amount (₹)</label><input type="number" step="0.01" name="amount" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"></div>
                        <div class="flex justify-end"><button type="submit" name="add_funds" :disabled="submitting" class="w-full px-6 py-2 bg-green-600 text-white rounded-lg disabled:bg-gray-400"><span x-show="!submitting">Add Client Funds</span><span x-show="submitting">Saving...</span></button></div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="bg-white rounded-lg shadow-lg p-6 mt-8">
        <div class="flex flex-col md:flex-row justify-between items-center mb-4">
            <h3 class="text-xl font-bold mb-4">Ad Spend History</h3>
            <div class="flex items-center gap-4">
                <form method="GET" action="export_full_ads_report.php" target="_blank">
                    <button type="submit" class="px-4 py-2 bg-green-600 text-white text-sm rounded-md hover:bg-green-700">Export Full Report (CSV)</button>
                </form>
                <button @click="exportPDF()" :disabled="!isClientSelectedForReport()" class="px-4 py-2 bg-red-600 text-white text-sm rounded-md hover:bg-red-700 disabled:bg-gray-400 disabled:cursor-not-allowed">Export to PDF</button>
            </div>
        </div>
        <form method="GET" action="manage_ads.php" class="mb-4">
            <div class="grid grid-cols-1 md:grid-cols-5 gap-4 items-end">
                <div><label class="text-sm font-medium text-gray-700">Client</label><select name="filter_client" class="mt-1 w-full border-gray-300 rounded-md shadow-sm"><option value="all">All Clients</option><?php foreach($all_clients as $c): ?><option value="<?php echo $c['id']; ?>" <?php if($filter_client == $c['id']) echo 'selected'; ?>><?php echo htmlspecialchars($c['name']); ?></option><?php endforeach; ?></select></div>
                <div><label class="text-sm font-medium text-gray-700">Account</label><select name="filter_account" class="mt-1 w-full border-gray-300 rounded-md shadow-sm"><option value="all">All Accounts</option><?php foreach($ad_accounts as $a): ?><option value="<?php echo $a['id']; ?>" <?php if($filter_account == $a['id']) echo 'selected'; ?>><?php echo htmlspecialchars($a['name']); ?></option><?php endforeach; ?></select></div>
                <div><label class="text-sm font-medium text-gray-700">Start Date</label><input type="date" name="filter_start_date" value="<?php echo htmlspecialchars($filter_start_date); ?>" class="mt-1 w-full border-gray-300 rounded-md shadow-sm"></div>
                <div><label class="text-sm font-medium text-gray-700">End Date</label><input type="date" name="filter_end_date" value="<?php echo htmlspecialchars($filter_end_date); ?>" class="mt-1 w-full border-gray-300 rounded-md shadow-sm"></div>
                <button type="submit" class="w-full px-4 py-2 bg-indigo-600 text-white rounded-lg">Filter History</button>
            </div>
        </form>
        <div class="overflow-y-auto max-h-96">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50 sticky top-0">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Ad Date</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Client</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Account</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Amount</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Duration</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Remark</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Ad Link</th>
                        <?php if ($is_admin): ?><th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Actions</th><?php endif; ?>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if(empty($ad_spends)): ?>
                        <tr><td colspan="8" class="p-8 text-center text-gray-500">No ad spends found for the selected criteria.</td></tr>
                    <?php else: ?>
                        <?php foreach($ad_spends as $spend): ?>
                            <tr>
                                <td class="px-4 py-4 text-sm"><?php echo date("d M, Y", strtotime($spend['ad_date'])); ?></td>
                                <td class="px-4 py-4 text-sm font-semibold"><?php echo htmlspecialchars($spend['client_name']); ?></td>
                                <td class="px-4 py-4 text-sm"><?php echo htmlspecialchars($spend['account_name']); ?></td>
                                <td class="px-4 py-4 font-semibold text-red-600">₹<?php echo number_format($spend['ad_amount'], 2); ?></td>
                                <td class="px-4 py-4 text-sm"><?php echo htmlspecialchars($spend['duration_days']); ?> days</td>
                                <td class="px-4 py-4 text-sm" style="white-space: pre-wrap; word-break: break-word;"><?php echo htmlspecialchars($spend['remark']); ?></td>
                                <td class="px-4 py-4 text-sm"><a href="<?php echo htmlspecialchars($spend['ad_link']); ?>" target="_blank" class="text-blue-600 hover:underline">View Ad</a></td>
                                <?php if ($is_admin): ?>
                                <td class="px-4 py-4 text-sm">
                                    <button @click="isDeleteModalOpen = true; currentSpend = JSON.parse('<?php echo addslashes(json_encode($spend)); ?>')" class="text-red-600 hover:text-red-900 ml-2">Delete</button>
                                </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
                <?php if($total_records > 0): ?>
                <tfoot class="bg-gray-100">
                    <tr>
                        <td colspan="3" class="px-4 py-3 text-right font-semibold text-gray-700">Total for this selection:</td>
                        <td colspan="5" class="px-4 py-3 font-bold text-red-700">₹<?php echo number_format($total_spend_sum, 2); ?></td>
                    </tr>
                </tfoot>
                <?php endif; ?>
            </table>
        </div>
        <div class="mt-4 flex justify-between items-center">
            <span class="text-sm text-gray-700">
                Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $total_records); ?> of <?php echo $total_records; ?> records
            </span>
            <div class="space-x-2">
                <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>&<?php echo http_build_query($_GET); ?>" class="px-3 py-1 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 text-sm">&laquo; Previous</a>
                <?php endif; ?>
                <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>&<?php echo http_build_query($_GET); ?>" class="ml-2 px-3 py-1 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 text-sm">Next &raquo;</a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</main>

<!-- Delete Modal -->
<div x-show="isDeleteModalOpen" x-transition class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center z-40" style="display: none;">
    <div class="bg-white rounded-lg shadow-xl p-8 w-full max-w-lg" @click.away="isDeleteModalOpen = false">
        <h3 class="text-xl font-semibold mb-4 text-red-700">Confirm Deletion</h3>
        <p>Are you sure you want to delete this ad spend record? The amount will be reversed from the corresponding wallet. This action cannot be undone.</p>
         <p class="text-sm text-gray-700 mt-4"><b>Details:</b> <span x-text="currentSpend.client_name"></span> - <b x-text="'₹' + parseFloat(currentSpend.ad_amount).toFixed(2)"></b></p>
        <form method="POST" action="manage_ads.php">
            <input type="hidden" name="spend_id" :value="currentSpend.id">
            <div class="mt-4">
                <label for="admin_password" class="block text-sm font-medium text-gray-700">Enter Your Admin Password</label>
                <input type="password" name="admin_password" id="admin_password" required class="w-full border-gray-300 rounded-md mt-1" placeholder="Enter password to confirm deletion">
            </div>
            <div class="flex justify-end mt-8">
                <button type="button" @click="isDeleteModalOpen = false" class="px-4 py-2 border rounded-md mr-2">Cancel</button>
                <button type="submit" name="delete_spend" class="px-4 py-2 bg-red-600 text-white rounded-md font-semibold">Confirm Delete</button>
            </div>
        </form>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.23/jspdf.plugin.autotable.min.js"></script>

<script>
function adsManagement() {
    return {
        activeTab: 'addSpend',
        isDeleteModalOpen: false, 
        currentSpend: {},
        isClientSelectedForReport() {
            const urlParams = new URLSearchParams(window.location.search);
            const clientId = urlParams.get('filter_client');
            return clientId && clientId !== 'all';
        },
        exportPDF() {
            if (!this.isClientSelectedForReport()) {
                alert('Please filter by a specific client to generate a PDF report.');
                return;
            }

            const { jsPDF } = window.jspdf;
            const doc = new jsPDF();

            const allClients = <?php echo json_encode($all_clients); ?>;
            const adSpends = <?php echo json_encode($ad_spends); ?>;
            const urlParams = new URLSearchParams(window.location.search);
            const clientId = urlParams.get('filter_client');
            const client = allClients.find(c => c.id == clientId);
            
            if (!client) {
                alert('Could not find client details.');
                return;
            }
            
            const startDate = urlParams.get('filter_start_date') || 'N/A';
            const endDate = urlParams.get('filter_end_date') || 'N/A';

            // PDF Header
            doc.setFillColor(128, 0, 0); 
            doc.rect(0, 0, 210, 35, 'F');
            doc.setFontSize(22);
            doc.setFont('helvetica', 'bold');
            doc.setTextColor(255, 255, 255);
            doc.text('Digify Infotech Ads Report', 105, 18, { align: 'center' });
            doc.setFontSize(11);
            doc.setFont('helvetica', 'normal');
            doc.text(`Report for period: ${startDate} to ${endDate}`, 105, 26, { align: 'center' });

            // Client Details
            doc.setFontSize(12);
            doc.setFont('helvetica', 'bold');
            doc.setTextColor(50);
            doc.text('Client Information', 14, 48);
            doc.setLineWidth(0.5);
            doc.line(14, 50, 196, 50);

            doc.autoTable({
                body: [
                    [{ content: 'Client Name:', styles: { fontStyle: 'bold', cellWidth: 40 } }, client.name],
                    [{ content: 'Contact Person:', styles: { fontStyle: 'bold', cellWidth: 40 } }, client.contact_person || 'N/A'],
                    [{ content: 'Ads Estimated Budget:', styles: { fontStyle: 'bold', cellWidth: 40 } }, `₹ ${parseFloat(client.wallet_balance).toFixed(2)}`],
                ],
                startY: 53,
                theme: 'plain',
                styles: { fontSize: 10, font: 'helvetica' },
            });

            const tableColumn = ["Date", "Account", "Amount (₹)", "Duration", "Remark", "Ad Link"];
            const tableRows = [];

            adSpends.forEach(spend => {
                const spendData = [
                    new Date(spend.ad_date).toLocaleDateString("en-GB"),
                    spend.account_name,
                    `₹ ${parseFloat(spend.ad_amount).toFixed(2)}`,
                    `${spend.duration_days || 'N/A'} days`,
                    spend.remark || 'N/A',
                    spend.ad_link ? 'See Ad' : 'N/A'
                ];
                tableRows.push(spendData);
            });

            const lastTableY = doc.lastAutoTable.finalY;

            doc.autoTable({
                head: [tableColumn],
                body: tableRows,
                startY: lastTableY + 10,
                theme: 'grid',
                headStyles: { fillColor: [128, 0, 0], font: 'helvetica', fontStyle: 'bold' },
                columnStyles: {
                    2: { halign: 'right' },
                    5: { textColor: [0, 0, 255], fontStyle: 'italic' } 
                },
                didDrawCell: function (data) {
                    if (data.column.dataKey === 5 && data.cell.raw === 'See Ad') {
                        const adLink = adSpends[data.row.index].ad_link;
                        if (adLink) {
                            doc.link(data.cell.x, data.cell.y, data.cell.width, data.cell.height, { url: adLink });
                        }
                    }
                }
            });

            const finalY = doc.lastAutoTable.finalY;
            const totalSpend = adSpends.reduce((sum, spend) => sum + parseFloat(spend.ad_amount), 0);
            
            doc.setFillColor(245, 245, 245);
            doc.roundedRect(14, finalY + 15, 182, 20, 3, 3, 'F');
            
            doc.setFontSize(12);
            doc.setFont('helvetica', 'bold');
            doc.setTextColor(50);
            doc.text('Total Spend for this Period:', 20, finalY + 27);
            
            doc.setFontSize(16);
            doc.setTextColor(128, 0, 0);
            doc.text(`₹ ${totalSpend.toFixed(2)}`, 194, finalY + 27, { align: 'right' });

            const pageCount = doc.internal.getNumberOfPages();
            for(let i = 1; i <= pageCount; i++) {
                doc.setPage(i);
                doc.setFontSize(9);
                doc.setTextColor(150);
                doc.text('Page ' + String(i) + ' of ' + String(pageCount), 105, 290, {align: 'center'});
            }

            doc.save(`Ad_Report_${client.name.replace(/ /g,"_")}.pdf`);
        }
    }
}
</script>

<?php
// फुटर को शामिल करें
require_once 'footer.php';
?>

