<?php
// ১. কনফিগারেশন এবং সেশন স্টার্ট
mysqli_report(MYSQLI_REPORT_OFF); 
session_start();

require '../includes/auth_session.php';
require '../includes/db.php';
require '../includes/functions.php';

// =========================================================
// 2. DATE RANGE & FILTERS (Default: Lifetime)
// =========================================================
$filter_period = $_GET['period'] ?? 'lifetime'; 
$start_date = $_GET['start'] ?? date('Y-m-d');
$end_date = $_GET['end'] ?? date('Y-m-d');

if ($filter_period == 'today') {
    $start_date = $end_date = date('Y-m-d');
} elseif ($filter_period == 'yesterday') {
    $start_date = $end_date = date('Y-m-d', strtotime('-1 days'));
} elseif ($filter_period == 'week') {
    $start_date = date('Y-m-d', strtotime('monday this week'));
    $end_date = date('Y-m-d', strtotime('sunday this week'));
} elseif ($filter_period == 'month') {
    $start_date = date('Y-m-01');
    $end_date = date('Y-m-d');
}

// =========================================================
// 3. ACTION HANDLER
// =========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'], $_POST['trx_id'])) {
    
    $tid = intval($_POST['trx_id']);
    $action = $_POST['action']; 
    $admin_id = $_SESSION['admin_id'] ?? 0;

    if ($action === 'approve') {
        $t_query = $conn->query("SELECT * FROM transactions_fake WHERE id=$tid");
        $t = $t_query->fetch_assoc();

        if ($t && $t['status'] === 'pending') {
            $update_sql = "UPDATE transactions_fake SET status='approved', agent_id=$admin_id WHERE id=$tid AND status='pending'";
            $conn->query($update_sql);

            if ($conn->affected_rows > 0) {
                $user_id = $t['user_id'];
                $amount = floatval($t['amount']);
                
                if ($t['type'] === 'deposit') {
                    $bonus_amount = 0; $wager_ratio = 1; 

                    $user_info = $conn->query("SELECT custom_wager_ratio FROM users WHERE id=$user_id")->fetch_assoc();
                    $settings = $conn->query("SELECT deposit_bonus_percent, normal_wager_ratio FROM settings WHERE id=1")->fetch_assoc();
                    
                    $promo_id = isset($t['promo_id']) ? intval($t['promo_id']) : 0;
                    if ($promo_id > 0) {
                        $promo_q = $conn->query("SELECT bonus_percent, wager_multiplier, bonus_amount FROM promotions WHERE id=$promo_id");
                        if ($promo_q && $promo_q->num_rows > 0) {
                            $promo = $promo_q->fetch_assoc();
                            $percent = (isset($promo['bonus_percent']) && $promo['bonus_percent'] > 0) ? floatval($promo['bonus_percent']) : floatval(preg_replace('/[^0-9.]/', '', $promo['bonus_amount'] ?? '0'));
                            if ($percent > 0) $bonus_amount = ($amount * $percent) / 100;
                            if (!empty($promo['wager_multiplier'])) $wager_ratio = floatval($promo['wager_multiplier']);
                        }
                    } else {
                        $wager_ratio = (!empty($user_info['custom_wager_ratio']) && $user_info['custom_wager_ratio'] > 0) ? floatval($user_info['custom_wager_ratio']) : floatval($settings['normal_wager_ratio'] ?? 1);
                        if (!empty($settings['deposit_bonus_percent'])) $bonus_amount = ($amount * floatval($settings['deposit_bonus_percent'])) / 100;
                    }

                    $total_money = $amount + $bonus_amount;
                    $target_add = $total_money * $wager_ratio;
                    $conn->query("UPDATE users SET balance = balance + $total_money, turnover_target = turnover_target + $target_add WHERE id = $user_id");
                }
                header("Location: finance.php?msg=success"); exit();
            }
        }
    } elseif ($action === 'reject') {
        $update_sql = "UPDATE transactions_fake SET status='rejected', agent_id=$admin_id WHERE id=$tid AND status='pending'";
        $conn->query($update_sql);
        if ($conn->affected_rows > 0) {
            $t = $conn->query("SELECT * FROM transactions_fake WHERE id=$tid")->fetch_assoc();
            if ($t && $t['type'] === 'withdraw') {
                $conn->query("UPDATE users SET balance = balance + {$t['amount']} WHERE id={$t['user_id']}");
            }
            header("Location: finance.php?msg=rejected"); exit();
        }
    }
    header("Location: finance.php?msg=already_processed"); exit();
}

// =========================================================
// 4. BUILD QUERY & FILTERS
// =========================================================
$search_query = isset($_GET['q']) ? $conn->real_escape_string($_GET['q']) : '';
$status_filter = $_GET['status'] ?? 'all';
$type_filter = $_GET['type'] ?? 'all';
$agent_filter = $_GET['agent'] ?? 'all';

$where_clauses = [];
if (!empty($search_query)) {
    $where_clauses[] = "(t.transaction_id LIKE '%$search_query%' OR u.username LIKE '%$search_query%' OR ag_u.username LIKE '%$search_query%')";
} else {
    if ($filter_period != 'lifetime') { $where_clauses[] = "DATE(t.created_at) BETWEEN '$start_date' AND '$end_date'"; }
}

if ($status_filter != 'all') $where_clauses[] = "t.status = '$status_filter'";
if ($type_filter != 'all') $where_clauses[] = "t.type = '$type_filter'";
if ($agent_filter != 'all') {
    if ($agent_filter == 'system') $where_clauses[] = "t.agent_id = 0";
    else $where_clauses[] = "t.agent_id = " . intval($agent_filter);
}

$where_sql = count($where_clauses) > 0 ? "WHERE " . implode(' AND ', $where_clauses) : "";

// জটিল কুয়েরি ফিক্স: প্লেয়ারের নির্ধারিত এজেন্টের নাম (ag_u.username) তুলে আনা হচ্ছে
$sql = "SELECT t.*, u.username, u.custom_wager_ratio, 
        proc_ag.name as proc_agent_name, 
        ag_u.username as assigned_agent_name,
        p.title as promo_title, p.bonus_percent as promo_percent, p.bonus_amount as promo_desc, p.wager_multiplier as promo_wager
        FROM transactions_fake t 
        LEFT JOIN users u ON t.user_id = u.id 
        LEFT JOIN agents proc_ag ON t.agent_id = proc_ag.id 
        LEFT JOIN agents ag ON u.agent_id = ag.id 
        LEFT JOIN users ag_u ON ag.user_id = ag_u.id
        LEFT JOIN promotions p ON (t.promo_id IS NOT NULL AND t.promo_id = p.id)
        $where_sql 
        ORDER BY t.created_at DESC";

$result = $conn->query($sql);

$stats_sql = "SELECT 
    SUM(CASE WHEN type='deposit' AND status='approved' THEN amount ELSE 0 END) as total_dep,
    SUM(CASE WHEN type='withdraw' AND status='approved' THEN amount ELSE 0 END) as total_wd,
    COUNT(CASE WHEN status='pending' THEN 1 END) as pending_count
    FROM transactions_fake t $where_sql";
$stats = $conn->query($stats_sql)->fetch_assoc();

$risk_alerts = $conn->query("SELECT wallet_number, COUNT(DISTINCT user_id) as user_count, GROUP_CONCAT(DISTINCT u.username) as users FROM transactions_fake t LEFT JOIN users u ON t.user_id = u.id WHERE type='withdraw' AND wallet_number IS NOT NULL AND wallet_number != '' GROUP BY wallet_number HAVING user_count > 1");
$agents_list = $conn->query("SELECT id, name FROM agents");
$global_settings = $conn->query("SELECT deposit_bonus_percent, normal_wager_ratio FROM settings WHERE id=1")->fetch_assoc();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Finance Controller</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; background-color: #f8fafc; }
        .input-border { border: 2px solid #e2e8f0; }
        .input-border:focus { border-color: #6366f1; outline: none; }
        .rotate-btn:active i { transform: rotate(180deg); transition: 0.3s; }
    </style>
</head>
<body class="text-slate-800">

    <?php include '../includes/sidebar_admin.php'; ?>

    <main class="lg:ml-64 p-4 lg:p-8 min-h-screen">
        
        <div class="flex flex-col md:flex-row justify-between items-center mb-8 gap-4">
            <div>
                <h1 class="text-3xl font-black text-slate-900">Finance Controller</h1>
                <p class="text-slate-500">Real-time deposit and withdrawal monitoring.</p>
            </div>
            
            <div class="flex items-center gap-3 w-full md:w-auto">
                <button onclick="location.reload()" class="rotate-btn bg-white p-3 rounded-xl border-2 border-slate-200 shadow-sm text-slate-600 hover:text-indigo-600 transition-all">
                    <i class="fas fa-sync-alt"></i>
                </button>
                <form method="GET" class="relative flex-1 md:w-64">
                    <input type="text" name="q" value="<?php echo htmlspecialchars($search_query); ?>" placeholder="Search TrxID, User..." 
                           class="w-full pl-10 pr-4 py-2.5 rounded-xl input-border shadow-sm">
                    <i class="fas fa-search absolute left-3.5 top-3.5 text-slate-400"></i>
                </form>
            </div>
        </div>

        <?php if(isset($_GET['msg'])): ?>
            <div class="p-4 mb-6 rounded-xl font-bold <?php echo ($_GET['msg']=='success') ? 'bg-emerald-100 text-emerald-800' : 'bg-amber-100 text-amber-800'; ?>">
                <i class="fas fa-info-circle mr-2"></i>
                <?php 
                    if($_GET['msg'] == 'success') echo "Transaction Processed Successfully!"; 
                    elseif($_GET['msg'] == 'rejected') echo "Transaction Rejected.";
                    else echo "Already processed.";
                ?>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div class="bg-white p-6 rounded-3xl shadow-sm border border-slate-100">
                <p class="text-xs font-bold text-slate-400 uppercase mb-2">Total Deposits</p>
                <h3 class="text-3xl font-black text-emerald-600">৳<?php echo number_format($stats['total_dep']); ?></h3>
            </div>
            <div class="bg-white p-6 rounded-3xl shadow-sm border border-slate-100">
                <p class="text-xs font-bold text-slate-400 uppercase mb-2">Total Withdraws</p>
                <h3 class="text-3xl font-black text-rose-600">৳<?php echo number_format($stats['total_wd']); ?></h3>
            </div>
            <div class="bg-slate-900 p-6 rounded-3xl shadow-xl text-white">
                <p class="text-xs font-bold text-slate-500 uppercase mb-2">Pending</p>
                <h3 class="text-3xl font-black text-amber-400"><?php echo $stats['pending_count']; ?> Requests</h3>
            </div>
        </div>

        <div class="bg-white p-6 rounded-3xl border-2 border-slate-100 mb-8 shadow-sm">
            <form method="GET" class="flex flex-wrap gap-6 items-end">
                <div class="flex-1 min-w-[180px]">
                    <label class="text-[10px] font-black text-slate-400 uppercase block mb-2">Period</label>
                    <select name="period" onchange="this.form.submit()" class="w-full input-border rounded-xl text-sm p-2.5 bg-slate-50">
                        <option value="lifetime" <?php if($filter_period=='lifetime') echo 'selected'; ?>>Lifetime (All)</option>
                        <option value="month" <?php if($filter_period=='month') echo 'selected'; ?>>This Month</option>
                        <option value="week" <?php if($filter_period=='week') echo 'selected'; ?>>This Week</option>
                        <option value="today" <?php if($filter_period=='today') echo 'selected'; ?>>Today</option>
                        <option value="custom" <?php if($filter_period=='custom') echo 'selected'; ?>>Custom...</option>
                    </select>
                </div>

                <div class="flex-1 min-w-[280px] <?php echo ($filter_period != 'custom') ? 'opacity-30 pointer-events-none' : ''; ?>">
                    <label class="text-[10px] font-black text-slate-400 uppercase block mb-2">Calendar Range</label>
                    <div class="flex items-center gap-2">
                        <input type="date" name="start" value="<?php echo $start_date; ?>" class="w-full input-border rounded-xl text-sm p-2">
                        <span class="text-slate-400">-</span>
                        <input type="date" name="end" value="<?php echo $end_date; ?>" class="w-full input-border rounded-xl text-sm p-2">
                    </div>
                </div>

                <div class="w-full md:w-auto flex gap-4">
                    <div>
                        <label class="text-[10px] font-black text-slate-400 uppercase block mb-2">Status</label>
                        <select name="status" class="w-full input-border rounded-xl text-sm p-2.5">
                            <option value="all">All</option>
                            <option value="pending" <?php if($status_filter=='pending') echo 'selected'; ?>>Pending</option>
                            <option value="approved" <?php if($status_filter=='approved') echo 'selected'; ?>>Approved</option>
                        </select>
                    </div>
                    <div>
                        <label class="text-[10px] font-black text-slate-400 uppercase block mb-2">Agent</label>
                        <select name="agent" class="w-full input-border rounded-xl text-sm p-2.5">
                            <option value="all">All</option>
                            <?php $agents_list->data_seek(0); while($ag = $agents_list->fetch_assoc()): ?>
                                <option value="<?php echo $ag['id']; ?>" <?php if($agent_filter==$ag['id']) echo 'selected'; ?>><?php echo htmlspecialchars($ag['name']); ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>

                <button type="submit" class="bg-slate-900 text-white px-8 py-3 rounded-xl text-sm font-bold hover:bg-black transition-all">Filter</button>
            </form>
        </div>

        <div class="bg-white rounded-[2.5rem] shadow-sm border border-slate-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full text-left text-sm">
                    <thead>
                        <tr class="bg-slate-50 border-b border-slate-100">
                            <th class="px-6 py-5 text-slate-400 font-bold uppercase text-[10px]">User & Assigned Agent</th>
                            <th class="px-6 py-5 text-slate-400 font-bold uppercase text-[10px]">Transaction Details</th>
                            <th class="px-6 py-5 text-slate-400 font-bold uppercase text-[10px] bg-amber-50/50">Wager/Bonus</th>
                            <th class="px-6 py-5 text-slate-400 font-bold uppercase text-[10px]">Status & Processor</th>
                            <th class="px-6 py-4 text-right text-[10px]">Action</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        <?php if($result->num_rows > 0): while($row = $result->fetch_assoc()): ?>
                            <tr class="hover:bg-slate-50/50 transition-all">
                                <td class="px-6 py-5">
                                    <div class="font-bold text-slate-900 text-base"><?php echo htmlspecialchars($row['username']); ?></div>
                                    <div class="flex items-center gap-1.5 mt-1">
                                        <i class="fas fa-user-tie text-indigo-400 text-[10px]"></i>
                                        <span class="text-[11px] font-bold text-indigo-600 uppercase">
                                            Agent: <?php echo !empty($row['assigned_agent_name']) ? htmlspecialchars($row['assigned_agent_name']) : '<span class="text-slate-300">Not Assigned</span>'; ?>
                                        </span>
                                    </div>
                                </td>
                                
                                <td class="px-6 py-5">
                                    <div class="flex items-center gap-2 mb-1.5">
                                        <span class="text-[9px] font-black px-1.5 py-0.5 rounded uppercase <?php echo $row['type']=='deposit'?'bg-emerald-100 text-emerald-700':'bg-rose-100 text-rose-700'; ?>">
                                            <?php echo $row['type']; ?>
                                        </span>
                                        <span class="font-black text-slate-900 text-lg">৳<?php echo number_format($row['amount']); ?></span>
                                    </div>
                                    <div class="text-xs font-bold text-slate-500 uppercase tracking-tighter">
                                        <?php echo $row['method']; ?> <span class="text-slate-300 mx-1">•</span> <?php echo $row['wallet_number']; ?>
                                    </div>
                                    <div class="text-[10px] text-slate-400 mt-1 uppercase">Time: <?php echo date('d M, h:i A', strtotime($row['created_at'])); ?></div>
                                </td>

                                <td class="px-6 py-5 bg-amber-50/20">
                                    <?php if($row['type'] == 'deposit'): ?>
                                        <div class="text-[11px] font-bold text-slate-500">Bonus: <span class="text-emerald-600"><?php echo !empty($row['promo_title']) ? $row['promo_title'] : 'None'; ?></span></div>
                                        <div class="text-[11px] font-bold text-slate-500 mt-1">Wager: <span class="text-rose-600"><?php echo !empty($row['promo_wager']) ? $row['promo_wager'] : ($global_settings['normal_wager_ratio'] ?? '1'); ?>x</span></div>
                                    <?php else: ?>
                                        <span class="text-slate-300 italic text-xs">N/A</span>
                                    <?php endif; ?>
                                </td>

                                <td class="px-6 py-5">
                                    <span class="px-2.5 py-1 rounded-full text-[10px] font-black uppercase tracking-widest <?php echo $row['status']=='approved'?'bg-emerald-100 text-emerald-700':($row['status']=='rejected'?'bg-rose-100 text-rose-700':'bg-amber-100 text-amber-700 animate-pulse'); ?>">
                                        <?php echo $row['status']; ?>
                                    </span>
                                    <div class="text-[10px] text-slate-400 mt-2.5 uppercase font-bold">
                                        Processor: <?php echo !empty($row['proc_agent_name']) ? htmlspecialchars($row['proc_agent_name']) : ($row['status']!='pending' ? 'Admin' : '-'); ?>
                                    </div>
                                </td>

                                <td class="px-6 py-5 text-right">
                                    <?php if($row['status'] === 'pending'): ?>
                                        <form method="POST" class="inline-flex gap-2">
                                            <input type="hidden" name="trx_id" value="<?php echo $row['id']; ?>">
                                            <button type="submit" name="action" value="approve" onclick="return confirm('Approve?')" class="w-9 h-9 flex items-center justify-center bg-emerald-500 text-white rounded-xl shadow-lg shadow-emerald-200 hover:bg-emerald-600"><i class="fas fa-check"></i></button>
                                            <button type="submit" name="action" value="reject" onclick="return confirm('Reject?')" class="w-9 h-9 flex items-center justify-center bg-rose-500 text-white rounded-xl shadow-lg shadow-rose-200 hover:bg-rose-600"><i class="fas fa-times"></i></button>
                                        </form>
                                    <?php else: ?>
                                        <div class="w-9 h-9 flex items-center justify-center bg-slate-100 text-slate-300 rounded-xl"><i class="fas fa-lock text-xs"></i></div>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endwhile; else: ?>
                            <tr><td colspan="5" class="p-20 text-center text-slate-400 font-bold uppercase tracking-widest">No data available</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</body>
</html>