<?php
require_once '../core/bootstrap.php';

// --- Authentication and Role Check ---
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'club_manager') {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: staff_members.php');
    exit();
}

$action = $_POST['action'] ?? '';
$clubManagerModel = new ClubManager();
$notificationModel = new Notification();

// Verify club ownership
$club = $clubManagerModel->getClubByManagerId($_SESSION['user_id']);
if (!$club) {
    header('Location: staff_members.php?error=no_club');
    exit();
}

if ($action === 'hire') {
    $user_id = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);
    $role_type = $_POST['role_type'] ?? ''; // 'team_manager' or 'other'
    $position = trim($_POST['position'] ?? '');
    $team_id = filter_input(INPUT_POST, 'team_id', FILTER_VALIDATE_INT);

    if (!$user_id || !$role_type) {
        header('Location: staff_members.php?error=missing_fields');
        exit();
    }

    if ($clubManagerModel->hireStaff($user_id, $club->id, $role_type, $position, $team_id)) {
        $message = "You have been hired by {$club->name} as a " . ($role_type === 'team_manager' ? 'Team Manager' : $position) . ".";
        $notificationModel->create($user_id, 'hired', $message);
        header('Location: staff_members.php?status=hired');
    } else {
        header('Location: staff_members.php?error=hire_failed');
    }

} elseif ($action === 'sack') {
    $user_id = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);

    if (!$user_id) {
        header('Location: staff_members.php?error=invalid_user');
        exit();
    }

    if ($clubManagerModel->sackStaff($user_id)) {
        $message = "You have been released from your position at {$club->name}.";
        $notificationModel->create($user_id, 'sacked', $message);
        header('Location: staff_members.php?status=sacked');
    } else {
        header('Location: staff_members.php?error=sack_failed');
    }
}
exit();
?>