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

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header('Location: index.php');
    exit;
}

$error = '';
$success = '';

// Fetch classes, programs, staff, and evaluation forms
$classes = mysqli_fetch_all(mysqli_query($conn, "SELECT * FROM classes"), MYSQLI_ASSOC);
$programs = mysqli_fetch_all(mysqli_query($conn, "SELECT * FROM programs"), MYSQLI_ASSOC);
$staff = mysqli_fetch_all(mysqli_query($conn, "SELECT id, first_name, last_name FROM users WHERE role = 'staff' AND is_deleted = 0"), MYSQLI_ASSOC);
$forms = mysqli_fetch_all(mysqli_query($conn, "
    SELECT form_id, title,
           CASE
               WHEN CURDATE() BETWEEN start_date AND end_date THEN title
               WHEN CURDATE() < start_date THEN CONCAT(title, ' (Not Started)')
               WHEN CURDATE() > end_date THEN CONCAT(title, ' (Expired)')
               ELSE CONCAT(title, ' (Invalid Date)')
           END AS display_title
    FROM evaluation_forms
"), MYSQLI_ASSOC);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $class_ids = $_POST['class_ids'] ?? [];
    $program_id = $_POST['program_id'] ?? '';
    $staff_id = $_POST['staff_id'] ?? '';
    $form_id = $_POST['form_id'] ?? '';

    // Validate inputs
    if (empty($class_ids) || empty($program_id) || empty($staff_id) || empty($form_id)) {
        $error = "Please select at least one class, a program, a staff member, and an evaluation form.";
    } else {
        $success_count = 0;
        $error_messages = [];

        foreach ($class_ids as $class_id) {
            // Check if staff is already assigned to class and program
            $query = "SELECT * FROM class_program_staff WHERE class_id = ? AND program_id = ? AND staff_id = ?";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 'iis', $class_id, $program_id, $staff_id);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);

            if (mysqli_num_rows($result) == 0) {
                // Insert staff assignment
                $query = "INSERT INTO class_program_staff (class_id, program_id, staff_id) VALUES (?, ?, ?)";
                $stmt = mysqli_prepare($conn, $query);
                mysqli_stmt_bind_param($stmt, 'iis', $class_id, $program_id, $staff_id);
                if (!mysqli_stmt_execute($stmt)) {
                    $error_messages[] = "Failed to assign staff to class ID $class_id: " . mysqli_error($conn);
                    continue;
                }
            }

            // Check if form assignment exists
            $query = "SELECT * FROM class_program_staff_forms WHERE class_id = ? AND program_id = ? AND staff_id = ? AND form_id = ?";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 'iisi', $class_id, $program_id, $staff_id, $form_id);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);

            if (mysqli_num_rows($result) > 0) {
                $error_messages[] = "Form ID $form_id already assigned to class ID $class_id, program ID $program_id, staff ID $staff_id.";
                continue;
            }

            // Insert form assignment
            $query = "INSERT INTO class_program_staff_forms (class_id, program_id, staff_id, form_id) VALUES (?, ?, ?, ?)";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 'iisi', $class_id, $program_id, $staff_id, $form_id);
            if (mysqli_stmt_execute($stmt)) {
                $success_count++;
            } else {
                $error_messages[] = "Failed to assign form ID $form_id to class ID $class_id: " . mysqli_error($conn);
            }
            mysqli_stmt_close($stmt);
        }

        if ($success_count > 0) {
            $success = "$success_count assignment(s) created successfully!";
        }
        if (!empty($error_messages)) {
            $error = implode('<br>', $error_messages);
        }
    }
}

// Get existing assignments
$assignments = mysqli_fetch_all(mysqli_query($conn, "
    SELECT cpsf.id, c.class_name, p.program_name, u.first_name, u.last_name, u.id AS staff_id, f.title AS form_title
    FROM class_program_staff_forms cpsf
    JOIN classes c ON cpsf.class_id = c.class_id
    JOIN programs p ON cpsf.program_id = p.program_id
    JOIN users u ON cpsf.staff_id = u.id
    JOIN evaluation_forms f ON cpsf.form_id = f.form_id
"), MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Assign Staff to Classes and Program</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/assign_staff.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h2>Assign Staff to Classes and Program</h2>
        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-group mb-3">
                <label>Classes (Hold Ctrl/Cmd to select multiple)</label>
                <select name="class_ids[]" class="form-control" multiple required>
                    <?php foreach ($classes as $c): ?>
                        <option value="<?php echo $c['class_id']; ?>"><?php echo htmlspecialchars($c['class_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group mb-3">
                <label>Program</label>
                <select name="program_id" class="form-control" required>
                    <option value="">-- Select Program --</option>
                    <?php foreach ($programs as $p): ?>
                        <option value="<?php echo $p['program_id']; ?>"><?php echo htmlspecialchars($p['program_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group mb-3">
                <label>Staff</label>
                <select name="staff_id" class="form-control" required>
                    <option value="">-- Select Staff --</option>
                    <?php foreach ($staff as $s): ?>
                        <option value="<?php echo $s['id']; ?>">
                            <?php echo htmlspecialchars($s['first_name'] . ' ' . $s['last_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group mb-3">
                <label>Evaluation Form</label>
                <select name="form_id" class="form-control" required>
                    <option value="">-- Select Evaluation Form --</option>
                    <?php foreach ($forms as $f): ?>
                        <option value="<?php echo $f['form_id']; ?>"><?php echo htmlspecialchars($f['display_title']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">Assign</button>
        </form>

        <h3>Current Assignments</h3>
        <?php if (empty($assignments)): ?>
            <p>No assignments found.</p>
        <?php else: ?>
            <table class="table">
                <thead>
                    <tr>
                        <th>Class</th>
                        <th>Program</th>
                        <th>Staff</th>
                        <th>Form</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($assignments as $a): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($a['class_name']); ?></td>
                            <td><?php echo htmlspecialchars($a['program_name']); ?></td>
                            <td><?php echo htmlspecialchars($a['first_name'] . ' ' . $a['last_name']); ?></td>
                            <td><?php echo htmlspecialchars($a['form_title']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>

        <a href="dashboard.php" class="btn btn-secondary mt-3">Back to Dashboard</a>
    </div>
</body>
</html>     