<?php
/* =========================================================
   AGENT MANAGER ULTIMATE - FIXED Z-INDEX & NULL DATA
   ========================================================= */
session_start();
if (!isset($_SESSION['unohs'])) {
    header("location:index.php?msg=unauthorized");
    exit;
}
include("conn.php");
date_default_timezone_set('Asia/Kolkata'); 

// --- 1. AJAX HANDLER: FETCH USER FULL DETAILS ---
if (isset($_POST['action']) && $_POST['action'] == 'get_details') {
    $uid = mysqli_real_escape_string($conn, $_POST['uid']);
    
    // FETCH DATA
    $q = mysqli_query($conn, "
        SELECT 
            u.mobile, u.owncode, u.code as upline, u.createdate,
            w.motta as wallet,
            k.khatesankhye as acc, k.kod as ifsc
        FROM shonu_subjects u
        LEFT JOIN shonu_kaichila w ON u.id = w.balakedara
        LEFT JOIN khate k ON u.id = k.byabaharkarta
        WHERE u.id='$uid'
    ");
    
    $basic = mysqli_fetch_assoc($q);
    
    // REFERRAL LIST
    $owncode = $basic['owncode'];
    $ref_q = mysqli_query($conn, "SELECT id, mobile, createdate FROM shonu_subjects WHERE code='$owncode' ORDER BY id DESC LIMIT 50");
    
    $ref_list = [];
    while($row = mysqli_fetch_assoc($ref_q)){
        $ref_list[] = $row;
    }
    
    echo json_encode([
        'status' => 'success',
        'basic' => $basic,
        'refers' => $ref_list,
        'total_ref' => mysqli_num_rows(mysqli_query($conn, "SELECT id FROM shonu_subjects WHERE code='$owncode'"))
    ]);
    exit(); 
}

// --- 2. ADD AGENT ---
if (isset($_POST['add_agent'])) {
    $serial = mysqli_real_escape_string($conn, $_POST['serial']); 
    $type = mysqli_real_escape_string($conn, $_POST['type']); 
    $salary = mysqli_real_escape_string($conn, $_POST['salary']);
    
    $chk_user = mysqli_query($conn, "SELECT id FROM `shonu_subjects` WHERE `id`='$serial' OR `mobile`='$serial'");
    if (mysqli_num_rows($chk_user) > 0) {
        $u_data = mysqli_fetch_assoc($chk_user);
        $uid = $u_data['id'];
        $chk_agent = mysqli_query($conn, "SELECT * FROM `tb_agent` WHERE `userid`='$uid' AND `status`='1'");
        if (mysqli_num_rows($chk_agent) == 0) {
            $date = date("Y-m-d H:i:s");
            $query = "INSERT INTO `tb_agent` (`userid`, `mobile`, `createdate`, `status`, `type`, `salary`) VALUES ('$uid', '$serial', '$date', '1', '$type', '$salary')";
            if (mysqli_query($conn, $query)) { $msg = "✅ Agent Hired Successfully!"; } else { $err = "❌ Database Error!"; }
        } else { $err = "⚠️ Already an Agent!"; }
    } else { $err = "❌ User Not Found!"; }
}

// --- 3. DELETE AGENT ---
if (isset($_GET['del_id'])) {
    $del_id = mysqli_real_escape_string($conn, $_GET['del_id']);
    mysqli_query($conn, "UPDATE tb_agent SET status='2' WHERE userid='$del_id'");
    echo "<script>window.location.href='agentuser.php';</script>";
}

// --- STATS ---
$total_agents = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as t FROM tb_agent WHERE status='1'"))['t'];
$total_liability = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(salary) as t FROM tb_agent WHERE status='1'"))['t'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=1200, initial-scale=0.1">
    <title>Agent Hiring Manager</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="vendors/base/vendor.bundle.base.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="css/style.css">

    <style>
        :root { --bg-color: #f3f4f7; --primary: #6c5ce7; --secondary: #a29bfe; --dark: #2d3436; --white: #ffffff; }
        body { background-color: var(--bg-color); font-family: 'Nunito', sans-serif; color: var(--dark); }
        .content-wrapper { padding: 30px; }

        /* CARDS */
        .stats-container { display: flex; gap: 20px; margin-bottom: 30px; }
        .stat-card { flex: 1; padding: 25px; border-radius: 20px; color: white; position: relative; box-shadow: 0 15px 30px rgba(0,0,0,0.15); overflow: hidden; }
        .bg-1 { background: linear-gradient(135deg, #6c5ce7, #a29bfe); }
        .bg-2 { background: linear-gradient(135deg, #00b894, #55efc4); }
        .bg-timer { background: linear-gradient(135deg, #ff9f43, #ff6b6b); }
        .stat-card h3 { font-size: 2.5rem; font-weight: 900; margin: 5px 0 0 0; }
        .stat-card p { font-size: 0.9rem; text-transform: uppercase; font-weight: 800; opacity: 0.9; margin: 0; }
        .timer-text { font-family: 'Courier New', monospace; font-size: 2.2rem !important; letter-spacing: 2px; }

        /* ACTION & TABLE CARDS */
        .action-card, .table-card { background: var(--white); border-radius: 25px; padding: 30px; box-shadow: 0 10px 30px rgba(0,0,0,0.08); margin-bottom: 30px; border: 1px solid #fff; }
        .modern-input { width: 100%; padding: 15px; border: 2px solid #eee; border-radius: 12px; font-weight: 700; outline: none; transition: 0.3s; background: #f9f9f9; }
        .modern-input:focus { border-color: var(--primary); background: #fff; }
        .btn-add { background: linear-gradient(135deg, #6c5ce7, #a29bfe); color: white; border: none; padding: 15px 30px; border-radius: 12px; font-weight: 800; width: 100%; cursor: pointer; transition: 0.3s; }
        .btn-add:hover { transform: translateY(-3px); }

        /* TABLE */
        .table-responsive { overflow-x: auto; }
        table.dataTable { width: 100% !important; border-collapse: separate; border-spacing: 0 10px; }
        table.dataTable thead th { background: transparent; padding: 15px; font-weight: 800; color: #888; text-transform: uppercase; border: none; }
        table.dataTable tbody tr { background: #fff; box-shadow: 0 5px 15px rgba(0,0,0,0.03); border-radius: 15px; transition: 0.2s; }
        table.dataTable tbody tr:hover { transform: scale(1.01); background: #fdfdfd; z-index: 5; position: relative; }
        table.dataTable tbody td { padding: 18px 15px; font-weight: 700; color: #444; border: none; vertical-align: middle; }
        table.dataTable tbody td:first-child { border-radius: 15px 0 0 15px; }
        table.dataTable tbody td:last-child { border-radius: 0 15px 15px 0; }

        /* BADGES & BUTTONS */
        .badge-type { background: #e0f2f1; color: #00695c; padding: 5px 12px; border-radius: 8px; font-weight: 900; text-transform: uppercase; font-size: 0.8rem; }
        .badge-salary { background: #e8f5e9; color: #2e7d32; padding: 5px 12px; border-radius: 8px; font-weight: 900; font-size: 1rem; }
        .btn-icon { width: 35px; height: 35px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; transition: 0.3s; border: none; cursor: pointer; text-decoration: none; }
        .btn-info { background: #e3f2fd; color: #1565c0; }
        .btn-del { background: #ffebee; color: #c62828; margin-left: 5px; }

        /* 🔥 MODAL STYLES (Z-INDEX FIX) 🔥 */
        .modal { z-index: 1000000 !important; } /* Higher than sidebar */
        .modal-backdrop { z-index: 999999 !important; }
        .modal-dialog { margin-top: 10vh; display: flex; align-items: center; justify-content: center; }
        .modal-content { border-radius: 20px; border: none; box-shadow: 0 25px 80px rgba(0,0,0,0.5); width: 100%; border: 1px solid rgba(0,0,0,0.1); }
        .modal-header { background: linear-gradient(135deg, #6c5ce7, #a29bfe); color: white; border-radius: 20px 20px 0 0; }
        
        .data-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px; }
        .data-box { background: #f8f9fa; padding: 15px; border-radius: 12px; border: 1px solid #eee; }
        .data-label { display: block; font-size: 0.8rem; color: #888; font-weight: 700; text-transform: uppercase; }
        .data-val { display: block; font-size: 1.1rem; color: #333; font-weight: 900; word-break: break-all; }
        
        .refer-list { max-height: 200px; overflow-y: auto; background: #fff; border: 1px solid #eee; border-radius: 12px; }
        .refer-item { padding: 10px 15px; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; }
        
        .navbar { background: #fff !important; box-shadow:0 5px 20px rgba(0,0,0,0.03); }
    </style>
</head>

<body>
<div class="container-scroller">
    <nav class="navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row">
        <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-center">
            <h3 style="color:var(--primary); font-weight:900; margin:0; letter-spacing:-1px;">AGENT<span style="color:var(--dark);">MANAGER</span></h3>
        </div>
        <div class="navbar-menu-wrapper d-flex align-items-center justify-content-end">
            <a class="nav-link" href="logout.php" style="font-weight:800; color:#333;"><i class="fa-solid fa-power-off" style="color:#ff7675;"></i> Logout</a>
        </div>
    </nav>

    <div class="container-fluid page-body-wrapper">
        <nav class="sidebar sidebar-offcanvas" id="sidebar" style="background:#fff;">
            <div class="user-profile" style="text-align:center; padding:30px 15px;">
                <img src="images/faces/face28.png" style="width:80px; border-radius:50%; border:4px solid #e0e7ff;">
                <div class="user-name" style="font-weight:900; margin-top:15px;">AB Coders</div>
            </div>
            <?php include 'compass.php'; ?>
        </nav>

        <div class="main-panel">
            <div class="content-wrapper">
                
                <div class="stats-container">
                    <div class="stat-card bg-1"><p>Active Agents</p><h3><?php echo number_format($total_agents); ?></h3><i class="fa-solid fa-user-tie stat-icon"></i></div>
                    <div class="stat-card bg-2"><p>Total Liability</p><h3>₹<?php echo number_format($total_liability); ?></h3><i class="fa-solid fa-money-bill-wave stat-icon"></i></div>
                    <div class="stat-card bg-timer"><p>Next Payout In</p><h3 id="countdown" class="timer-text">00:00:00</h3><i class="fa-solid fa-clock stat-icon"></i></div>
                </div>

                <div class="row">
                    <div class="col-md-4">
                        <div class="action-card">
                            <div style="font-size:1.3rem; font-weight:900; color:var(--primary); margin-bottom:20px;"><i class="fa-solid fa-user-plus"></i> Hire Agent</div>
                            <?php if(isset($msg)) echo "<div style='color:green; font-weight:bold; margin-bottom:10px;'>$msg</div>"; ?>
                            <?php if(isset($err)) echo "<div style='color:red; font-weight:bold; margin-bottom:10px;'>$err</div>"; ?>
                            <form method="post">
                                <div style="margin-bottom:15px;"><label style="font-weight:700; color:#555;">UID / Mobile</label><input name="serial" type="text" placeholder="Enter UID" required class="modern-input"/></div>
                                <div style="margin-bottom:15px;"><label style="font-weight:700; color:#555;">Salary</label><input name="salary" type="number" placeholder="₹ Amount" required class="modern-input"/></div>
                                <div style="margin-bottom:20px;">
                                    <label style="font-weight:700; color:#555;">Type</label>
                                    <select name="type" required class="modern-input"><option value="day">Daily</option><option value="week">Weekly</option><option value="month">Monthly</option></select>
                                </div>
                                <button type="submit" name="add_agent" class="btn-add">HIRE AGENT</button>
                            </form>
                        </div>
                    </div>

                    <div class="col-md-8">
                        <div class="table-card">
                            <h4 style="font-weight:900; margin-bottom:20px; color:var(--primary);">Active Agents</h4>
                            <div class="table-responsive">
                                <table id="agentTable" class="table">
                                    <thead><tr><th>Agent ID</th><th>Mobile</th><th>Salary</th><th>Type</th><th>Info</th><th>Action</th></tr></thead>
                                    <tbody>
                                        <?php
                                        $q = mysqli_query($conn, "SELECT userid, mobile, salary, type, createdate FROM tb_agent WHERE status='1'");
                                        while ($row = mysqli_fetch_assoc($q)) {
                                        ?>
                                        <tr>
                                            <td><span style="background:#eee; padding:5px 10px; border-radius:5px; font-weight:800;">#<?php echo $row['userid']; ?></span></td>
                                            <td><?php echo $row['mobile']; ?></td>
                                            <td><span class="badge-salary">₹<?php echo $row['salary']; ?></span></td>
                                            <td><span class="badge-type"><?php echo strtoupper($row['type']); ?></span></td>
                                            <td><button class="btn-icon btn-info" onclick="fetchDetails('<?php echo $row['userid']; ?>')"><i class="fa-solid fa-info"></i></button></td>
                                            <td><a href="agentuser.php?del_id=<?php echo $row['userid']; ?>" class="btn-icon btn-del" onclick="return confirm('Remove Agent?');"><i class="fa-solid fa-trash"></i></a></td>
                                        </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <div class="table-card" style="border-left:5px solid #00b894;">
                            <h4 style="font-weight:900; margin-bottom:20px; color:#00b894;">Today's Payouts</h4>
                            <div class="table-responsive">
                                <table class="table">
                                    <thead><tr><th>Agent ID</th><th>Amount</th><th>Time</th><th>Status</th></tr></thead>
                                    <tbody>
                                        <?php
                                        $today = date("Y-m-d");
                                        $hq = mysqli_query($conn, "SELECT * FROM dailysalary WHERE DATE(createdate)='$today' ORDER BY id DESC LIMIT 5");
                                        if(mysqli_num_rows($hq)>0){
                                            while ($h = mysqli_fetch_assoc($hq)) {
                                                echo "<tr><td><b>#{$h['userid']}</b></td><td style='color:green;'>₹{$h['salary']}</td><td>".date("h:i A", strtotime($h['createdate']))."</td><td><span class='badge-salary'>PAID</span></td></tr>";
                                            }
                                        } else { echo "<tr><td colspan='4' align='center'>No payouts today.</td></tr>"; }
                                        ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <footer class="footer" style="background:transparent; border:none; text-align:center;"><span class="text-muted" style="font-weight:700;">Copyright © 2026 AB Coders</span></footer>
        </div>
    </div>
</div>

<div id="infoModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" style="font-weight:900;"><i class="fa-solid fa-id-card"></i> Agent Full Profile</h5>
                <button type="button" class="close" data-dismiss="modal" style="color:white; opacity:1;">&times;</button>
            </div>
            <div class="modal-body" style="padding:30px;">
                <div id="modalLoader" style="text-align:center; display:none;"><i class="fa-solid fa-spinner fa-spin fa-3x" style="color:var(--primary);"></i></div>
                <div id="modalContent">
                    <div class="data-grid">
                        <div class="data-box"><span class="data-label">Mobile</span><span class="data-val" id="d_mobile">...</span></div>
                        <div class="data-box"><span class="data-label">Own Code</span><span class="data-val" id="d_code" style="color:#6c5ce7;">...</span></div>
                        <div class="data-box"><span class="data-label">Wallet Bal</span><span class="data-val" id="d_wallet" style="color:green;">...</span></div>
                        <div class="data-box"><span class="data-label">Upline</span><span class="data-val" id="d_upline">...</span></div>
                        <div class="data-box"><span class="data-label">Account No</span><span class="data-val" id="d_acc">...</span></div>
                        <div class="data-box"><span class="data-label">IFSC Code</span><span class="data-val" id="d_ifsc">...</span></div>
                    </div>
                    
                    <h6 style="font-weight:800; margin-top:20px; margin-bottom:10px;">👥 Referred Users List (<span id="d_count">0</span>)</h6>
                    <div class="refer-list" id="d_ref_list"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="vendors/base/vendor.bundle.base.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<script>
    $(document).ready(function() { $('#agentTable').DataTable({ "pageLength": 10, "ordering": false }); });

    function updateTimer() {
        const now = new Date();
        const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
        const diff = tomorrow - now;
        const h = Math.floor((diff / (1000 * 60 * 60)) % 24);
        const m = Math.floor((diff / (1000 * 60)) % 60);
        const s = Math.floor((diff / 1000) % 60);
        document.getElementById("countdown").innerText = (h < 10 ? "0"+h : h) + ":" + (m < 10 ? "0"+m : m) + ":" + (s < 10 ? "0"+s : s);
    }
    setInterval(updateTimer, 1000); updateTimer();

    function fetchDetails(uid) {
        $('#infoModal').modal('show');
        $('#modalContent').hide();
        $('#modalLoader').show();

        $.ajax({
            url: 'agentuser.php', type: 'POST',
            data: { action: 'get_details', uid: uid },
            dataType: 'json',
            success: function(res) {
                if(res.status === 'success') {
                    // Inject Data with Null Checks
                    $('#d_mobile').text(res.basic.mobile || 'Null');
                    $('#d_code').text(res.basic.owncode || 'Null');
                    $('#d_wallet').text('₹' + (res.basic.wallet || '0.00'));
                    $('#d_upline').text(res.basic.upline || 'None');
                    $('#d_acc').text(res.basic.acc || 'Not Linked');
                    $('#d_ifsc').text(res.basic.ifsc || 'Not Linked');
                    $('#d_count').text(res.total_ref);

                    let listHtml = '';
                    if(res.refers.length > 0) {
                        res.refers.forEach(user => {
                            listHtml += `<div class="refer-item"><span style="font-weight:bold;">#${user.id} - ${user.mobile}</span><span style="font-size:0.8rem; color:#888;">${user.createdate}</span></div>`;
                        });
                    } else { listHtml = '<div style="padding:15px; text-align:center; color:#888;">No referrals found.</div>'; }
                    $('#d_ref_list').html(listHtml);

                    $('#modalLoader').hide();
                    $('#modalContent').fadeIn();
                }
            }
        });
    }
</script>
</body>
</html>