<?php
// हेडर को शामिल करें
require_once 'header.php';

// सुरक्षा जांच: केवल एडमिन और मैनेजर ही इस पेज को देख सकते हैं।
if (!userHasRole(['Admin', 'Manager'])) {
    header("Location: dashboard.php");
    exit();
}

$message = '';
$message_type = '';

// --- FORM SUBMISSION LOGIC ---

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 1. Add New Ad Spend
    if (isset($_POST['add_spend'])) {
        $client_id = $_POST['client_id'];
        $ad_account_id = $_POST['ad_account_id'];
        $ad_date = $_POST['ad_date'];
        $ad_amount = (float)$_POST['ad_amount'];
        $ad_link = $_POST['ad_link'];
        $duration_days = !empty($_POST['duration_days']) ? (int)$_POST['duration_days'] : NULL;
        $month_year = date('Y-m', strtotime($ad_date));

        $conn->begin_transaction();
        try {
            $stmt1 = $conn->prepare("INSERT INTO ad_spends (client_id, ad_account_id, ad_date, ad_amount, ad_link, duration_days) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt1->bind_param("iisdsi", $client_id, $ad_account_id, $ad_date, $ad_amount, $ad_link, $duration_days);
            $stmt1->execute();
            $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();
            
            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");
            }
            $acc_stmt->close();

            $conn->commit();
            $message = "Ad spend of ₹" . number_format($ad_amount, 2) . " recorded successfully!";
            $message_type = 'success';
        } catch (mysqli_sql_exception $exception) {
            $conn->rollback();
            $message = "Error recording spend: " . $exception->getMessage();
            $message_type = 'error';
        }
    }

    // 2. Add Funds to Agency Wallet
    elseif (isset($_POST['add_agency_funds'])) {
        $ad_account_id = $_POST['ad_account_id'];
        $amount = (float)$_POST['amount'];
        $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);
            $stmt1->execute();
            $stmt1->close();

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

    // 3. Add Funds to Client Wallet
    elseif (isset($_POST['add_client_funds'])) {
        $client_id_for_funds = $_POST['client_id'];
        $amount = (float)$_POST['amount'];
        
        $stmt = $conn->prepare("UPDATE clients SET wallet_balance = wallet_balance + ? WHERE id = ?");
        $stmt->bind_param("di", $amount, $client_id_for_funds);
        if($stmt->execute()){
            $message = "Successfully added ₹" . number_format($amount, 2) . " to the client's wallet.";
            $message_type = 'success';
        } else {
            $message = "Error adding funds to client wallet: " . $stmt->error;
            $message_type = 'error';
        }
        $stmt->close();
    }
}

// --- DATA FETCHING (Yeh section naye data ko reflect karega) ---
$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, 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);

// Client Wallet Stats
$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();
}

$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 = '';
$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 = ?"; $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();
$ad_spends = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$total_spend_sum = array_sum(array_column($ad_spends, 'ad_amount'));

$conn->close();
?>

<title>Ads Management - Digify OS</title>
<h2 class="text-xl font-bold text-gray-800">Ads Management Dashboard</h2>

<main class="p-6 md:p-10">
    
    <?php if (!empty($message)): ?>
        <div class="mb-4 p-4 rounded <?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</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 Wallet --</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 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">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="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
        <div class="bg-white p-6 rounded-lg shadow-lg" 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">Add 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 Balance: ₹<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</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 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 class="bg-white p-6 rounded-lg shadow-lg">
            <div class="space-y-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">
                        <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_agency_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 pt-8" x-data="{ submitting: false }">
                    <h3 class="text-xl font-bold mb-4">Add Funds (Client Wallet)</h3>
                    <form method="POST" action="manage_ads.php" @submit="submitting = true" class="grid grid-cols-1 sm:grid-cols-3 gap-4 items-end">
                        <div class="sm:col-span-1"><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 class="sm:col-span-1"><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="sm:col-span-1"><button type="submit" name="add_client_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">
        <h3 class="text-xl font-bold mb-4">Ad Spend History</h3>
        <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">Ad Link</th></tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if(empty($ad_spends)): ?>
                        <tr><td colspan="6" 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"><a href="<?php echo htmlspecialchars($spend['ad_link']); ?>" target="_blank" class="text-blue-600 hover:underline">View Ad</a></td></tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
                <?php if(!empty($ad_spends)): ?>
                <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="3" 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>
</main>

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