<?php
include 'config.php';
if($_SESSION['user_role'] != 'AgencyOwner') exit();

$aid = $_SESSION['agency_id'];

// 1. HANDLE DELETE
if(isset($_GET['delete'])){
    $id = (int)$_GET['delete'];
    $conn->query("DELETE FROM users WHERE id = $id AND agency_id = $aid AND role = 'Staff'");
    header("Location: staff.php?msg=deleted");
    exit();
}

// 2. HANDLE ADD NEW STAFF
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // SERVER-SIDE COUNT CHECK
    $check_count = $conn->query("SELECT COUNT(id) as total FROM users WHERE agency_id = $aid AND role = 'Staff'")->fetch_assoc();
    
    if($check_count['total'] >= 2) {
        die("Error: You have reached your limit of 2 staff members.");
    }

    $name = $_POST['name'];
    $email = $_POST['email'];
    $pass = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $stmt = $conn->prepare("INSERT INTO users (agency_id, name, email, password, role) VALUES (?, ?, ?, ?, 'Staff')");
    $stmt->bind_param("isss", $aid, $name, $email, $pass);
    
    if($stmt->execute()){
        header("Location: staff.php?success=1");
    } else {
        echo "Error: Email already exists in the system.";
    }
}
?>