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

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

// Fetch officers and sites for the form
$officers = $pdo->query("SELECT id, username FROM users WHERE role = 'officer'")->fetchAll();
$sites = $pdo->query("SELECT id, site_name FROM sites")->fetchAll();

// Initialize variables
$edit_mode = false;
$edit_id = null;
$edit_data = null;
$error_message = '';
$success_message = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];
    $officer_id = $_POST['officer_id'];
    $shift_date = $_POST['shift_date'];
    $shift_type = $_POST['shift_type'];
    $site_id = $_POST['site_id'];

    // Define shift timings
    $shift_timings = [
        'day' => ['08:00:00', '20:00:00'],
        'night'   => ['20:00:00', '08:00:00']
    ];

    $start_time = $shift_timings[$shift_type][0];
    $end_time = $shift_timings[$shift_type][1];

    // Combine date and time for comparison
    $new_start = $shift_date . ' ' . $start_time;
    $new_end = $shift_date . ' ' . $end_time;

    // Adjust end time for shifts that end at midnight
    if ($end_time === '00:00:00') {
        $new_end = date('Y-m-d H:i:s', strtotime($shift_date . ' +1 day ' . $end_time));
    }

    // Prepare SQL to check for overlapping shifts
    $overlap_sql = "
        SELECT COUNT(*) FROM officer_roster
        WHERE officer_id = :officer_id
          AND shift_date = :shift_date
          AND (
                (:new_start < end_time AND start_time < :new_end)
              )
    ";

    // Exclude current record when updating
    if ($action === 'update') {
        $id = $_POST['id'];
        $overlap_sql .= " AND id != :id";
    }

    $stmt = $pdo->prepare($overlap_sql);
    $params = [
        ':officer_id' => $officer_id,
        ':shift_date' => $shift_date,
        ':new_start' => $new_start,
        ':new_end' => $new_end
    ];

    if ($action === 'update') {
        $params[':id'] = $id;
    }

    $stmt->execute($params);
    $overlap_count = $stmt->fetchColumn();

    if ($overlap_count > 0) {
        $error_message = "Error: The new shift overlaps with an existing shift for this officer.";
    } else {
        if ($action === 'create') {
            $stmt = $pdo->prepare("INSERT INTO officer_roster (officer_id, shift_date, shift_type, site_id, start_time, end_time) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$officer_id, $shift_date, $shift_type, $site_id, $new_start, $new_end]);
            $success_message = "Roster entry added successfully.";
        } elseif ($action === 'update') {
            $stmt = $pdo->prepare("UPDATE officer_roster SET officer_id = ?, shift_date = ?, shift_type = ?, site_id = ?, start_time = ?, end_time = ? WHERE id = ?");
            $stmt->execute([$officer_id, $shift_date, $shift_type, $site_id, $new_start, $new_end, $id]);
            $success_message = "Roster entry updated successfully.";
        }
    }
}

// Handle edit request
if (isset($_GET['edit'])) {
    $edit_mode = true;
    $edit_id = $_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM officer_roster WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_data = $stmt->fetch();
}

// Handle delete request
if (isset($_GET['delete'])) {
    $delete_id = $_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM officer_roster WHERE id = ?");
    $stmt->execute([$delete_id]);
    $success_message = "Roster entry deleted successfully.";
}

// Fetch roster entries
$stmt = $pdo->query("
    SELECT r.id, u.username AS officer_name, r.shift_date, r.shift_type, s.site_name
    FROM officer_roster r
    JOIN users u ON r.officer_id = u.id
    JOIN sites s ON r.site_id = s.id
    ORDER BY r.shift_date DESC
");
$rosters = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Manage Officer Roster</title>
    <link rel="stylesheet" href="../assets/css/controller_dashboard.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>

<body">

<?php include '../includes/topbar.php'; ?>
<?php include '../includes/sidebar_controller.php'; ?>

<div class="main-content" id="mainContent">
    <div class="container mt-4">

        <h4>🗓️ Manage Officer Roster</h4>
        <hr>

            <!-- Roster Form -->
            <form method="post" class="mb-4">
                <input type="hidden" name="action" value="create">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label for="officer_id" class="form-label">Officer</label>
                        <select name="officer_id" id="officer_id" class="form-select" required>
                            <option value="">Select Officer</option>
                            <?php foreach ($officers as $officer): ?>
                                <option value="<?= $officer['id'] ?>"><?= htmlspecialchars($officer['username']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label for="shift_date" class="form-label">Shift Date</label>
                        <input type="date" name="shift_date" id="shift_date" class="form-control" required>
                    </div>
                    <div class="col-md-2">
                        <label for="shift_type" class="form-label">Shift Type</label>
                        <select name="shift_type" id="shift_type" class="form-select" required>
                            <option value="day">Day</option>
                            <option value="night">Night</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label for="site_id" class="form-label">Site</label>
                        <select name="site_id" id="site_id" class="form-select" required>
                            <option value="">Select Site</option>
                            <?php foreach ($sites as $site): ?>
                                <option value="<?= $site['id'] ?>"><?= htmlspecialchars($site['site_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-1 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary">Add</button>
                    </div>
                </div>
            </form>

            <!-- Roster Table -->
            <table class="table table-bordered table-striped small">
                <thead class="table-dark">
                    <tr>
                        <th>Officer</th>
                        <th>Shift Date</th>
                        <th>Shift Type</th>
                        <th>Site</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($rosters as $roster): ?>
                        <tr>
                            <td><?= htmlspecialchars($roster['officer_name']) ?></td>
                            <td><?= htmlspecialchars($roster['shift_date']) ?></td>
                            <td><?= htmlspecialchars($roster['shift_type']) ?></td>
                            <td><?= htmlspecialchars($roster['site_name']) ?></td>
                            <td>
                                <!-- Edit and Delete buttons can be implemented here -->
                                <!-- For brevity, only Delete is shown -->
                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $roster['id'] ?>">
                                    <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this roster entry?');">Delete</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
    </div>
</div>       
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>
