<?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 = "Payments Manager";


if (isset($_GET['id'])) {
	$id = $_GET['id'];
	$user = $_GET['user'];
	$sql = "UPDATE users SET pending = 0 WHERE mobile = $user;";
	$sql .= "UPDATE payments SET status = 'Paid' WHERE id = $id";
	
	if ($conn -> multi_query($sql) === TRUE) {
		//snack ("success", "Success");
		header('location: payments.php?success');
	}
	
}

// --- 2. Helper: Time Ago ---
function time_elapsed_string($timestamp) {
    if(empty($timestamp) || $timestamp < 1000) return "";
    $etime = time() - $timestamp;
    if ($etime < 1) return 'Just now';
    
    $a = array( 365 * 24 * 60 * 60  =>  'y',
                 30 * 24 * 60 * 60  =>  'm',
                      24 * 60 * 60  =>  'd',
                           60 * 60  =>  'h',
                                60  =>  'min',
                                 1  =>  's');
    
    foreach ($a as $secs => $str) {
        $d = $etime / $secs;
        if ($d >= 1) {
            $r = round($d);
            return $r . ' ' . $str . ' ago';
        }
    }
}

// --- 3. Handle Deletions ---
if (isset($_GET['delete_all'])) {
    $sql = "TRUNCATE TABLE payments"; 
    if ($conn->query($sql) === TRUE) snack("success", "All records deleted");
}

if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $sql = "DELETE FROM payments WHERE id = $id";
    if ($conn->query($sql) === TRUE) snack("success", "Deleted Successfully");
    else snack("error", "Failed: " . $conn->error);
}

// --- 4. Build Filters & Sorting ---
$where = "WHERE 1=1";
$order_by = "p.date";
$order_dir = "DESC";

if (!empty($_GET['search'])) {
    $s = $conn->real_escape_string($_GET['search']);
    $where .= " AND (p.number LIKE '%$s%' OR p.mnumber LIKE '%$s%' OR p.method LIKE '%$s%')";
}
if (!empty($_GET['status']) && $_GET['status'] != 'all') {
    $st = $conn->real_escape_string($_GET['status']);
    $where .= " AND p.status = '$st'";
}
if (!empty($_GET['date_filter'])) {
    $df = $_GET['date_filter'];
    if ($df == 'today') $where .= " AND DATE(p.date) = CURDATE()"; 
    elseif ($df == 'yesterday') $where .= " AND DATE(p.date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
    elseif ($df == 'week') $where .= " AND p.date >= DATE_SUB(NOW(), INTERVAL 1 WEEK)";
    elseif ($df == 'month') $where .= " AND p.date >= DATE_SUB(NOW(), INTERVAL 1 MONTH)";
    elseif ($df == 'custom' && !empty($_GET['start']) && !empty($_GET['end'])) {
        $start = $conn->real_escape_string($_GET['start']);
        $end = $conn->real_escape_string($_GET['end']);
        $where .= " AND DATE(p.date) BETWEEN '$start' AND '$end'";
    }
}

// Sorting
$valid_sorts = ['id', 'date', 'mnumber', 'amount', 'method', 'status', 'balance', 'task_count'];
if (isset($_GET['sort']) && in_array($_GET['sort'], $valid_sorts)) {
    $sort_key = $_GET['sort'];
    if($sort_key == 'date') $sort_key = 'p.date';
    if($sort_key == 'balance') $sort_key = 'u.balance';
    $order_by = $sort_key;
    $order_dir = (isset($_GET['dir']) && $_GET['dir'] == 'ASC') ? 'ASC' : 'DESC';
}
$next_dir = ($order_dir == 'ASC') ? 'DESC' : 'ASC';

// --- 5. Main Query ---
if (isset($multi_task) && $multi_task == 1) {
    $task_sql = "(u.today_task1 + u.today_task2 + u.today_task3 + u.today_task4)";
} else {
    $task_sql = "u.today_task";
}

$sql = "SELECT p.*, 
        u.balance, 
        u.onlineStatus,
        $task_sql as task_count,
        (SELECT COUNT(*) FROM payments p2 WHERE p2.mnumber = p.mnumber) as user_total_pay,
        (SELECT COUNT(*) FROM payments p3 WHERE p3.mnumber = p.mnumber AND p3.status = 'Pending') as user_pending_pay
        FROM payments p
        LEFT JOIN users u ON p.mnumber = u.mobile
        $where
        ORDER BY $order_by $order_dir";

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

// Stats
$sql2 = "SELECT
        (SELECT COUNT(1) FROM payments p $where) AS payment_count,
        (SELECT SUM(amount) FROM payments p $where AND status = 'Paid') AS paid_amount,
        (SELECT SUM(amount) FROM payments p $where AND status = 'Pending') AS pending_amount
        FROM dual";
$data2 = $conn->query($sql2)->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 { padding: 1em; padding-bottom: 80px; }
        table { white-space: nowrap; }
        tbody > tr { cursor: pointer; transition: background 0.1s; }
        tbody > tr:hover { background: #e9ecef !important; }
        tbody > tr:nth-child(even) { background: #F8F8F8; }
        
        .Paid { color: #28a745; font-weight: 600; background: rgba(40, 167, 69, 0.1); padding: 4px 8px; border-radius: 4px; }
        .Pending { color: #dc3545; font-weight: 600; background: rgba(220, 53, 69, 0.1); padding: 4px 8px; border-radius: 4px; }
        
        .filter-bar { background: #fff; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); margin-bottom: 20px; }
        
        /* Action Buttons Group */
        .btn-group-custom { display: flex; }
        .btn-group-custom .btn { border-radius: 0; margin-left: -1px; padding: 0.25rem 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; }
        
        /* FAB */
        .fab-delete { position: fixed; bottom: 20px; right: 20px; width: 56px; height: 56px; border-radius: 50%; background: #dc3545; color: white; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 10px rgba(0,0,0,0.3); cursor: pointer; z-index: 1000; }
        
        /* Modal Styles */
        .modal-label { font-size: 0.8rem; text-transform: uppercase; color: #888; margin-bottom: 0; }
        .modal-value { font-size: 1.1rem; font-weight: 500; color: #333; margin-bottom: 15px; word-break: break-all; }
        .copy-hint { font-size: 0.7rem; color: #007bff; cursor: pointer; margin-left: 5px; }
        
        th a { color: #333; display: flex; align-items: center; text-decoration: none; }
    </style>
</head>
<body class="bg-gray-200">
    <?php include("header.php") ?>
    
    <main>
        <section class="fr-container fr-lg" style="width:100%">
            
            <div class="filter-bar">
                <form method="GET">
                    <div class="form-row align-items-end">
                        <div class="col-md-3 mb-2">
                            <label class="small text-muted">Search</label>
                            <input type="text" name="search" class="form-control form-control-sm" placeholder="User, Number, Method..." 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">Range</label>
                             <div class="btn-group btn-group-sm w-100">
                                <button type="submit" name="date_filter" value="today" class="btn btn-outline-primary <?= ($_GET['date_filter']??'')=='today'?'active':'' ?>">Today</button>
                                <button type="submit" name="date_filter" value="yesterday" class="btn btn-outline-primary <?= ($_GET['date_filter']??'')=='yesterday'?'active':'' ?>">Yest</button>
                                <button type="submit" name="date_filter" value="week" class="btn btn-outline-primary <?= ($_GET['date_filter']??'')=='week'?'active':'' ?>">Week</button>
                            </div>
                        </div>
                         <div class="col-md-4 mb-2">
                             <label class="small text-muted">Custom / Action</label>
                             <div class="input-group input-group-sm">
                                 <input type="date" name="start" class="form-control" value="<?= $_GET['start'] ?? '' ?>">
                                 <input type="date" name="end" class="form-control" value="<?= $_GET['end'] ?? '' ?>">
                                 <div class="input-group-append">
                                     <button type="submit" name="date_filter" value="custom" class="btn btn-primary">Go</button>
                                     <a href="payments.php" class="btn btn-light border">Reset</a>
                                 </div>
                             </div>
                        </div>
                    </div>
                </form>
            </div>

            <div class="row mb-3">
                <div class="col-4"><div class="bg-white p-2 rounded shadow-sm text-center border-left border-primary"><small class="text-muted d-block">Requests</small><h5 class="mb-0 text-primary"><?= number_format($data2['payment_count'] ?? 0) ?></h5></div></div>
                <div class="col-4"><div class="bg-white p-2 rounded shadow-sm text-center border-left border-success"><small class="text-muted d-block">Paid</small><h5 class="mb-0 text-success"><?= number_format($data2['paid_amount'] ?? 0) ?></h5></div></div>
                <div class="col-4"><div class="bg-white p-2 rounded shadow-sm text-center border-left border-danger"><small class="text-muted d-block">Pending</small><h5 class="mb-0 text-danger"><?= number_format($data2['pending_amount'] ?? 0) ?></h5></div></div>
            </div>

            <section 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' style='font-size:14px'>$icon</i></a>";
                            } ?>
                            <th>#</th>
                            <th><?php sortLink('date', 'Date', $order_by, $order_dir, $next_dir); ?></th>
                            <th><?php sortLink('mnumber', 'User / Pay Num', $order_by, $order_dir, $next_dir); ?></th>
                            <th><?php sortLink('amount', 'Amt', $order_by, $order_dir, $next_dir); ?></th>
                            <th>User Stats</th>
                            <th><?php sortLink('status', 'Status', $order_by, $order_dir, $next_dir); ?></th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($rows)): ?>
                            <tr><td colspan="7" class="text-center py-4">No payments found.</td></tr>
                        <?php else: ?>
                            <?php $index = 1; foreach ($rows as $row) : 
                                $ts = strtotime($row['date']);
                                $date_display = date("d M H:i", $ts);
                                $time_ago = time_elapsed_string($ts);
                                
                                // JSON encode row data for the popup
                                $jsonData = htmlspecialchars(json_encode($row), ENT_QUOTES, 'UTF-8');
                            ?>
                            <tr onclick="openDetails(<?= $jsonData ?>)">
                                <td><?= $index++ ?></td>
                                <td><?= $date_display ?><br><small class="text-muted"><?= $time_ago ?></small></td>
                                <td>
                                    <strong><?= htmlspecialchars($row['mnumber']) ?></strong><br>
                                    <span class="text-info"><?= htmlspecialchars($row['number']) ?></span> <small>(<?= $row['method'] ?>)</small>
                                </td>
                                <td class="font-weight-bold"><?= $row['amount'] ?></td>
                                <td style="font-size:0.9em">
                                    Bal: <span class="text-success"><?= $row['balance'] ?? 0 ?></span><br>
                                    Task: <?= $row['task_count'] ?? 0 ?>
                                </td>
                                <td><span class="<?= $row['status'] ?>"><?= $row['status'] ?></span></td>
                                
                                <td onclick="event.stopPropagation()">
                                    <div class="btn-group-custom">
                                        <a href="payments.php?id=<?= $row['id'] ?>&user=<?= $row['mnumber'] ?>" class="btn btn-outline-success" title="Mark Paid">
                                            <span class="material-icons" style="font-size:18px">check_circle</span>
                                        </a>
                                        <a href="user-profile.php?mobile=<?= $row['mnumber'] ?>" class="btn btn-outline-primary" title="Profile">
                                            <span class="material-icons" style="font-size:18px">person</span>
                                        </a>
                                        <a href="payments.php?delete=<?= $row['id'] ?>" class="btn btn-outline-danger" onclick="return confirm('Delete?')" title="Delete">
                                            <span class="material-icons" style="font-size:18px">delete</span>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </section>
        </section>
    </main>

    <a onclick="delete_all()" class="fab-delete"><span class="material-icons">delete_forever</span></a>

    <div class="modal fade" id="detailModal" tabindex="-1" role="dialog">
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Transaction Details</h5>
            <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
          </div>
          <div class="modal-body">
            <div class="row">
                <div class="col-6">
                    <p class="modal-label">Amount</p>
                    <p class="modal-value text-primary h4" id="m_amount"></p>
                </div>
                <div class="col-6">
                    <p class="modal-label">Status</p>
                    <p class="modal-value" id="m_status"></p>
                </div>
                <div class="col-12"><hr></div>
                
                <div class="col-12 mb-3">
                    <p class="modal-label">Payment Number (Click to Copy)</p>
                    <div class="p-2 bg-light border rounded d-flex justify-content-between align-items-center" 
                         onclick="copyToClipboard(document.getElementById('m_paynum').innerText)" style="cursor:pointer">
                        <span id="m_paynum" class="h5 mb-0 text-dark font-weight-bold"></span>
                        <span class="material-icons text-muted">content_copy</span>
                    </div>
                </div>

                <div class="col-6">
                    <p class="modal-label">User Mobile</p>
                    <p class="modal-value" id="m_user"></p>
                </div>
                <div class="col-6">
                    <p class="modal-label">Method</p>
                    <p class="modal-value" id="m_method"></p>
                </div>
                <div class="col-6">
                    <p class="modal-label">Date</p>
                    <p class="modal-value" id="m_date" style="font-size:0.9rem"></p>
                </div>
                <div class="col-6">
                    <p class="modal-label">ID</p>
                    <p class="modal-value" id="m_id"></p>
                </div>
            </div>
            
            <div class="alert alert-secondary mt-2">
                <strong>User Stats:</strong> 
                Balance: <span id="m_bal"></span> | 
                Tasks: <span id="m_task"></span> | 
                Last Active: <span id="m_last"></span>
            </div>
          </div>
          <div class="modal-footer">
            <a href="#" id="btn_pay" class="btn btn-success">Pay Now</a>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
    // Open Modal and Populate Data
    function openDetails(data) {
        $('#m_id').text('#' + data.id);
        $('#m_amount').text(data.amount);
        $('#m_status').html('<span class="'+data.status+'">' + data.status + '</span>');
        $('#m_paynum').text(data.number);
        $('#m_user').text(data.mnumber);
        $('#m_method').text(data.method);
        $('#m_date').text(data.date);
        
        // Stats
        $('#m_bal').text(data.balance || '0');
        $('#m_task').text(data.task_count || '0');
        
        // Last Active Formatting
        let last = 'Never';
        if(data.onlineStatus > 1000) {
            let date = new Date(data.onlineStatus * 1000);
            last = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
        }
        $('#m_last').text(last);

        // Update Pay Button Link
        $('#btn_pay').attr('href', 'payments.php?id=' + data.id + '&user=' + data.mnumber);

        $('#detailModal').modal('show');
    }

    // Copy to Clipboard
    function copyToClipboard(text) {
        navigator.clipboard.writeText(text).then(function() {
            const Toast = Swal.mixin({
                toast: true, position: 'top-end', showConfirmButton: false, timer: 1500,
                didOpen: (toast) => { toast.addEventListener('mouseenter', Swal.stopTimer); toast.addEventListener('mouseleave', Swal.resumeTimer) }
            })
            Toast.fire({ icon: 'success', title: 'Number Copied!' });
        }, function(err) {
            console.error('Async: Could not copy text: ', err);
        });
    }

    function delete_all() {
        Swal.fire({
            title: 'Delete ALL?', text: "Irreversible action!", icon: 'warning',
            showCancelButton: true, confirmButtonColor: '#d33', confirmButtonText: 'Yes, DELETE ALL'
        }).then((result) => { if (result.isConfirmed) window.location.replace("?delete_all"); })
    }
    </script>
    
    <?php if (isset($_GET['success'])) : ?> <p class="snackbar success">Success</p> <?php endif ?>
</body>
</html>