<?php
// sales-managers.php
// Shows Sales Managers under the logged-in Agency

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

function e($v){ return htmlspecialchars($v ?? '', ENT_QUOTES); }

/* ---------- AUTH ---------- */

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

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

/* ---------- FETCH SALES MANAGERS ---------- */

$managers = [];

$sql = "
SELECT id, name, email, is_approved, requested_agency_id
FROM users
WHERE role = 'sales_manager'
AND requested_agency_id = ?
ORDER BY name ASC
";

$stmt = $conn->prepare($sql);

if($stmt){
    $stmt->bind_param("i",$agency_id);
    $stmt->execute();
    $res = $stmt->get_result();

    while($row = $res->fetch_assoc()){
        $managers[] = $row;
    }

    $stmt->close();
}else{
    $db_error = $conn->error;
}

?>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Managers</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>

body{
font-family:Inter,Arial;
background:#eef2f7;
margin:0;
padding:90px 16px;
}

.container{
margin-left:260px;
}

.card{
background:#fff;
border-radius:14px;
padding:25px;
box-shadow:0 10px 25px rgba(0,0,0,0.05);
}

h2{
margin:0 0 20px;
font-size:24px;
color:#1e293b;
}

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

.table th{
background:#334155;
color:#fff;
padding:14px;
text-align:left;
font-size:13px;
}

.table td{
background:#f8fafc;
padding:14px;
font-size:14px;
}

.badge{
padding:6px 10px;
border-radius:20px;
font-size:12px;
font-weight:600;
display:inline-block;
}

.approved{
background:#dcfce7;
color:#166534;
}

.pending{
background:#fee2e2;
color:#991b1b;
}

</style>
</head>

<body>

<?php include "agencysidebar.php"; ?>
<?php include "../header.php"; ?>

<div class="container">

<div class="card">

<h2>Sales Managers</h2>

<?php if(!empty($db_error)): ?>
<div style="color:red"><?php echo e($db_error); ?></div>
<?php endif; ?>

<table class="table">

<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Status</th>
</tr>
</thead>

<tbody>

<?php if(empty($managers)): ?>

<tr>
<td colspan="5">No Sales Managers found for this agency.</td>
</tr>

<?php else: ?>

<?php foreach($managers as $m): ?>

<tr>
<td><?php echo (int)$m['id']; ?></td>
<td><?php echo e($m['name']); ?></td>
<td><?php echo e($m['email']); ?></td>
<td><?php echo (int)$m['requested_agency_id']; ?></td>

<td>
<?php if((int)$m['is_approved']==1): ?>
<span class="badge approved">Approved</span>
<?php else: ?>
<span class="badge pending">Pending</span>
<?php endif; ?>
</td>

</tr>

<?php endforeach; ?>

<?php endif; ?>

</tbody>
</table>

</div>
</div>

</body>
</html>