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

// --- 1. Authentication ---
$password = $_SESSION['password'] ?? '';
$admin_data = get_admin($conn, $password);

if (empty($admin_data) || $password != $admin_data['password']) {
    header('location: login.php');
    exit;
}

$pageTitle = 'Users Table';

// --- 2. Helper Function: Time Ago ---
function time_elapsed_string($timestamp) {
    if(empty($timestamp) || $timestamp < 1000) return "Never";
    $etime = time() - $timestamp;
    if ($etime < 1) return 'Just now';

    $a = array( 365 * 24 * 60 * 60  =>  'year',
                 30 * 24 * 60 * 60  =>  'month',
                      24 * 60 * 60  =>  'day',
                           60 * 60  =>  'hour',
                                60  =>  'min',
                                 1  =>  'sec');
    $a_plural = array( 'year' => 'years', 'month' => 'months', 'day' => 'days', 'hour' => 'hours', 'min' => 'mins', 'sec' => 'secs');

    foreach ($a as $secs => $str) {
        $d = $etime / $secs;
        if ($d >= 1) {
            $r = round($d);
            return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ago';
        }
    }
}

// --- 3. Handle Actions ---
if (isset($_GET['block']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $new_click = $invalid_limit + 1;
    $conn->query("UPDATE users SET i_click = $new_click WHERE id = $id");
    snack("success", "User Blocked");
}
if (isset($_GET['unblock']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $conn->query("UPDATE users SET i_click = 0 WHERE id = $id");
    snack("success", "User Unblocked");
}

// --- 4. Filters & Sorting ---
$where = "WHERE NOT (mobile = '1234')";
$order_by = "id";
$order_dir = "ASC";

// Search
if (!empty($_GET['search'])) {
    $s = $conn->real_escape_string($_GET['search']);
    $where .= " AND (fname LIKE '%$s%' OR mobile LIKE '%$s%')";
}

// Date Filter
if (!empty($_GET['date_filter'])) {
    $df = $_GET['date_filter'];
    // Assuming 'date' column exists for registration date. 
    // If you want to filter by Last Use, change 'date' to 'FROM_UNIXTIME(onlineStatus)'
    if ($df == 'today') $where .= " AND DATE(date) = CURDATE()"; 
    elseif ($df == 'yesterday') $where .= " AND DATE(date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
    elseif ($df == 'week') $where .= " AND date >= DATE_SUB(NOW(), INTERVAL 1 WEEK)";
    elseif ($df == 'month') $where .= " AND date >= DATE_SUB(NOW(), INTERVAL 1 MONTH)";
}

// Sorting Logic
// Note: 'task_count' is a calculated column we will add to the query
$valid_sorts = ['id', 'fname', 'mobile', 'balance', 't_ref', 'onlineStatus', 'task_count'];
if (isset($_GET['sort']) && in_array($_GET['sort'], $valid_sorts)) {
    $order_by = $_GET['sort'];
    $order_dir = (isset($_GET['dir']) && $_GET['dir'] == 'DESC') ? 'DESC' : 'ASC';
}
$next_dir = ($order_dir == 'ASC') ? 'DESC' : 'ASC';

// --- 5. Main Query ---

// Determine Task Calculation for SQL Sorting
if (isset($multi_task) && $multi_task == 1) {
    $task_calc = "(today_task1 + today_task2 + today_task3 + today_task4)";
} else {
    $task_calc = "today_task";
}

// Updated Payment Subqueries to use 'mnumber' (User Mobile)
$sql = "SELECT users.*, 
        $task_calc as task_count,
        (SELECT COUNT(*) FROM payments WHERE payments.mnumber = users.mobile) as pay_total,
        (SELECT COUNT(*) FROM payments WHERE payments.mnumber = users.mobile AND payments.status = 'Pending') as pay_pending
        FROM users 
        $where 
        ORDER BY $order_by $order_dir";

$data = mysqli_query($conn, $sql);
$rows = [];
while ($row = mysqli_fetch_array($data)) { $rows[] = $row; }

// Stats Query
$sql2 = "SELECT
        (SELECT COUNT(1) FROM users WHERE id > 1) AS total_users,
        (SELECT SUM(amount) FROM payments WHERE status = 'Paid') AS paid_amount
        FROM dual";
$data2 = $conn->query($sql2)->fetch_assoc();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Users Table</title>
    <meta name="theme-color" content="#f9fbfd">
    <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>
        main { padding: 1em; }
        .table > tbody > tr > td { vertical-align: middle; font-size: 0.95rem; }
        tbody > tr:nth-child(even) { background: #F8F8F8; }
        
        th a { color: #333; text-decoration: none; display: flex; align-items: center; }
        th a:hover { text-decoration: none; color: #007bff; }
        th a .material-icons { font-size: 14px; margin-left: 5px; color: #aaa; }
        
        .filter-bar { background: #fff; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); margin-bottom: 20px; }
        .text-pending { color: red; font-weight: bold; }
        
        /* Last Use Toggle Style */
        .date-toggle { cursor: pointer; border-bottom: 1px dashed #999; user-select: none; }
        .date-toggle:hover { color: #007bff; border-bottom-style: solid; }

        /* Action Buttons Styling to match your image */
        .btn-group-custom { display: flex; }
        .btn-group-custom .btn { border-radius: 0; margin-left: -1px; padding: 0.375rem 0.5rem; }
        .btn-group-custom .btn:first-child { border-top-left-radius: 0.25rem; border-bottom-left-radius: 0.25rem; margin-left: 0; }
        .btn-group-custom .btn:last-child { border-top-right-radius: 0.25rem; border-bottom-right-radius: 0.25rem; }
        
        /* Specific Colors for Outline Buttons */
        .btn-outline-primary { color: #007bff; border-color: #007bff; } /* Blue */
        .btn-outline-info { color: #17a2b8; border-color: #17a2b8; }    /* Cyan/Teal */
        .btn-outline-secondary { color: #6c757d; border-color: #6c757d; } /* Gray */
        .btn-outline-danger { color: #dc3545; border-color: #dc3545; }   /* Red */
        .btn-outline-success { color: #28a745; border-color: #28a745; }  /* Green (Unblock) */
    </style>
</head>
<body class="bg-gray-200">
    <?php include("header.php") ?>
    
    <main>
        <section class="fr-container fr-xl">
            
            <div class="filter-bar">
                <form method="GET">
                    <div class="form-row align-items-center">
                        <div class="col-md-4 my-1">
                            <div class="input-group input-group-sm">
                                <div class="input-group-prepend"><span class="input-group-text"><i class="material-icons" style="font-size: 16px;">search</i></span></div>
                                <input type="text" name="search" class="form-control" placeholder="Search name or mobile..." value="<?= $_GET['search'] ?? '' ?>">
                            </div>
                        </div>
                        <!--<div class="col-md-5 my-1">-->
                        <!--    <div class="btn-group btn-group-sm w-100">-->
                        <!--        <?php $df = $_GET['date_filter'] ?? ''; ?>-->
                        <!--        <button type="submit" name="date_filter" value="today" class="btn btn-outline-primary <?= $df == 'today' ? 'active' : '' ?>">Today</button>-->
                        <!--        <button type="submit" name="date_filter" value="yesterday" class="btn btn-outline-primary <?= $df == 'yesterday' ? 'active' : '' ?>">Yesterday</button>-->
                        <!--        <button type="submit" name="date_filter" value="week" class="btn btn-outline-primary <?= $df == 'week' ? 'active' : '' ?>">Week</button>-->
                        <!--        <button type="submit" name="date_filter" value="month" class="btn btn-outline-primary <?= $df == 'month' ? 'active' : '' ?>">Month</button>-->
                        <!--    </div>-->
                        </div>
                        <div class="col-md-3 my-1 text-right">
                             <a href="user-table.php" class="btn btn-sm btn-light text-muted">Reset</a>
                             <button type="submit" class="btn btn-sm btn-primary">Apply</button>
                        </div>
                    </div>
                    <?php if(isset($_GET['sort'])): ?>
                        <input type="hidden" name="sort" value="<?= $_GET['sort'] ?>">
                        <input type="hidden" name="dir" value="<?= $_GET['dir'] ?>">
                    <?php endif; ?>
                </form>
            </div>

            <div class="table-wrapper">
                <table class="table table-divo">
                    <thead>
                        <tr>
                            <?php 
                            function sortLink($col, $text, $cSort, $cDir, $nDir) {
                                $icon = ($cSort == $col) ? ($cDir == 'ASC' ? 'expand_less' : 'expand_more') : 'unfold_more';
                                $q = $_GET; $q['sort'] = $col; $q['dir'] = $nDir;
                                $url = '?' . http_build_query($q);
                                echo "<a href='$url'>$text <i class='material-icons'>$icon</i></a>";
                            }
                            ?>
                            <th><?= $data2['total_users'] ?? '0' ?></th>
                            <th><?php sortLink('fname', 'Name', $order_by, $order_dir, $next_dir); ?></th>
                            <th><?php sortLink('mobile', 'Mobile', $order_by, $order_dir, $next_dir); ?></th>
                            <th><?php sortLink('balance', 'Balance', $order_by, $order_dir, $next_dir); ?></th>
                            <th><?php sortLink('t_ref', 'Referral', $order_by, $order_dir, $next_dir); ?></th>
                            <th>Payments</th>
                            <th><?php sortLink('task_count', 'Task', $order_by, $order_dir, $next_dir); ?></th>
                            <th><?php sortLink('onlineStatus', 'Last Use', $order_by, $order_dir, $next_dir); ?></th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($rows)): ?>
                            <tr><td colspan="9" class="text-center p-4">No users found.</td></tr>
                        <?php else: ?>
                            <?php $index = 1; foreach ($rows as $row) : 
                                $ago = time_elapsed_string($row['onlineStatus']);
                                $full_date = !empty($row['onlineStatus']) ? date('d-M-y h:i A', $row['onlineStatus']) : 'Never';
                            ?>
                            <tr>
                                <td><?= $index++ ?></td>
                                <td class="font-weight-bold"><?= htmlspecialchars($row['fname']) ?></td>
                                <td><?= htmlspecialchars($row['mobile']) ?></td>
                                <td class="text-success font-weight-bold"><?= $row['balance'] ?></td>
                                <td><?= $row['t_ref'] ?></td>
                                
                                <td>
                                    <a href="history.php?user=<?= $row['mobile'] ?>" class="btn btn-sm btn-light border" style="min-width: 60px;">
                                        <?php if ($row['pay_pending'] > 0): ?>
                                            <?= $row['pay_total'] ?> / <span class="text-pending"><?= $row['pay_pending'] ?></span>
                                        <?php else: ?>
                                            <?= $row['pay_total'] ?>
                                        <?php endif; ?>
                                    </a>
                                </td>

                                <td><?= $row['task_count'] ?></td>
                                
                                <td>
                                    <span class="date-toggle" onclick="toggleDate(this)" 
                                          data-ago="<?= $ago ?>" 
                                          data-date="<?= $full_date ?>">
                                        <?= $ago ?>
                                    </span>
                                </td>

                                <td>
                                    <div class="btn-group-custom">
                                        <a href="user-profile.php?mobile=<?= $row['mobile'] ?>" class="btn btn-outline-primary" title="Profile">
                                            <span class="material-icons" style="font-size:18px">person</span>
                                        </a>
                                        <a href="history.php?user=<?= $row['mobile'] ?>" class="btn btn-outline-info" title="History">
                                            <span class="material-icons" style="font-size:18px">visibility</span>
                                        </a>
                                        <a href="refer.php?user=<?= $row['mobile'] ?>" class="btn btn-outline-secondary" title="Referrals">
                                            <span class="material-icons" style="font-size:18px">check</span>
                                        </a>
                                        <?php if ($row['i_click'] <= $invalid_limit) : ?>
                                            <a href="?block&id=<?= $row['id'] ?>" class="btn btn-outline-danger" title="Block" onclick="return confirm('Block this user?')">
                                                <span class="material-icons" style="font-size:18px">block</span>
                                            </a>
                                        <?php else : ?>
                                            <a href="?unblock&id=<?= $row['id'] ?>" class="btn btn-outline-success" title="Unblock">
                                                <span class="material-icons" style="font-size:18px">check_circle</span>
                                            </a>
                                        <?php endif ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach ?>
                        <?php endif ?>
                    </tbody>
                </table>
            </div>
        </section>
    </main>

    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        function toggleDate(element) {
            const current = element.innerText;
            const ago = element.getAttribute('data-ago');
            const date = element.getAttribute('data-date');
            
            // Swap content
            if (current === ago) {
                element.innerText = date;
                element.style.color = '#333';
                element.style.fontWeight = 'bold';
            } else {
                element.innerText = ago;
                element.style.color = '';
                element.style.fontWeight = 'normal';
            }
        }
    </script>
    <?php include('footer.php') ?>
</body>
</html>