<?php
session_start();
require_once "../config.php";

if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] !== 'agency') {
    header("Location: ../login.php");
    exit;
}

function e($v) {
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}

$agencyId = (int)$_SESSION['user_id'];

/* CSRF */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

$msg = $_SESSION['flash_success'] ?? '';
$error = $_SESSION['flash_error'] ?? '';
unset($_SESSION['flash_success'], $_SESSION['flash_error']);

$activeTab = $_GET['tab'] ?? 'pending';
if (!in_array($activeTab, ['pending', 'approved'], true)) {
    $activeTab = 'pending';
}

/* =========================================================
   HANDLE APPROVE / REJECT
========================================================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postedToken = $_POST['csrf_token'] ?? '';

    if (!hash_equals($_SESSION['csrf_token'], $postedToken)) {
        $_SESSION['flash_error'] = 'Invalid request.';
        header("Location: " . $_SERVER['PHP_SELF'] . "?tab=" . urlencode($activeTab));
        exit;
    }

    if (isset($_POST['approve_id'])) {
        $id = (int)$_POST['approve_id'];

        $stmt = $conn->prepare("
            UPDATE users
            SET is_approved = 1,
                approver_id = ?
            WHERE id = ?
              AND role = 'sales_manager'
              AND agency_id = ?
        ");

        if ($stmt) {
            $stmt->bind_param("iii", $agencyId, $id, $agencyId);
            if ($stmt->execute() && $stmt->affected_rows >= 0) {
                $_SESSION['flash_success'] = 'Sales Manager approved successfully.';
            } else {
                $_SESSION['flash_error'] = 'Unable to approve this request.';
            }
            $stmt->close();
        } else {
            $_SESSION['flash_error'] = 'Database error while approving.';
        }

        header("Location: " . $_SERVER['PHP_SELF'] . "?tab=pending");
        exit;
    }

    if (isset($_POST['reject_id'])) {
        $id = (int)$_POST['reject_id'];

        $stmt = $conn->prepare("
            UPDATE users
            SET is_approved = 2,
                approver_id = ?
            WHERE id = ?
              AND role = 'sales_manager'
              AND agency_id = ?
        ");

        if ($stmt) {
            $stmt->bind_param("iii", $agencyId, $id, $agencyId);
            if ($stmt->execute() && $stmt->affected_rows >= 0) {
                $_SESSION['flash_success'] = 'Sales Manager rejected successfully.';
            } else {
                $_SESSION['flash_error'] = 'Unable to reject this request.';
            }
            $stmt->close();
        } else {
            $_SESSION['flash_error'] = 'Database error while rejecting.';
        }

        header("Location: " . $_SERVER['PHP_SELF'] . "?tab=pending");
        exit;
    }
}

/* =========================================================
   COUNTS
========================================================= */
$pendingCount = 0;
$approvedCount = 0;
$rejectedCount = 0;

$stmt = $conn->prepare("
    SELECT
        SUM(CASE WHEN is_approved = 0 THEN 1 ELSE 0 END) AS pending_count,
        SUM(CASE WHEN is_approved = 1 THEN 1 ELSE 0 END) AS approved_count,
        SUM(CASE WHEN is_approved = 2 THEN 1 ELSE 0 END) AS rejected_count
    FROM users
    WHERE role = 'sales_manager'
    AND agency_id = ?
");

if ($stmt) {
    $stmt->bind_param("i", $agencyId);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        $pendingCount = (int)($row['pending_count'] ?? 0);
        $approvedCount = (int)($row['approved_count'] ?? 0);
        $rejectedCount = (int)($row['rejected_count'] ?? 0);
    }
    $stmt->close();
}

/* =========================================================
   PENDING LIST
========================================================= */
$pendingResult = null;
$stmt = $conn->prepare("
    SELECT id, name, email, requested_agency_id, is_approved, created_at
    FROM users
    WHERE role = 'sales_manager'
      AND is_approved = 0
      AND agency_id = ?
    ORDER BY id DESC
");

if ($stmt) {
    $stmt->bind_param("i", $agencyId);
    $stmt->execute();
    $pendingResult = $stmt->get_result();
}

/* =========================================================
   APPROVED LIST
========================================================= */
$approvedResult = null;
$stmt2 = $conn->prepare("
    SELECT id, name, email, requested_agency_id, is_approved, approver_id, created_at
    FROM users
    WHERE role = 'sales_manager'
      AND is_approved = 1
      AND agency_id = ?
    ORDER BY id DESC
");

if ($stmt2) {
    $stmt2->bind_param("i", $agencyId);
    $stmt2->execute();
    $approvedResult = $stmt2->get_result();
}

/* =========================================================
   REJECTED LIST
========================================================= */
$rejectedResult = null;

$stmt3 = $conn->prepare("
    SELECT id, name, email
    FROM users
    WHERE role = 'sales_manager'
      AND is_approved = 2
      AND agency_id = ?
    ORDER BY id DESC
");

if ($stmt3) {
    $stmt3->bind_param("i", $agencyId);
    $stmt3->execute();
    $rejectedResult = $stmt3->get_result();
}

$currentPage = basename($_SERVER['PHP_SELF']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sales Manager Approval</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root{
            --bg:#eef3f9;
            --card:#ffffff;
            --card-2:#f8fbff;
            --text:#0f172a;
            --muted:#64748b;
            --border:#e5eaf2;
            --shadow:0 16px 40px rgba(15,23,42,.08);
            --shadow-soft:0 10px 24px rgba(15,23,42,.06);
            --radius:22px;

            --primary:#2563eb;
            --primary-dark:#1d4ed8;
            --success:#16a34a;
            --success-bg:#dcfce7;
            --success-text:#166534;
            --danger:#dc2626;
            --danger-bg:#fee2e2;
            --danger-text:#991b1b;
            --warning-bg:#fef3c7;
            --warning-text:#92400e;
            --neutral-bg:#e2e8f0;
            --neutral-text:#334155;
        }

        *{ box-sizing:border-box; }

        body{
            margin:0;
            font-family:Inter, Arial, Helvetica, sans-serif;
            background:var(--bg);
            color:var(--text);
        }

        a{ text-decoration:none; color:inherit; }

        .page{
            margin-left:260px;
            padding:40px 40px 36px;
            min-height:100vh;
        }

.header-card{
    background:linear-gradient(135deg,#ffffff,#f8fbff);
    border-radius:20px;
    padding:36px;
    margin-bottom:22px;
    box-shadow:0 15px 40px rgba(0,0,0,0.06);
    border:1px solid #e2e8f0;
}


        .topbar{
            display:flex;
            justify-content:space-between;
            align-items:flex-start;
            gap:16px;
            margin-bottom:18px;
        }

    .title-wrap h1{
    font-size:30px;
    font-weight:900;
    background:linear-gradient(135deg,#374155,#1e293b);
    -webkit-background-clip:text;
    -webkit-text-fill-color:transparent;
}


        .title-wrap p{
            margin:8px 0 0;
            font-size:14px;
            color:#64748b
        }

        .summary{
            display:grid;
            grid-template-columns:repeat(3, minmax(0, 1fr));
            gap:14px;
            margin-top:18px;
        }
        .stat{
            border-radius:18px;
            padding:18px;
            background:linear-gradient(135deg,#ffffff,#f8fafc);
            border:1px solid #e2e8f0;
            transition:0.25s;
            position:relative;
            overflow:hidden;
        }

        .stat:hover{
            transform:translateY(-4px);
            box-shadow:0 12px 25px rgba(0,0,0,0.08);
        }

        /* LEFT COLOR BAR */
        .stat::before{
            content:"";
            position:absolute;
            left:0;
            top:0;
            width:4px;
            height:100%;
            background:#374155;
        }

        /* DIFFERENT COLORS */
        .stat:nth-child(1)::before{ background:#f59e0b; }
        .stat:nth-child(2)::before{ background:#16a34a; }
        .stat:nth-child(3)::before{ background:#dc2626; }

        .stat .value{
            font-size:28px;
            font-weight:900;
        }

        /* TEXT COLORS */
        .stat:nth-child(1) .value{ color:#f59e0b; }
        .stat:nth-child(2) .value{ color:#16a34a; }
        .stat:nth-child(3) .value{ color:#dc2626; }

        .stat .label{
            color:var(--muted);
            font-size:13px;
            font-weight:700;
            margin-bottom:8px;
        }

        .stat .value{
            font-size:28px;
            font-weight:900;
            line-height:1;
            color:#0f172a;
        }

 .tabs{
    display:flex;
    gap:12px;
    background:#eef2f7;
    padding:8px;
    border-radius:16px;
    width:fit-content;
    box-shadow:inset 0 2px 6px rgba(0,0,0,0.05);
}

/* TAB BUTTON */
.tab-btn{
    position:relative;
    display:flex;
    align-items:center;
    gap:10px;
    border-radius:12px;
    padding:10px 18px;
    border:none;
    background:transparent;
    color:#475569;
    font-weight:600;
    cursor:pointer;
    transition:all .25s ease;
}

/* ICON */
.tab-btn i{
    font-size:13px;
}

/* HOVER */
.tab-btn:hover{
    color:#0f172a;
}

/* ACTIVE TAB */
.tab-btn.active{
    background:#374155;
    color:#fff;
    box-shadow:0 8px 20px rgba(55,65,85,0.3);
}

/* COUNT BADGE */
.tab-count{
    margin-left:6px;
    padding:3px 8px;
    border-radius:999px;
    font-size:11px;
    font-weight:700;
    background:#e2e8f0;
    color:#334155;
}

/* ACTIVE BADGE */
.tab-btn.active .tab-count{
    background:rgba(255,255,255,0.2);
    color:#fff;
}

/* NON-ACTIVE COUNT */
.tab-btn:not(.active) .tab-count{
    background:#cbd5e1;
    color:#1e293b;
}

        .panel{
            background:var(--card);
            border:1px solid var(--border);
            border-radius:var(--radius);
            box-shadow:var(--shadow);
            overflow:hidden;
        }

        .panel-head{
            display:flex;
            justify-content:space-between;
            align-items:center;
            gap:12px;
            padding:18px 20px;
            border-bottom:1px solid var(--border);
            background:linear-gradient(180deg,#fff 0%, #fbfcfe 100%);
        }

        .panel-head h2{
            margin:0;
            font-size:18px;
            font-weight:900;
            color:#0f172a;
        }

        .panel-head .sub{
            color:var(--muted);
            font-size:13px;
        }

        .flash{
            padding:14px 16px;
            border-radius:14px;
            margin-bottom:16px;
            font-weight:700;
            border:1px solid transparent;
        }

        .flash.success{
            background:#ecfdf5;
            color:var(--success-text);
            border-color:#bbf7d0;
        }

        .flash.error{
            background:#fef2f2;
            color:var(--danger-text);
            border-color:#fecaca;
        }

            /* TABLE WRAPPER */
        .table-wrap{
            margin-top:10px;
        }

        /* TABLE */
        table{
            width:100%;
            border-collapse:separate;
            border-spacing:0 12px;
        }

        /* HEADER */
        thead th{
            background:#334155;
            color:#fff;
            padding:14px;
            font-size:13px;
            text-align:left;
            border:none;
        }

        thead th:first-child{
            border-radius:12px 0 0 12px;
        }
        thead th:last-child{
            border-radius:0 12px 12px 0;
        }

        /* BODY */
      tbody td{
    background:#ffffff;
    font-weight:500;
    padding:14px;
    font-size:13px;
    border-top:1px solid #e2e8f0;
    border-bottom:1px solid #e2e8f0;

    /* 🔥 FIX */
    color:#0f172a;   /* dark text */
    font-weight:500;
}

        /* ROW CARD EFFECT */
        tbody tr td:first-child{
            border-left:1px solid #e2e8f0;
            border-radius:12px 0 0 12px;
        }

        tbody tr td:last-child{
            border-right:1px solid #e2e8f0;
            border-radius:0 12px 12px 0;
        }

        /* HOVER */
        tbody tr:hover td{
    background:#f1f5f9;
        }

        .id-pill{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            min-width:42px;
            height:30px;
            border-radius:999px;
            padding:0 12px;
            background:#e0e7ff;
            color:#3730a3;
            font-weight:800;
            font-size:12px;
        }

.badge{
    font-size:12px;
    padding:6px 12px;
    border-radius:999px;
    font-weight:700;
}

.badge-pending{
    background:#fff7ed;
    color:#c2410c;
}

.badge-approved{
    background:#ecfdf5;
    color:#15803d;
}

.badge-rejected{
    background:#fef2f2;
    color:#b91c1c;
}
        .btn-row{
            display:flex;
            gap:8px;
            flex-wrap:wrap;
        }

  .btn{
    border:none;
      border-radius:12px;
    padding:9px 16px;
    font-weight:700;
    font-size:13px;
    cursor:pointer;
    display:inline-flex;
    align-items:center;
    gap:6px;
    transition:all .25s ease;
    box-shadow:0 4px 10px rgba(0,0,0,0.08);
}
    
/* APPROVE BUTTON */
.btn-approve{
      background:linear-gradient(135deg,#22c55e,#16a34a);
    box-shadow:0 6px 15px rgba(34,197,94,0.3);
    color:#fff;
}

       /* REJECT BUTTON */
.btn-reject{
background:linear-gradient(135deg,#ef4444,#dc2626);
    box-shadow:0 6px 15px rgba(239,68,68,0.3);
    color:#fff;
}

        .empty{
            padding:46px 22px;
            text-align:center;
            color:var(--muted);
        }

        .empty i{
            display:block;
            font-size:44px;
            margin-bottom:12px;
            color:#94a3b8;
        }

        .tab-content{
            display:none;
        }

        .tab-content.active{
            display:block;
        }

        @media (max-width:1100px){
            .page{ margin-left:0; }
            .summary{ grid-template-columns:1fr; }
            .topbar{ flex-direction:column; }
        }

        @media (max-width:768px){
            .page{ padding:16px; }
            .header-card{ padding:18px; }
            .title-wrap h1{ font-size:24px; }
            .panel-head{
                flex-direction:column;
                align-items:flex-start;
            }
            .tab-btn{
                width:100%;
                justify-content:space-between;
            }
            .btn-row{
                width:100%;
            }
            .btn{
                width:100%;
                justify-content:center;
            }
        }
        .btn-delete{
    background:linear-gradient(135deg,#ef4444,#b91c1c);
    color:#fff;
}

.btn-delete:hover{
    transform:translateY(-1px);
    box-shadow:0 6px 14px rgba(220,38,38,0.3);
}
    </style>
</head>
<body>

<?php
if (file_exists("../header.php")) {
    include "../header.php";
}
if (file_exists("agencysidebar.php")) {
    include "agencysidebar.php";
}
?>

<div class="page">
    <div class="header-card">
        <div class="topbar">
            <div class="title-wrap">
                <h1>Sales Manager Approval</h1>
                <p>Review, approve, or reject sales manager signup requests for your agency.</p>
            </div>
        </div>

        <div class="summary">
            <div class="stat">
                <div class="label">Pending Requests</div>
                <div class="value"><?php echo (int)$pendingCount; ?></div>
            </div>
            <div class="stat">
                <div class="label">Approved Managers</div>
                <div class="value"><?php echo (int)$approvedCount; ?></div>
            </div>
            <div class="stat">
                <div class="label">Rejected Requests</div>
                <div class="value"><?php echo (int)$rejectedCount; ?></div>
            </div>
        </div>
    </div>

    <?php if ($msg !== ''): ?>
        <div class="flash success"><?php echo e($msg); ?></div>
    <?php endif; ?>

    <?php if ($error !== ''): ?>
        <div class="flash error"><?php echo e($error); ?></div>
    <?php endif; ?>

    <div class="tabs">
        <button type="button" class="tab-btn <?php echo $activeTab === 'pending' ? 'active' : ''; ?>" onclick="showTab('pending')">
            <span><i class="fa-solid fa-clock"></i> Pending</span>
            <span class="tab-count"><?php echo (int)$pendingCount; ?></span>
        </button>
        <button type="button" class="tab-btn <?php echo $activeTab === 'approved' ? 'active' : ''; ?>" onclick="showTab('approved')">
            <span><i class="fa-solid fa-circle-check"></i> Approved</span>
            <span class="tab-count"><?php echo (int)$approvedCount; ?></span>
        </button>
        <button type="button" class="tab-btn <?php echo $activeTab === 'rejected' ? 'active' : ''; ?>" onclick="showTab('rejected')">
    <span><i class="fa-solid fa-xmark-circle"></i> Rejected</span>
    <span class="tab-count"><?php echo (int)$rejectedCount; ?></span>
</button>
    </div>

    <div id="pending" class="tab-content panel <?php echo $activeTab === 'pending' ? 'active' : ''; ?>">
        <div class="panel-head">
            <div>
                <h2>Pending Sales Manager Requests</h2>
                <div class="sub">Requests waiting for your approval</div>
            </div>
        </div>

        <div class="table-wrap">
            <?php if ($pendingResult && $pendingResult->num_rows === 0): ?>
                <div class="empty">
                    <i class="fa-regular fa-folder-open"></i>
                    No pending sales manager requests
                </div>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if ($pendingResult): while ($row = $pendingResult->fetch_assoc()): ?>
                        <tr>
                            <td><span class="id-pill"><?php echo (int)$row['id']; ?></span></td>
                            <td><?php echo e($row['name']); ?></td>
                            <td><?php echo e($row['email']); ?></td>
                            <td><span class="badge badge-pending">Pending</span></td>
                            <td>
                                <div class="btn-row">
                                    <form method="post" style="margin:0;">
                                        <input type="hidden" name="csrf_token" value="<?php echo e($csrf); ?>">
                                        <input type="hidden" name="approve_id" value="<?php echo (int)$row['id']; ?>">
                                        <button type="submit" class="btn btn-approve">
                                            <i class="fa-solid fa-check"></i> Approve
                                        </button>
                                    </form>

                                    <form method="post" style="margin:0;">
                                        <input type="hidden" name="csrf_token" value="<?php echo e($csrf); ?>">
                                        <input type="hidden" name="reject_id" value="<?php echo (int)$row['id']; ?>">
                                        <button type="submit" class="btn btn-reject" onclick="return confirm('Reject this request?');">
                                            <i class="fa-solid fa-xmark"></i> Reject
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endwhile; endif; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>

    <div id="approved" class="tab-content panel <?php echo $activeTab === 'approved' ? 'active' : ''; ?>" style="margin-top:18px;">
        <div class="panel-head">
            <div>
                <h2>Approved Sales Managers</h2>
                <div class="sub">Managers approved by your agency</div>
            </div>
        </div>

        <div class="table-wrap">
            <?php if (!$approvedResult || $approvedResult->num_rows == 0): ?>
                <div class="empty">
                    <i class="fa-solid fa-user-check"></i>
                    No approved sales managers yet
                </div>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Email</th>
                           <th>Status</th>
                           <th>Action</th>
                            </tr>
                    </thead>
                    <tbody>
                    <?php if ($approvedResult): while ($row = $approvedResult->fetch_assoc()): ?>
                        <tr>
                            <td><span class="id-pill"><?php echo (int)$row['id']; ?></span></td>
                            <td><?php echo e($row['name']); ?></td>
                            <td><?php echo e($row['email']); ?></td>
                            <td><span class="badge badge-approved">Approved</span></td>
                            <td>
                                <form method="post" onsubmit="return confirm('Remove this manager?');">
                                    <input type="hidden" name="csrf_token" value="<?php echo e($csrf); ?>">
                                    <input type="hidden" name="delete_id" value="<?php echo (int)$row['id']; ?>">
                                    <button type="submit" class="btn btn-delete">
                                        <i class="fa-solid fa-trash"></i> Remove
                                    </button>
                                </form>
                            </td>             
                                   </tr>
                    <?php endwhile; endif; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
    <div id="rejected" class="tab-content panel <?php echo $activeTab === 'rejected' ? 'active' : ''; ?>" style="margin-top:18px;">
    <div class="panel-head">
        <div>
            <h2>Rejected Sales Managers</h2>
            <div class="sub">Managers rejected by your agency</div>
        </div>
    </div>

    <div class="table-wrap">
        <?php if (!$rejectedResult || $rejectedResult->num_rows == 0): ?>
            <div class="empty">
                <i class="fa-solid fa-user-xmark"></i>
                No rejected sales managers
            </div>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php while ($row = $rejectedResult->fetch_assoc()): ?>
                    <tr>
                        <td><span class="id-pill"><?php echo (int)$row['id']; ?></span></td>
                        <td><?php echo e($row['name']); ?></td>
                        <td><?php echo e($row['email']); ?></td>
                    <td><span class="badge badge-rejected">Rejected</span></td>
                    <td>
                        <form method="post" onsubmit="return confirm('Remove this manager?');">
                            <input type="hidden" name="csrf_token" value="<?php echo e($csrf); ?>">
                            <input type="hidden" name="delete_id" value="<?php echo (int)$row['id']; ?>">
                            <button type="submit" class="btn btn-delete">
                                <i class="fa-solid fa-trash"></i> Remove
                            </button>
                        </form>
                    </td>                    
                </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>
</div>

<script>
function showTab(tab) {
    const tabs = ['pending', 'approved', 'rejected'];

    tabs.forEach(t => {
        document.getElementById(t).classList.remove('active');
    });

    document.getElementById(tab).classList.add('active');

    const buttons = document.querySelectorAll('.tab-btn');
    buttons.forEach(btn => btn.classList.remove('active'));

    if (tab === 'pending') buttons[0].classList.add('active');
    if (tab === 'approved') buttons[1].classList.add('active');
    if (tab === 'rejected') buttons[2].classList.add('active');
}
</script>

</body>
</html>