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

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

$action = $_POST['action'] ?? '';
$redirect = 'manage_roster.php';

try {
    if ($action === 'add') {
        $officer_id = $_POST['officer_id'] ?? null;
        $site_id = $_POST['site_id'] ?? null;
        $shift_date = $_POST['shift_date'] ?? null;
        $shift_type = $_POST['shift_type'] ?? null;

        if ($officer_id && $site_id && $shift_date && $shift_type) {
            $stmt = $pdo->prepare("INSERT INTO roster (officer_id, site_id, shift_date, shift_type) VALUES (?, ?, ?, ?)");
            $stmt->execute([$officer_id, $site_id, $shift_date, $shift_type]);
        }

    } elseif ($action === 'update') {
        $id = $_POST['id'] ?? null;
        $officer_id = $_POST['officer_id'] ?? null;
        $site_id = $_POST['site_id'] ?? null;
        $shift_date = $_POST['shift_date'] ?? null;
        $shift_type = $_POST['shift_type'] ?? null;

        if ($id && $officer_id && $site_id && $shift_date && $shift_type) {
            $stmt = $pdo->prepare("UPDATE roster SET officer_id = ?, site_id = ?, shift_date = ?, shift_type = ? WHERE id = ?");
            $stmt->execute([$officer_id, $site_id, $shift_date, $shift_type, $id]);
        }

    } elseif ($action === 'delete') {
        $id = $_POST['id'] ?? null;

        if ($id) {
            $stmt = $pdo->prepare("DELETE FROM roster WHERE id = ?");
            $stmt->execute([$id]);
        }
    }

} catch (PDOException $e) {
    // Log the error or handle it as needed
    // For security reasons, avoid displaying detailed errors to the user
    // You can log $e->getMessage() to a file or monitoring system
}

header("Location: $redirect");
exit;
?>
