<?php
session_start();
$db_path = file_exists('includes/db.php') ? 'includes/db.php' : '../includes/db.php';
if (file_exists($db_path)) {
    require $db_path;
} else {
    $conn = new mysqli('localhost', 'root', '', 'bajipari');
}

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

$uid = $_SESSION['user_id'];

// --- FILTER LOGIC ---
$where_clauses = ["user_id = $uid"];

// 1. Date Filter
$date_filter = isset($_GET['date']) ? $_GET['date'] : 'today';
if ($date_filter == 'today') {
    $where_clauses[] = "DATE(created_at) = CURDATE()";
} elseif ($date_filter == 'yesterday') {
    $where_clauses[] = "DATE(created_at) = CURDATE() - INTERVAL 1 DAY";
} elseif ($date_filter == 'week') {
    $where_clauses[] = "created_at >= CURDATE() - INTERVAL 7 DAY";
}

// 2. Status Filter
if (isset($_GET['status']) && $_GET['status'] != '') {
    $status = $conn->real_escape_string($_GET['status']); // pending/approved/rejected
    $where_clauses[] = "status = '$status'";
}

// 3. Type Filter
if (isset($_GET['type']) && $_GET['type'] != '') {
    $type = $conn->real_escape_string($_GET['type']); // deposit/withdraw/adjustment
    $where_clauses[] = "type = '$type'";
}

// Build Query
$sql = "SELECT * FROM transactions_fake WHERE " . implode(' AND ', $where_clauses) . " ORDER BY created_at DESC";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Transaction Records</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=Roboto:wght@400;500;700&display=swap" rel="stylesheet">

    <style>
        body { 
            background-color: #121619; 
            color: #d1d5db; 
            font-family: 'Roboto', sans-serif; 
            padding-bottom: 80px;
        }

        /* Header */
        .header-bg { background-color: #232a31; padding: 15px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #2f3840; }
        
        /* Table Header */
        .tbl-header {
            display: grid; grid-template-columns: 1fr 1fr 1fr 1fr;
            background-color: #2f3b43; padding: 10px 5px; font-size: 11px;
            text-align: center; color: #9ca3af;
        }
        .tbl-col { border-right: 1px solid #374151; }
        .tbl-col:last-child { border-right: none; }

        /* Data Row */
        .data-row {
            display: grid; grid-template-columns: 1fr 1fr 1fr 1fr;
            padding: 15px 5px; font-size: 11px; text-align: center;
            border-bottom: 1px solid #232a31; align-items: center;
        }
        
        /* Status Colors */
        .st-approved { color: #10b981; }
        .st-pending { color: #facc15; }
        .st-rejected { color: #ef4444; }

        /* No Data Icon (Toggle lookalike) */
        .no-data-icon {
            width: 50px; height: 26px; border-radius: 20px;
            background-color: #2f3b43; position: relative;
            margin: 0 auto 15px auto;
        }
        .no-data-icon::before {
            content: ''; position: absolute; left: 4px; top: 4px;
            width: 18px; height: 18px; border-radius: 50%; background-color: #4b5563;
        }
        .no-data-icon::after {
            content: ''; position: absolute; right: 4px; top: 4px;
            width: 18px; height: 18px; border-radius: 50%; background-color: #374151;
        }

        /* --- FILTER MODAL STYLES --- */
        .filter-modal {
            position: fixed; inset: 0; z-index: 100;
            background-color: #121619;
            transform: translateX(100%); transition: transform 0.3s ease-in-out;
        }
        .filter-modal.open { transform: translateX(0); }
        
        .filter-sec-title { font-size: 12px; color: #9ca3af; margin-bottom: 8px; margin-top: 20px; }
        
        .filter-btn {
            background-color: #2f3b43; color: #9ca3af;
            font-size: 13px; padding: 10px; border-radius: 4px;
            text-align: center; border: 1px solid transparent; transition: 0.2s;
        }
        /* Active Filter Button */
        .filter-btn.active {
            background-color: #eab308; color: #000; font-weight: bold; border-color: #eab308;
        }

        /* Bottom Nav */
        .bottom-nav { background-color: #000; border-top: 1px solid #222; }
        .nav-item { color: #6b7280; } .nav-item.active { color: #facc15; }
    </style>
</head>
<body>

    <div class="header-bg sticky top-0 z-40">
        <a href="account.php" class="text-xl text-gray-400"><i class="fas fa-home"></i></a>
        <h1 class="text-white font-medium text-base">Transaction Records</h1>
        <button onclick="openFilter()" class="text-xl text-white"><i class="fas fa-times"></i></button>
    </div>

    <div class="bg-[#1c2227] px-4 py-2 border-b border-[#2f3840] flex justify-between items-center">
        <span class="bg-[#2f3b43] text-[#9ca3af] text-xs px-3 py-1 rounded">
            <?php 
                if($date_filter == 'today') echo 'Today';
                elseif($date_filter == 'yesterday') echo 'Yesterday';
                else echo 'Last 7 days';
            ?>
        </span>
        <button onclick="openFilter()" class="text-white"><i class="fas fa-filter"></i></button>
    </div>

    <div class="tbl-header">
        <div class="tbl-col">Type</div>
        <div class="tbl-col">Amount</div>
        <div class="tbl-col">Status</div>
        <div class="tbl-col">Txn Date</div>
    </div>

    <div class="min-h-[60vh]">
        <?php if ($result && $result->num_rows > 0): ?>
            <?php while($row = $result->fetch_assoc()): 
                $status_class = 'st-pending';
                if($row['status'] == 'approved') $status_class = 'st-approved';
                if($row['status'] == 'rejected') $status_class = 'st-rejected';
                
                // Map DB enum to display text
                $status_text = $row['status'] == 'pending' ? 'Processing' : ucfirst($row['status']);
            ?>
            <div class="data-row">
                <div class="text-white capitalize"><?php echo $row['type']; ?></div>
                <div class="text-white font-mono"><?php echo number_format($row['amount'], 2); ?></div>
                <div class="<?php echo $status_class; ?>"><?php echo $status_text; ?></div>
                <div class="text-gray-500 text-[10px]">
                    <?php echo date('Y-m-d', strtotime($row['created_at'])); ?><br>
                    <?php echo date('H:i:s', strtotime($row['created_at'])); ?>
                </div>
            </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div class="flex flex-col items-center justify-center pt-32 opacity-30">
                <div class="no-data-icon"></div>
                <div class="no-data-icon" style="width: 30px; margin-top:-10px;"></div>
                <p class="text-sm text-gray-400 mt-2">No Data</p>
            </div>
        <?php endif; ?>
    </div>

    <div id="filterModal" class="filter-modal flex flex-col h-full">
        <div class="bg-[#232a31] p-4 flex items-center gap-4 border-b border-[#2f3840]">
            <button onclick="closeFilter()" class="text-white text-lg"><i class="fas fa-chevron-left"></i></button>
            <h2 class="text-gray-300 text-sm font-medium">Transaction Record Filter</h2>
        </div>

        <div class="p-4 flex-1 overflow-y-auto">
            
            <p class="filter-sec-title">Status</p>
            <div class="grid grid-cols-3 gap-3">
                <div class="filter-btn f-status" data-val="pending" onclick="selectFilter(this, 'status')">Processing</div>
                <div class="filter-btn f-status" data-val="rejected" onclick="selectFilter(this, 'status')">Rejected</div>
                <div class="filter-btn f-status" data-val="approved" onclick="selectFilter(this, 'status')">Approved</div>
            </div>

            <p class="filter-sec-title">Payment Type</p>
            <div class="grid grid-cols-3 gap-3">
                <div class="filter-btn f-type" data-val="deposit" onclick="selectFilter(this, 'type')">Deposit</div>
                <div class="filter-btn f-type" data-val="withdraw" onclick="selectFilter(this, 'type')">Withdrawal</div>
                <div class="filter-btn f-type" data-val="adjustment" onclick="selectFilter(this, 'type')">Adjustment</div>
            </div>

            <p class="filter-sec-title">Date</p>
            <div class="grid grid-cols-3 gap-3">
                <div class="filter-btn f-date active" data-val="today" onclick="selectFilter(this, 'date')">Today</div>
                <div class="filter-btn f-date" data-val="yesterday" onclick="selectFilter(this, 'date')">Yesterday</div>
                <div class="filter-btn f-date" data-val="week" onclick="selectFilter(this, 'date')">Last 7 days</div>
            </div>

        </div>

        <div class="p-4 bg-[#121619] border-t border-[#2f3840]">
            <button onclick="applyFilters()" class="w-full bg-[#eab308] text-black font-bold py-3 rounded text-sm shadow-lg">Confirm</button>
        </div>
    </div>

    <div class="fixed bottom-0 left-0 w-full h-[60px] bottom-nav z-50 flex justify-between items-center px-6">
        <a href="index.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-home text-lg mb-1"></i><span class="text-[10px]">Home</span>
        </a>
        <a href="promotions.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-gift text-lg mb-1"></i><span class="text-[10px]">Promotions</span>
        </a>
        <a href="deposit.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-wallet text-lg mb-1"></i><span class="text-[10px]">Deposit</span>
        </a>
        <a href="account.php" class="flex flex-col items-center justify-center nav-item active">
            <i class="fas fa-user text-lg mb-1"></i><span class="text-[10px]">My Account</span>
        </a>
    </div>

    <script>
        // State variables
        let selectedStatus = '';
        let selectedType = '';
        let selectedDate = 'today';

        // Initialize from URL params if present
        const urlParams = new URLSearchParams(window.location.search);
        if(urlParams.get('status')) setActive('status', urlParams.get('status'));
        if(urlParams.get('type')) setActive('type', urlParams.get('type'));
        if(urlParams.get('date')) setActive('date', urlParams.get('date'));

        function openFilter() {
            document.getElementById('filterModal').classList.add('open');
        }

        function closeFilter() {
            document.getElementById('filterModal').classList.remove('open');
        }

        function selectFilter(btn, type) {
            // Remove active class from siblings
            const group = document.querySelectorAll(`.f-${type}`);
            group.forEach(el => el.classList.remove('active'));
            
            // Add active to clicked
            btn.classList.add('active');

            // Update state
            const val = btn.getAttribute('data-val');
            if (type === 'status') selectedStatus = val;
            if (type === 'type') selectedType = val;
            if (type === 'date') selectedDate = val;
        }

        function setActive(type, val) {
            const btn = document.querySelector(`.f-${type}[data-val="${val}"]`);
            if(btn) {
                // Trigger logic
                selectFilter(btn, type);
            }
        }

        function applyFilters() {
            let url = 'trans_rec_full.php?';
            if (selectedDate) url += `date=${selectedDate}&`;
            if (selectedStatus) url += `status=${selectedStatus}&`;
            if (selectedType) url += `type=${selectedType}&`;
            
            window.location.href = url;
        }
    </script>

</body>
</html>