<?php
session_start();
require_once('functions.php');
require_once('dbconnection.php');
require_once('includes/init.php');

$password = $_SESSION['password'];
$admin_data = get_admin($conn, $password);

// --- Security Checks ---
if ($password != $admin_data['password']) {
    header('location: login.php');
    exit;
}
if (!isset($_SESSION['password'])) {
    header('location: login.php');
    exit;
}
if (empty($admin_data)) header('location: login.php');

$pageTitle = "Transaction History";

// --- Handle Delete Requests ---
// Delete from Task History
if (isset($_GET['delete_task'])) {
    $id = intval($_GET['delete_task']);
    $sql = "DELETE FROM history WHERE id = $id";
    $conn->query($sql) ? snack("success", "Task Deleted") : snack("error", "Failed");
}
// Delete from Withdrawals (Payments)
if (isset($_GET['delete_payment'])) {
    $id = intval($_GET['delete_payment']);
    $sql = "DELETE FROM payments WHERE id = $id";
    $conn->query($sql) ? snack("success", "Withdrawal Deleted") : snack("error", "Failed");
}

// --- Build Filter Query ---
$where_history = "WHERE 1=1";
$where_payments = "WHERE 1=1";

// 1. Search Filter (User/Number)
// Filter by user (mobile number)
if (isset($_GET['user']) && !empty($_GET['user'])) {
    $user = $conn->real_escape_string($_GET['user']);
    $where_history .= " AND number = '$user'";
    $where_payments .= " AND (mnumber = '$user' OR number = '$user')";
}

if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search = $conn->real_escape_string($_GET['search']);
    $where_history .= " AND (number LIKE '%$search%')";
    $where_payments .= " AND (mnumber LIKE '%$search%' OR number LIKE '%$search%')";
}

// 2. Status Filter
if (isset($_GET['status']) && $_GET['status'] != 'all') {
    $status = $conn->real_escape_string($_GET['status']);
    $where_history .= " AND status = '$status'";
    $where_payments .= " AND status = '$status'";
}

// 3. Date Filter
if (isset($_GET['date_type'])) {
    $dt = $_GET['date_type'];
    if ($dt == 'today') {
        $where_history .= " AND DATE(date) = CURDATE()";
        $where_payments .= " AND DATE(date) = CURDATE()";
    } elseif ($dt == 'week') {
        $where_history .= " AND date >= DATE_SUB(NOW(), INTERVAL 1 WEEK)";
        $where_payments .= " AND date >= DATE_SUB(NOW(), INTERVAL 1 WEEK)";
    } elseif ($dt == 'month') {
        $where_history .= " AND date >= DATE_SUB(NOW(), INTERVAL 1 MONTH)";
        $where_payments .= " AND date >= DATE_SUB(NOW(), INTERVAL 1 MONTH)";
    } elseif ($dt == 'custom' && !empty($_GET['start']) && !empty($_GET['end'])) {
        $start = $conn->real_escape_string($_GET['start']);
        $end = $conn->real_escape_string($_GET['end']);
        $where_history .= " AND DATE(date) BETWEEN '$start' AND '$end'";
        $where_payments .= " AND DATE(date) BETWEEN '$start' AND '$end'";
    }
}

// --- Fetch Data ---

// 1. Get Withdrawals (Payments Table)
$sql_pay = "SELECT * FROM payments $where_payments ORDER BY date DESC";
$res_pay = mysqli_query($conn, $sql_pay);
$payments = [];
while ($row = mysqli_fetch_array($res_pay)) { $payments[] = $row; }

// 2. Get Task History (History Table)
$sql_hist = "SELECT * FROM history $where_history ORDER BY date DESC";
$res_hist = mysqli_query($conn, $sql_hist);
$history = [];
while ($row = mysqli_fetch_array($res_hist)) { $history[] = $row; }

// 3. Get Summary Counts (Based on History Table only, as per original logic)
// You can adjust this to include payments if needed
$sql_count = "SELECT
        (SELECT COUNT(1) FROM history $where_history) AS history_count,
        (SELECT SUM(amount) FROM history $where_history AND status = 'Paid') AS paid_amount,
        (SELECT SUM(amount) FROM history $where_history AND status = 'Pending') AS pending_amount
    FROM dual";
$res_count = $conn->query($sql_count);
$summary = $res_count->fetch_assoc();

?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo $pageTitle ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=false, shrink-to-fit=no">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <style>
        *, .select { user-select: text !important; }
        main { overflow: auto; padding: 1em; }
        table { white-space: nowrap; }
        tbody > tr:nth-child(even) { background: #F8F8F8; }
        .Paid, .Success { color: green; font-weight: bold; }
        .Pending { color: red; font-weight: bold; }
        td { max-width: 150px; word-break: break-all; vertical-align: middle !important; }
        
        /* Custom Filter Styling to match your UI */
        .filter-box { background: #fff; padding: 15px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
        .table-title { font-size: 1.2rem; color: #333; margin: 20px 0 10px 5px; font-weight: 600; border-left: 4px solid #007bff; padding-left: 10px; }
    </style>
</head>
<body class="bg-gray-200">
    <?php include("header.php") ?>
    
    <main>
        <section class="fr-container fr-lg" style="width: 100%;">
            
            <div class="filter-box">
                <form method="GET" action="history.php">
                    <div class="form-row align-items-end">
                        <div class="col-md-3 mb-2">
                            <label class="small text-muted">Search User/Number</label>
                            <input type="text" name="search" class="form-control form-control-sm" placeholder="Search..." value="<?= $_GET['search'] ?? '' ?>">
                        </div>
                        <div class="col-md-2 mb-2">
                            <label class="small text-muted">Status</label>
                            <select name="status" class="form-control form-control-sm">
                                <option value="all">All</option>
                                <option value="Paid" <?= ($_GET['status'] ?? '') == 'Paid' ? 'selected' : '' ?>>Paid</option>
                                <option value="Pending" <?= ($_GET['status'] ?? '') == 'Pending' ? 'selected' : '' ?>>Pending</option>
                            </select>
                        </div>
                        <div class="col-md-3 mb-2">
                            <label class="small text-muted">Date Range</label>
                            <div class="btn-group btn-group-sm w-100">
                                <button type="submit" name="date_type" value="today" class="btn btn-outline-primary <?= ($_GET['date_type'] ?? '') == 'today' ? 'active' : '' ?>">Today</button>
                                <button type="submit" name="date_type" value="week" class="btn btn-outline-primary <?= ($_GET['date_type'] ?? '') == 'week' ? 'active' : '' ?>">Week</button>
                                <button type="submit" name="date_type" value="month" class="btn btn-outline-primary <?= ($_GET['date_type'] ?? '') == 'month' ? 'active' : '' ?>">Month</button>
                            </div>
                        </div>
                         <div class="col-md-3 mb-2">
                             <label class="small text-muted">Custom Date</label>
                             <div class="d-flex">
                                 <input type="date" name="start" class="form-control form-control-sm mr-1" value="<?= $_GET['start'] ?? '' ?>">
                                 <input type="date" name="end" class="form-control form-control-sm" value="<?= $_GET['end'] ?? '' ?>">
                             </div>
                             <input type="hidden" name="date_type" value="custom" id="custom_hidden" disabled>
                        </div>
                        <div class="col-md-1 mb-2">
                            <button type="submit" class="btn btn-primary btn-sm btn-block" onclick="if(document.querySelector('[name=start]').value) document.getElementById('custom_hidden').disabled=false">Go</button>
                        </div>
                    </div>
                </form>
            </div>

            <h4 class="table-title">Withdraw History</h4>
            <section class="table-wrapper mb-4">
                <table class="table table-divo">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Date</th>
                            <th>User (mNumber)</th>
                            <th>Payment Number</th>
                            <th>Amount</th>
                            <th>Method</th>
                            <th>Status</th>
                            <!--<th>Action</th>-->
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($payments)): ?>
                            <tr><td colspan="8" class="text-center">No withdrawals found</td></tr>
                        <?php else: ?>
                            <?php $p_idx = 1; foreach ($payments as $row) : ?>
                            <tr>
                                <td><?= $p_idx++ ?></td>
                                <td><?= date("d-M-y H:i", strtotime($row['date'])) ?></td>
                                <td><?= $row['mnumber'] ?></td>
                                <td><?= $row['number'] ?></td>
                                <td><?= $row['amount'] ?></td>
                                <td><?= $row['method'] ?></td>
                                <td class="<?= $row['status'] ?>"><?= $row['status'] ?></td>
                                <!--<td>-->
                                <!--    <a href="history.php?delete_payment=<?= $row['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete this withdrawal?');">-->
                                <!--        <span class="material-icons" style="font-size: 16px;">delete</span>-->
                                <!--    </a>-->
                                <!--</td>-->
                            </tr>
                            <?php endforeach ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </section>

            <h4 class="table-title">Task History (Total: <?= $summary['history_count'] ?? 0 ?>)</h4>
            <section class="table-wrapper">
                <table class="table table-divo">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Date</th>
                            <th>Account</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>IP</th>
                            <th>Country</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($history)): ?>
                            <tr><td colspan="8" class="text-center">No task history found</td></tr>
                        <?php else: ?>
                            <?php $h_idx = 1; foreach ($history as $row) : ?>
                            <tr>
                                <td><?= $h_idx++ ?></td>
                                <td><?= date("d-M-y H:i", strtotime($row['date']) + 10*3600 ) ?></td>
                                <td><?= $row['number'] ?></td>
                                <td><?= $row['amount'] ?></td>
                                <td class="<?= $row['status'] ?>"><?= $row['status'] ?></td>
                                <td><?= $row['ip'] ?></td>
                                <td><?= $row['country'] ?></td>
                                <td>
                                    <a href="history.php?delete_task=<?= $row['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete this task?');">
                                        <span class="material-icons" style="font-size: 16px;">delete</span>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </section>

        </section>
    </main>

    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <?php if (isset($_GET['success'])) : ?>
        <p class="snackbar success">Success</p>
    <?php endif ?>
    <?php include('footer.php') ?>
</body>
</html>