<?php
// admin/reports.php — Final Fixed Version (Dashboard Stats + View Button)

// 1. SETTINGS & SESSION
date_default_timezone_set('Asia/Kolkata');
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 2. CONFIG & AUTH
// Config path adjust kar lena agar folder structure alag ho
if (file_exists("includes/config.php")) {
    require_once "includes/config.php";
} elseif (file_exists("../includes/config.php")) {
    require_once "../includes/config.php"; 
} else {
    die("Config file missing.");
}

// Ensure DB uses India Time
if (isset($conn) && $conn instanceof mysqli) {
    $conn->query("SET time_zone = '+05:30'");
}

if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit();
}

// --- TABLE NAMES ---
$tbl_users   = "users";
$tbl_dep     = "deposits";
$tbl_with    = "withdrawals";
$tbl_history = "transactions"; 

// --------------------------------------------------------
// 📊 PAGE LOGIC
// --------------------------------------------------------
$view_type   = $_GET['type'] ?? 'dashboard'; 
$filter_date = $_GET['date'] ?? '';
$search_mobile = $_GET['mobile'] ?? '';

// 1. DASHBOARD STATS LOGIC
if ($view_type == 'dashboard') {
    $today = date('Y-m-d');
    $start = $today . " 00:00:00";
    $end   = $today . " 23:59:59";
    
    // A. Users Today
    $reg_stats = $conn->query("SELECT COUNT(*) as cnt FROM $tbl_users WHERE created_at BETWEEN '$start' AND '$end'")->fetch_assoc();
    
    // B. Deposits Today (Exclude Gateway ID 1)
    $dep_stats = $conn->query("SELECT 
        SUM(CASE WHEN status='successful' THEN amount ELSE 0 END) as s_amt, 
        COUNT(CASE WHEN status='successful' THEN 1 END) as s_cnt, 
        COUNT(CASE WHEN status='pending' THEN 1 END) as p_cnt 
        FROM $tbl_dep WHERE created_at BETWEEN '$start' AND '$end' AND (gateway_id != 1 OR gateway_id IS NULL)")->fetch_assoc();
    
    // C. Withdrawals Today (🔥 FIXED: Checks 'approved', 'success', 'completed')
    $with_stats = $conn->query("SELECT 
        SUM(CASE WHEN status IN ('approved', 'success', 'completed') THEN amount ELSE 0 END) as s_amt, 
        COUNT(CASE WHEN status IN ('approved', 'success', 'completed') THEN 1 END) as s_cnt, 
        COUNT(CASE WHEN status='pending' THEN 1 END) as p_cnt 
        FROM $tbl_with WHERE created_at BETWEEN '$start' AND '$end'")->fetch_assoc();
    
    // D. Graph Data (Last 7 Days)
    $graph_labels = []; $graph_reg = []; $graph_dep = []; $graph_with = [];
    for ($i = 6; $i >= 0; $i--) {
        $d = date('Y-m-d', strtotime("-$i days"));
        $graph_labels[] = date('d M', strtotime($d));
        
        // Register Count
        $graph_reg[] = $conn->query("SELECT COUNT(*) as c FROM $tbl_users WHERE DATE(created_at)='$d'")->fetch_assoc()['c'] ?? 0;
        
        // Deposit Sum
        $graph_dep[] = $conn->query("SELECT SUM(amount) as t FROM $tbl_dep WHERE status='successful' AND DATE(created_at)='$d' AND (gateway_id != 1 OR gateway_id IS NULL)")->fetch_assoc()['t'] ?? 0;
        
        // Withdrawal Sum (🔥 FIXED STATUS)
        $graph_with[] = $conn->query("SELECT SUM(amount) as t FROM $tbl_with WHERE status IN ('approved', 'success', 'completed') AND DATE(created_at)='$d'")->fetch_assoc()['t'] ?? 0;
    }
}

// 2. USER HISTORY SEARCH LOGIC
$user_data = null;
$history_rows = [];
if ($view_type == 'user_history' && !empty($search_mobile)) {
    $u_sql = "SELECT id, mobile, (income_balance+deposit_balance+bonus_balance) as total_bal, created_at FROM $tbl_users WHERE mobile='$search_mobile' LIMIT 1";
    $u_res = $conn->query($u_sql);
    
    if ($u_res && $u_res->num_rows > 0) {
        $user_data = $u_res->fetch_assoc();
        $uid = $user_data['id'];
        $h_sql = "SELECT * FROM $tbl_history WHERE user_id='$uid' ORDER BY id DESC";
        $history_rows = $conn->query($h_sql);
    }
}

// 3. LIST VIEW LOGIC (Users/Deposits/Withdrawals)
if ($view_type != 'dashboard' && $view_type != 'user_history') {
    if ($view_type == 'users') $target_tbl = $tbl_users;
    elseif ($view_type == 'deposits') $target_tbl = $tbl_dep;
    else $target_tbl = $tbl_with;

    $whereArr = [];
    
    // Date Filter
    if (!empty($filter_date)) $whereArr[] = "DATE(t.created_at) = '$filter_date'";
    
    // Deposit Gateway Filter
    if ($view_type == 'deposits') {
        $whereArr[] = "(t.gateway_id != 1 OR t.gateway_id IS NULL)";
    }
    
    // Status Filter
    $filter_status = $_GET['status'] ?? 'all';
    if ($filter_status != 'all') {
        if ($view_type == 'users') {
            $whereArr[] = "t.status = '$filter_status'";
        } else {
            // Smart Status Filter
            if ($filter_status == 'success') {
                if ($view_type == 'deposits') {
                    $whereArr[] = "t.status = 'successful'";
                } else {
                    $whereArr[] = "t.status IN ('approved', 'success', 'completed')";
                }
            } else {
                $whereArr[] = "t.status = '$filter_status'";
            }
        }
    }
    $whereStr = count($whereArr) > 0 ? "WHERE " . implode(' AND ', $whereArr) : "";

    // Calculation Stats for Lists
    $stats = [];
    if ($view_type == 'deposits') {
        $sqlStats = "SELECT COUNT(CASE WHEN status='successful' THEN 1 END) as success_cnt, SUM(CASE WHEN status='successful' THEN amount ELSE 0 END) as success_amt, COUNT(CASE WHEN status='pending' THEN 1 END) as pending_cnt, SUM(CASE WHEN status='pending' THEN amount ELSE 0 END) as pending_amt FROM $target_tbl t $whereStr";
        $stats = $conn->query($sqlStats)->fetch_assoc();
    } elseif ($view_type == 'withdrawals') {
         // 🔥 FIXED: Stats for withdrawal list
         $sqlStats = "SELECT COUNT(CASE WHEN status IN ('approved','success','completed') THEN 1 END) as success_cnt, SUM(CASE WHEN status IN ('approved','success','completed') THEN amount ELSE 0 END) as success_amt, COUNT(CASE WHEN status='pending' THEN 1 END) as pending_cnt, SUM(CASE WHEN status='pending' THEN amount ELSE 0 END) as pending_amt FROM $target_tbl t $whereStr";
         $stats = $conn->query($sqlStats)->fetch_assoc();
    }

    // Fetch Rows
    if ($view_type == 'users') {
        $sql = "SELECT t.* FROM $target_tbl t $whereStr ORDER BY t.id DESC";
    } else {
        $sql = "SELECT t.*, u.mobile FROM $target_tbl t LEFT JOIN users u ON t.user_id=u.id $whereStr ORDER BY t.id DESC";
    }
    $res = $conn->query($sql);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
    :root { --bg: #f3f4f6; --card: #ffffff; --text: #1f2937; --blue: #3b82f6; --green: #10b981; --red: #ef4444; --purp: #8b5cf6; --yell: #f59e0b; }
    body { font-family: 'Segoe UI', sans-serif; background: var(--bg); color: var(--text); margin: 0; padding: 20px; }
    
    .flex-between { display: flex; justify-content: space-between; align-items: center; }
    .btn { padding: 8px 15px; border-radius: 6px; border: none; font-weight: 600; cursor: pointer; font-size: 13px; text-decoration: none; display: inline-flex; align-items: center; gap: 5px; color:#fff; transition:0.2s; }
    .btn-dark { background: #1f2937; } .btn-dark:hover { background: #374151; }
    .btn-exp { background: #059669; } .btn-exp:hover { background: #047857; }
    .btn-clr { background: #6b7280; } .btn-clr:hover { background: #4b5563; }
    .btn-search { background: var(--blue); }
    .btn-view { background: #6366f1; padding: 6px 12px; font-size: 12px; border-radius: 4px; }
    .btn-view:hover { background: #4f46e5; }

    .head { background: var(--card); padding: 15px 20px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.03); margin-bottom: 25px; }
    
    .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 20px; margin-bottom: 30px; }
    .card { background: var(--card); padding: 20px; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.02); text-decoration:none; display:block; color:inherit; border-left: 5px solid transparent;}
    .card h4 { margin: 0 0 5px; color: #6b7280; font-size: 12px; font-weight: 700; text-transform: uppercase; }
    .card .val { font-size: 24px; font-weight: 800; }
    
    .c-green { border-color: var(--green); } .c-green .val { color: var(--green); }
    .c-red { border-color: var(--red); } .c-red .val { color: var(--red); }
    .c-purp { border-color: var(--purp); } .c-purp .val { color: var(--purp); }

    .filter-bar { background: var(--card); padding: 15px; border-radius: 12px; display: flex; flex-wrap: wrap; gap: 15px; align-items: center; margin-bottom: 20px; }
    select, input[type=date], input[type=text] { padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 13px; outline: none; }

    .table-container { overflow-x: auto; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.02); background:white; min-height: 200px; }
    table { width: 100%; border-collapse: collapse; white-space: nowrap; }
    th { text-align: left; padding: 15px; background: #f9fafb; font-size: 12px; text-transform: uppercase; color: #6b7280; border-bottom: 1px solid #e5e7eb; }
    td { padding: 15px; border-bottom: 1px solid #f3f4f6; font-size: 14px; color: #374151; }
    tr:hover td { background: #f9fafb; }
    
    .badge { padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: bold; text-transform: uppercase; }
    .b-suc { background: #d1fae5; color: #065f46; }
    .b-pen { background: #fef3c7; color: #92400e; }
    .b-rej { background: #fee2e2; color: #b91c1c; }
    .b-inf { background: #e0f2fe; color: #0369a1; }

    /* Modal Styles */
    .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.5); backdrop-filter: blur(2px); }
    .modal-content { background-color: #fff; margin: 10% auto; padding: 25px; border-radius: 12px; width: 90%; max-width: 450px; box-shadow: 0 10px 25px rgba(0,0,0,0.2); animation: slideDown 0.3s ease; }
    @keyframes slideDown { from {transform: translateY(-20px); opacity:0;} to {transform: translateY(0); opacity:1;} }
    .close { color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer; }
    .close:hover { color: #000; }
    .data-row { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #f0f0f0; }
    .data-row:last-child { border-bottom: none; }
    .data-label { color: #666; font-weight: 500; font-size: 14px; }
    .data-val { font-weight: 700; color: #333; font-size: 14px; text-align: right; word-break: break-all; max-width: 60%; }
</style>
</head>
<body>

<div class="head flex-between">
    <h2 style="margin:0; font-size:20px;">
        <?php if($view_type == 'user_history'): ?> <i class="fa-solid fa-clock-rotate-left"></i> User History
        <?php elseif($view_type == 'deposits'): ?> <i class="fa-solid fa-wallet" style="color:#10b981;"></i> Deposits
        <?php elseif($view_type == 'withdrawals'): ?> <i class="fa-solid fa-money-bill-transfer" style="color:#ef4444;"></i> Withdrawals
        <?php else: ?> <i class="fa-solid fa-chart-pie"></i> Dashboard
        <?php endif; ?>
    </h2>
    
    <div style="display:flex; gap:10px;">
        <?php if($view_type != 'dashboard'): ?>
            <a href="reports.php" class="btn btn-dark"><i class="fa-solid fa-arrow-left"></i> Home</a>
        <?php endif; ?>
        
        <?php if($view_type == 'dashboard'): ?>
             <a href="?type=user_history" class="btn btn-search"><i class="fa-solid fa-magnifying-glass"></i> Search User</a>
        <?php endif; ?>
    </div>
</div>

<?php if ($view_type == 'dashboard'): ?>

<div class="grid">
    <a href="?type=users" class="card c-purp">
        <h4>New Registers</h4>
        <div class="val"><?= number_format($reg_stats['cnt']) ?></div>
        <div class="sub">Joined Today</div>
    </a>
    <a href="?type=deposits" class="card c-green">
        <h4>Deposits (Today)</h4>
        <div class="val">₹<?= number_format($dep_stats['s_amt'] ?? 0) ?></div>
        <div class="sub">Success: <?= $dep_stats['s_cnt'] ?> | Pending: <?= $dep_stats['p_cnt'] ?></div>
    </a>
    <a href="?type=withdrawals" class="card c-red">
        <h4>Withdrawals (Today)</h4>
        <div class="val">₹<?= number_format($with_stats['s_amt'] ?? 0) ?></div>
        <div class="sub">Success: <?= $with_stats['s_cnt'] ?> | Pending: <?= $with_stats['p_cnt'] ?></div>
    </a>
    <a href="?type=user_history" class="card" style="border-left-color:#2563eb;">
        <h4 style="color:#2563eb;">Check History</h4>
        <div class="val" style="color:#1e40af;"><i class="fa-solid fa-search"></i></div>
        <div class="sub">Search by Mobile</div>
    </a>
</div>

<div style="background:white; padding:20px; border-radius:12px; height:350px;">
    <canvas id="mainChart"></canvas>
</div>
<script>
const ctx = document.getElementById('mainChart');
new Chart(ctx, {
    type: 'bar',
    data: {
        labels: <?= json_encode($graph_labels) ?>,
        datasets: [
            { label: 'Register', data: <?= json_encode($graph_reg) ?>, backgroundColor: '#8b5cf6' },
            { label: 'Deposit', data: <?= json_encode($graph_dep) ?>, backgroundColor: '#10b981' }
        ]
    },
    options: { responsive: true, maintainAspectRatio: false }
});
</script>

<?php elseif ($view_type == 'user_history'): ?>
    
    <div class="filter-bar">
    <form method="GET" style="display:flex; gap:10px; align-items:center; width:100%;">
        <input type="hidden" name="type" value="user_history">
        <label style="font-weight:bold;">Enter User Mobile:</label>
        <input type="text" name="mobile" placeholder="e.g. 9876543210" value="<?= $search_mobile ?>" required>
        <button type="submit" class="btn btn-search">Search History</button>
    </form>
    </div>

    <?php if($user_data): ?>
    <div style="background:#e0f2fe; padding:15px; border-radius:10px; margin-bottom:20px; border:1px solid #bae6fd; display:flex; justify-content:space-between; align-items:center;">
        <div>
            <strong style="color:#0369a1; font-size:16px;">User Found: <?= $user_data['mobile'] ?></strong><br>
            <span style="font-size:13px; color:#555;">User ID: #<?= $user_data['id'] ?> | Joined: <?= date('d M Y', strtotime($user_data['created_at'])) ?></span>
        </div>
        <div style="text-align:right;">
            <div style="font-size:12px; color:#555;">Current Balance</div>
            <div style="font-size:20px; font-weight:bold; color:#0369a1;">₹<?= number_format($user_data['total_bal'], 2) ?></div>
        </div>
    </div>
    <div class="table-container">
        <table>
            <thead><tr><th>Type</th><th>Amount</th><th>Status</th><th>Remarks</th><th>Date</th></tr></thead>
            <tbody>
                <?php if($history_rows && $history_rows->num_rows > 0): ?>
                    <?php while($row = $history_rows->fetch_assoc()): ?>
                    <tr>
                        <td><?= ucfirst($row['type']) ?></td>
                        <td><b>₹<?= number_format($row['amount'], 2) ?></b></td>
                        <td><?= ucfirst($row['status']) ?></td>
                        <td><?= $row['remarks'] ?? '-' ?></td>
                        <td><?= date('d-M h:i A', strtotime($row['created_at'])) ?></td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="5" style="text-align:center;">No history found.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php elseif(!empty($search_mobile)): ?>
    <div style="background:#fee2e2; padding:15px; border-radius:10px; color:#b91c1c; text-align:center;">User not found!</div>
    <?php endif; ?>

<?php else: ?>

<div class="filter-bar flex-between">
    <form method="GET" style="display:flex; flex-wrap:wrap; gap:15px; align-items:center; width:100%;">
        <input type="hidden" name="type" value="<?= $view_type ?>">
        <div style="display:flex; gap:5px; align-items:center;">
            <div>
                <span style="font-weight:bold; font-size:12px; color:#666;">DATE:</span>
                <input type="date" name="date" value="<?= $filter_date ?>" onchange="this.form.submit()">
            </div>
            <a href="?type=<?=$view_type?>" class="btn btn-clr" style="height:20px; margin-top:18px; line-height:20px;">Show All</a>
        </div>
        <?php if($view_type != 'users'): ?>
        <div>
            <span style="font-weight:bold; font-size:12px; color:#666; margin-left:10px;">STATUS:</span>
            <select name="status" onchange="this.form.submit()">
                <option value="all">All Status</option>
                <option value="success">Successful</option>
                <option value="pending">Pending</option>
            </select>
        </div>
        <?php endif; ?>
    </form>
</div>

<?php if(isset($stats)): ?>
<div class="split-stats" style="margin-bottom:20px; display:flex; gap:20px;">
    <div style="background:#ecfdf5; padding:15px; border-radius:8px; flex:1; border:1px solid #10b981;">
        <b style="color:#059669;">Success Total:</b> ₹<?= number_format($stats['success_amt'] ?? 0) ?>
    </div>
    <div style="background:#fffbeb; padding:15px; border-radius:8px; flex:1; border:1px solid #f59e0b;">
        <b style="color:#d97706;">Pending Total:</b> ₹<?= number_format($stats['pending_amt'] ?? 0) ?>
    </div>
</div>
<?php endif; ?>

<div class="table-container">
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>User Details</th>
                <?php if($view_type != 'users'): ?><th>Amount</th><?php endif; ?>
                <th>Status</th>
                <th>Date</th>
                <?php if($view_type == 'withdrawals'): ?><th>Action</th><?php endif; ?>
            </tr>
        </thead>
        <tbody>
            <?php if($res && $res->num_rows > 0): ?>
                <?php while($row = $res->fetch_assoc()): ?>
                <tr>
                    <td>#<?= $row['id'] ?></td>
                    <td>
                        <?php if($view_type == 'users'): ?> <b><?= $row['mobile'] ?></b>
                        <?php else: ?> <b><?= $row['mobile'] ?? 'User #'.$row['user_id'] ?></b><br><small>ID: <?= $row['user_id'] ?></small>
                        <?php endif; ?>
                    </td>
                    <?php if($view_type != 'users'): ?>
                    <td><b>₹<?= number_format($row['amount'], 2) ?></b></td>
                    <?php endif; ?>
                    <td>
                        <?php 
                            $s = strtolower($row['status'] ?? '');
                            if(strpos($s, 'succ')!==false || $s=='approved' || $s=='active' || $s=='completed') echo '<span class="badge b-suc">'.$s.'</span>';
                            elseif($s=='pending') echo '<span class="badge b-pen">'.$s.'</span>';
                            else echo '<span class="badge b-rej">'.$s.'</span>';
                        ?>
                    </td>
                    <td><?= date('d-M h:i A', strtotime($row['created_at'])) ?></td>
                    
                    <?php if($view_type == 'withdrawals'): ?>
                    <td>
                        <button class="btn btn-view" onclick='showDetails(
                            <?= json_encode($row['mch_transfer_id'] ?? "-") ?>,
                            <?= json_encode($row['account_number'] ?? "-") ?>,
                            <?= json_encode($row['ifsc'] ?? "-") ?>,
                            <?= json_encode($row['remark'] ?? "-") ?>,
                            <?= json_encode($row['amount']) ?>
                        )'>
                            <i class="fa-solid fa-eye"></i> View
                        </button>
                    </td>
                    <?php endif; ?>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="6" style="text-align:center; padding:30px; color:#999;">No records found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<div id="detailsModal" class="modal">
  <div class="modal-content">
    <span class="close" onclick="closeModal()">&times;</span>
    <h3 style="margin-top:0; color:#4f46e5; border-bottom:1px solid #eee; padding-bottom:10px;">Transaction Details</h3>
    <div id="modalBody">
        </div>
  </div>
</div>

<script>
function showDetails(txnId, acc, ifsc, remark, amt) {
    const modal = document.getElementById("detailsModal");
    const body = document.getElementById("modalBody");
    
    // Safety check for null values
    if(!txnId) txnId = "-";
    if(!remark) remark = "-";
    
    body.innerHTML = `
        <div class="data-row"><span class="data-label">Transfer ID:</span> <span class="data-val">${txnId}</span></div>
        <div class="data-row"><span class="data-label">Account No:</span> <span class="data-val">${acc}</span></div>
        <div class="data-row"><span class="data-label">IFSC Code:</span> <span class="data-val">${ifsc}</span></div>
        <div class="data-row"><span class="data-label">Amount:</span> <span class="data-val" style="color:green">₹${amt}</span></div>
        <div class="data-row"><span class="data-label">Status:</span> <span class="data-val" style="color:green">Success</span></div>
        <div class="data-row"><span class="data-label">Remark/Msg:</span> <span class="data-val">${remark}</span></div>
    `;
    modal.style.display = "block";
}

function closeModal() {
    document.getElementById("detailsModal").style.display = "none";
}

window.onclick = function(event) {
    const modal = document.getElementById("detailsModal");
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>

<?php endif; ?>

</body>
</html>