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

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

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    echo "Access Denied";
    exit;
}

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

if (!function_exists('role_label')) {
    function role_label($role) {
        $role = strtolower(trim($role ?? ''));
        return match ($role) {
            'ra' => 'RA',
            'agency' => 'Agency',
            'sales_manager' => 'Sales Manager',
            'medical_representative' => 'Medical Representative',
            'admin' => 'Admin',
            default => ucfirst($role),
        };
    }
}

if (!function_exists('status_label')) {
    function status_label($isApproved) {
        return ((int)$isApproved === 1)
            ? '<span class="badge approved">Approved</span>'
            : '<span class="badge pending">Pending</span>';
    }
}

if (!function_exists('safe_name')) {
    function safe_name($v) {
        return trim((string)($v ?? '')) !== '' ? $v : '-';
    }
}

/*
|--------------------------------------------------------------------------
| APPROVE / REJECT ACTION
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'], $_POST['id'])) {
    $id = (int) $_POST['id'];
    $action = $_POST['action'];

    $userStmt = $conn->prepare("SELECT role, requested_agency_id, requested_manager_id FROM users WHERE id = ?");
    if ($userStmt) {
        $userStmt->bind_param("i", $id);
        $userStmt->execute();
        $userRes = $userStmt->get_result();
        $userRow = $userRes ? $userRes->fetch_assoc() : null;
        $userStmt->close();

        if ($userRow) {
            $role = strtolower(trim($userRow['role'] ?? ''));

            if ($action === 'approve') {
                if ($role === 'medical_representative') {
                    $sql = "
                        UPDATE users
                        SET is_approved = 1,
                            agency_id = CASE
                                WHEN requested_agency_id IS NOT NULL AND requested_agency_id <> 0 THEN requested_agency_id
                                ELSE agency_id
                            END,
                            manager_id = CASE
                                WHEN requested_manager_id IS NOT NULL AND requested_manager_id <> 0 THEN requested_manager_id
                                ELSE manager_id
                            END
                        WHERE id = ?
                    ";
                } elseif ($role === 'sales_manager' || $role === 'agency') {
                    $sql = "
                        UPDATE users
                        SET is_approved = 1,
                            agency_id = CASE
                                WHEN requested_agency_id IS NOT NULL AND requested_agency_id <> 0 THEN requested_agency_id
                                ELSE agency_id
                            END
                        WHERE id = ?
                    ";
                } else {
                    $sql = "
                        UPDATE users
                        SET is_approved = 1
                        WHERE id = ?
                    ";
                }
            } elseif ($action === 'reject') {
                $sql = "
                    UPDATE users
                    SET is_approved = 0
                    WHERE id = ?
                ";
            } else {
                header("Location: roles.php");
                exit;
            }

            $stmt = $conn->prepare($sql);
            if ($stmt) {
                $stmt->bind_param("i", $id);
                $stmt->execute();
                $stmt->close();
            }
        }
    }

    header("Location: roles.php");
    exit;
}

/*
|--------------------------------------------------------------------------
| DATA FETCH HELPERS
|--------------------------------------------------------------------------
*/
function fetch_requests_by_role($conn, $role) {
    $data = [];

    $sql = "
        SELECT 
            u.*,
            m.name AS manager_name,
            a.name AS agency_name,
            rm.name AS requested_manager_name,
            ra.name AS requested_agency_name
        FROM users u
        LEFT JOIN users m ON u.manager_id = m.id
        LEFT JOIN users a ON u.agency_id = a.id
        LEFT JOIN users rm ON u.requested_manager_id = rm.id
        LEFT JOIN users ra ON u.requested_agency_id = ra.id
        WHERE u.role = ? AND u.is_approved = 0
        ORDER BY u.id ASC
    ";

    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param("s", $role);
        $stmt->execute();
        $res = $stmt->get_result();

        if ($res) {
            while ($row = $res->fetch_assoc()) {
                $data[] = $row;
            }
        }
        $stmt->close();
    }

    return $data;
}

function fetch_sales_manager_map($conn) {
    $data = [];

    $sql = "
        SELECT 
            m.id,
            m.name AS manager_name,
            m.is_approved,

            -- FINAL FIX (handles NULL + empty)
            COALESCE(
                NULLIF(a1.name, ''),
                NULLIF(a2.name, ''),
                '-'
            ) AS agency_name,

            a1.name AS current_agency_name,
            a2.name AS requested_agency_name

        FROM users m

        LEFT JOIN users a1 ON m.agency_id = a1.id
        LEFT JOIN users a2 ON m.requested_agency_id = a2.id

        WHERE m.role = 'sales_manager'
        ORDER BY m.name ASC
    ";

    $res = $conn->query($sql);
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $data[] = $row;
        }
    }

    return $data;
}

function fetch_medical_representative_map($conn) {
    $data = [];

   $sql = "
SELECT 
    e.id,
    e.name AS executive_name,
    e.is_approved,

    -- MANAGER (current OR requested)
    COALESCE(
        NULLIF(m.name, ''),
        NULLIF(rm.name, ''),
        '-'
    ) AS manager_name,

    -- AGENCY (manager current → manager requested → fallback)
    COALESCE(
        NULLIF(ma.name, ''),     -- manager current agency
        NULLIF(mra.name, ''),    -- manager requested agency
        '-'
    ) AS agency_name

FROM users e

-- CURRENT MANAGER
LEFT JOIN users m ON e.manager_id = m.id
LEFT JOIN users ma ON m.agency_id = ma.id

-- REQUESTED MANAGER
LEFT JOIN users rm ON e.requested_manager_id = rm.id
LEFT JOIN users mra ON rm.requested_agency_id = mra.id

WHERE e.role = 'medical_representative'
ORDER BY e.name ASC
";

    $res = $conn->query($sql);
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $data[] = $row;
        }
    }

    return $data;
}

$roleSections = [
    'ra' => 'RA Requests',
    'agency' => 'Agency Requests',
    'sales_manager' => 'Sales Manager Requests',
    'medical_representative' => 'Medical Representative Requests',
];

$requests = [];
foreach ($roleSections as $roleKey => $label) {
    $requests[$roleKey] = fetch_requests_by_role($conn, $roleKey);
}

$managerMap = fetch_sales_manager_map($conn);
$executiveMap = fetch_medical_representative_map($conn);

$counts = [
    'ra' => count($requests['ra']),
    'agency' => count($requests['agency']),
    'sales_manager' => count($requests['sales_manager']),
    'medical_representative' => count($requests['medical_representative']),
    'managers' => count($managerMap),
    'executives' => count($executiveMap),
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Roles & Permissions</title>
    <style>
        * { box-sizing: border-box; }

        body {
            font-family: Arial, sans-serif;
            background: #f4f6fb;
            margin: 0;
            padding: 0;
            color: #1f2937;
        }

        .container {
            padding: 80px;
            margin-left: 240px;
            transition: margin-left 0.3s ease;
        }

        .page-head {
            background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
            border: 1px solid #e5e7eb;
            padding: 22px;
            border-radius: 16px;
            box-shadow: 0 6px 20px rgba(15, 23, 42, 0.05);
            margin-bottom: 20px;
        }

        .page-head h1 {
            margin: 0 0 8px;
            font-size: 24px;
            color: #111827;
        }

        .page-head p {
            margin: 0;
            color: #6b7280;
            font-size: 14px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(6, minmax(0, 1fr));
            gap: 14px;
            margin-bottom: 22px;
        }

        .stat-card {
            background: #fff;
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            padding: 16px;
            box-shadow: 0 4px 14px rgba(15, 23, 42, 0.04);
        }

        .stat-card .label {
            font-size: 12px;
            color: #6b7280;
            margin-bottom: 8px;
        }

        .stat-card .value {
            font-size: 24px;
            font-weight: 800;
            color: #111827;
        }

        .section {
            margin-top: 18px;
            background: #fff;
            padding: 18px;
            border-radius: 16px;
            box-shadow: 0 6px 20px rgba(15, 23, 42, 0.05);
            border: 1px solid #e5e7eb;
            overflow-x: auto;
        }

        .section-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            margin-bottom: 12px;
            flex-wrap: wrap;
        }

        .section-header h2 {
            margin: 0;
            color: #111827;
            font-size: 18px;
        }

        .muted {
            color: #6b7280;
            font-size: 13px;
            margin-top: 4px;
        }

        .count-box {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 40px;
            padding: 5px 10px;
            border-radius: 999px;
            background: #000;
            color: #fff;
            font-size: 12px;
            font-weight: 800;
            margin-left: 8px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: #fff;
            overflow: hidden;
            border-radius: 12px;
        }

        th, td {
            padding: 11px 12px;
            border-bottom: 1px solid #e5e7eb;
            text-align: left;
            vertical-align: middle;
            white-space: nowrap;
            font-size: 13px;
        }

        th {
            background: #1f2937;
            color: #fff;
            font-weight: 700;
            position: sticky;
            top: 0;
            z-index: 1;
        }

        tr:hover td {
            background: #f9fafb;
        }

        .badge {
            display: inline-block;
            padding: 5px 9px;
            border-radius: 999px;
            color: #fff;
            font-size: 12px;
            line-height: 1;
            font-weight: 700;
        }

        .pending { background: #f59e0b; }
        .approved { background: #16a34a; }

        .btn {
            display: inline-block;
            padding: 7px 11px;
            border: 0;
            border-radius: 8px;
            color: #fff;
            font-size: 12px;
            font-weight: 700;
            cursor: pointer;
            text-decoration: none;
            margin-right: 6px;
        }

        .btn-approve { background: #16a34a; }
        .btn-reject { background: #dc2626; }

        .role-tag {
            display: inline-flex;
            align-items: center;
            padding: 5px 10px;
            border-radius: 999px;
          
            color: #000;
            font-size: 12px;
            font-weight: 700;
        }

        .small-note {
            color: #6b7280;
            font-size: 12px;
        }

        .mapping-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 18px;
        }

        .info-row {
            display: flex;
            gap: 6px;
            flex-wrap: wrap;
            align-items: center;
        }

        .pill {
            display: inline-block;
            padding: 4px 9px;
            border-radius: 999px;
            background: #f3f4f6;
            color: #374151;
            font-size: 12px;
        }
        

        @media (max-width: 1200px) {
            .stats-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
        }

     @media (max-width: 768px) {

    /* HEADER HEIGHT FIX */
    body {
        padding-top: 65px; /* header height ke according adjust */
    }

    .container {
        margin-left: 0;
        padding: 15px;
        padding-top: 10px; /* extra space avoid */
    }

    /* GRID FIX */
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
    }

    /* CARD SIZE IMPROVE */
    .stat-card {
        padding: 14px;
        border-radius: 12px;
    }

    .stat-card .value {
        font-size: 20px;
    }

    .stat-card .label {
        font-size: 11px;
    }

    /* TABLE RESPONSIVE */
    table {
        font-size: 12px;
    }

    th, td {
        padding: 8px;
        white-space: normal;
    }

    /* SECTION SPACING */
    .section {
        padding: 14px;
        border-radius: 12px;
    }

    /* HEADER TEXT FIX */
    .page-head {
        padding: 16px;
    }

    .page-head h1 {
        font-size: 18px;
    }

    .page-head p {
        font-size: 12px;
    }
}
    </style>
</head>
<body>
<?php include "adminsidebar.php"; ?>
<?php include "../header.php"; ?>

<div class="container">

    <div class="page-head">
        <h1>👥 Roles & Permissions</h1>
        <p>Role-wise requests, approval control.</p>
    </div>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="label">RA Requests</div>
            <div class="value"><?php echo (int)$counts['ra']; ?></div>
        </div>
        <div class="stat-card">
            <div class="label">Agency Requests</div>
            <div class="value"><?php echo (int)$counts['agency']; ?></div>
        </div>
        <div class="stat-card">
            <div class="label">Sales Manager Requests</div>
            <div class="value"><?php echo (int)$counts['sales_manager']; ?></div>
        </div>
        <div class="stat-card">
            <div class="label">Medical Representative Requests</div>
            <div class="value"><?php echo (int)$counts['medical_representative']; ?></div>
        </div>
        <div class="stat-card">
            <div class="label">Managers Mapping</div>
            <div class="value"><?php echo (int)$counts['managers']; ?></div>
        </div>
        <div class="stat-card">
            <div class="label">Executives Mapping</div>
            <div class="value"><?php echo (int)$counts['executives']; ?></div>
        </div>
    </div>

    <?php foreach ($roleSections as $roleKey => $sectionTitle): ?>
        <div class="section">
            <div class="section-header">
                <div>
                    <h2>
                        <?php echo e($sectionTitle); ?>
                        <span class="count-box"><?php echo count($requests[$roleKey]); ?></span>
                    </h2>
                    <div class="muted">Pending <?php echo e(role_label($roleKey)); ?> users.</div>
                </div>
            </div>

            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Role</th>
                        <th>Requested Agency</th>
                        <th>Requested Manager</th>
                        <th>Current Agency</th>
                        <th>Current Manager</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!empty($requests[$roleKey])): ?>
                    <?php foreach ($requests[$roleKey] as $u): ?>
                        <tr>
                            <td><?php echo (int)$u['id']; ?></td>
                            <td><?php echo e($u['name']); ?></td>
                            <td><span class="role-tag"><?php echo e(role_label($u['role'])); ?></span></td>
                            <td><?php echo e($u['requested_agency_name'] ?? '-'); ?></td>
                            <td><?php echo e($u['requested_manager_name'] ?? '-'); ?></td>
                            <td><?php echo e($u['agency_name'] ?? '-'); ?></td>
                            <td><?php echo e($u['manager_name'] ?? '-'); ?></td>
                            <td><?php echo status_label($u['is_approved'] ?? 0); ?></td>
                            <td>
                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="action" value="approve">
                                    <input type="hidden" name="id" value="<?php echo (int)$u['id']; ?>">
                                    <button type="submit" class="btn btn-approve" onclick="return confirm('Approve this user?');">Approve</button>
                                </form>
                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="action" value="reject">
                                    <input type="hidden" name="id" value="<?php echo (int)$u['id']; ?>">
                                    <button type="submit" class="btn btn-reject" onclick="return confirm('Reject this user?');">Reject</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="9">No <?php echo e(strtolower($sectionTitle)); ?> found.</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    <?php endforeach; ?>

    <div class="section">
        <div class="section-header">
            <div>
                <h2> Sales Manager → Agency Mapping</h2>
                <div class="muted">For each Sales Manager, both their current agency and the requested agency are displayed.</div>
            </div>
        </div>

        <table>
            <thead>
                <tr>
                    <th>Manager</th>
                    <th>Requested Agency</th>
                    <th>Current Agency</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
            <?php if (!empty($managerMap)): ?>
                <?php foreach ($managerMap as $row): ?>
    <tr>
        <td><?php echo e($row['manager_name'] ?? '-'); ?></td>

        <!-- Requested Agency -->
        <td><?php echo e($row['requested_agency_name'] ?? '-'); ?></td>

        <!-- Current Agency -->
        <td><?php echo e($row['current_agency_name'] ?? '-'); ?></td>

        <!-- Status -->
        <td><?php echo status_label($row['is_approved'] ?? 0); ?></td>
    </tr>
<?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="4">No sales managers found.</td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- ✅ FIXED SECTION -->
    <div class="section">
        <div class="section-header">
            <div>
                <h2>Medical Representative → Manager → Agency Mapping</h2>
                <div class="muted">The current manager and that manager's agency are being displayed to every executive.</div>
            </div>
        </div>

        <table>
            <thead>
                <tr>
                    <th>Executive</th>
                    <th>Sales Manager</th>
                    <th>Agency</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
            <?php if (!empty($executiveMap)): ?>
                <?php foreach ($executiveMap as $row): ?>
                    <tr>
                        <td><?php echo e($row['executive_name']); ?></td>
                        <td><?php echo e($row['manager_name']); ?></td>
                        <td><?php echo e($row['agency_name']); ?></td>
                        <td><?php echo status_label($row['is_approved']); ?></td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="4">No medical representatives found.</td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

</div>
</body>
</html>