<?php
session_start();
require 'db.php';

// Redirect if not admin
if (!isset($_SESSION['admin_id'])) {
    header("Location: admin-login.php");
    exit();
}

$success = "";
$error = "";

// Handle Update Instructor
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['id'])) {
    $id = $_POST['id'];
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);

    // Check for duplicate email (excluding current)
    $check = $conn->prepare("SELECT id FROM Instructors WHERE email = ? AND id != ?");
    $check->bind_param("si", $email, $id);
    $check->execute();
    $check->store_result();

    if ($check->num_rows > 0) {
        $error = "This email is already in use by another instructor.";
    } else {
        $stmt = $conn->prepare("UPDATE Instructors SET first_name=?, last_name=?, email=? WHERE id=?");
        $stmt->bind_param("sssi", $first_name, $last_name, $email, $id);
        if ($stmt->execute()) {
            $success = "Instructor updated successfully.";
        } else {
            $error = "Update failed: " . $stmt->error;
        }
        $stmt->close();
    }
    $check->close();
}

// Handle Add Instructor
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['action']) && $_POST['action'] === 'add') {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $password = password_hash(trim($_POST['password']), PASSWORD_DEFAULT);

    $check = $conn->prepare("SELECT id FROM Instructors WHERE email = ?");
    $check->bind_param("s", $email);
    $check->execute();
    $check->store_result();

    if ($check->num_rows > 0) {
        $error = "This email is already registered.";
    } else {
        $stmt = $conn->prepare("INSERT INTO Instructors (first_name, last_name, email, password) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("ssss", $first_name, $last_name, $email, $password);
        if ($stmt->execute()) {
            $success = "Instructor added successfully.";
        } else {
            $error = "Failed to add instructor.";
        }
        $stmt->close();
    }
    $check->close();
}

// Handle Remove Instructor
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['action']) && $_POST['action'] === 'delete') {
    $instructor_id = intval($_POST['instructor_id']);

    $stmt = $conn->prepare("DELETE FROM Instructors WHERE id = ?");
    $stmt->bind_param("i", $instructor_id);
    if ($stmt->execute()) {
        $success = "Instructor removed successfully.";
    } else {
        $error = "Error: Could not remove instructor.";
    }
    $stmt->close();
}

// Fetch instructors for removal dropdown
$instructors = $conn->query("SELECT id, first_name, last_name FROM Instructors ORDER BY last_name");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Instructors</title>
    <style>
        body { font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px; }
        .container { max-width: 600px; margin: auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        h2 { text-align: center; }
        label, input, select { display: block; width: 100%; margin-top: 10px; padding: 8px; }
        input[type=submit] { background: #007bff; color: white; border: none; cursor: pointer; margin-top: 20px; }
        .success { color: green; text-align: center; }
        .error { color: red; text-align: center; }
        .nav-btn {
            padding: 10px 20px;
            background: #007bff;
            color: white;
            border-radius: 5px;
            text-decoration: none;
            font-weight: bold;
        }
        .nav-btn:hover {
            background: #0056b3;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Manage Instructors</h2>
        <?php if ($success): ?><p class="success">✅ <?= $success ?></p><?php endif; ?>
        <?php if ($error): ?><p class="error">⚠️ <?= $error ?></p><?php endif; ?>

        <form method="post">
            <h3>Add New Instructor</h3>
            <input type="hidden" name="action" value="add">
            <label for="first_name">First Name:</label>
            <input type="text" name="first_name" required>

            <label for="last_name">Last Name:</label>
            <input type="text" name="last_name" required>

            <label for="email">Email:</label>
            <input type="email" name="email" required>

            <label for="password">Password:</label>
            <input type="password" name="password" required>

            <input type="submit" value="Add Instructor">
        </form>

        <hr>

        <form method="post">
            <h3>Remove Instructor</h3>
            <input type="hidden" name="action" value="delete">
            <label for="instructor_id">Select Instructor:</label>
            <select name="instructor_id" required>
                <option value="">-- Choose Instructor --</option>
                <?php while ($inst = $instructors->fetch_assoc()): ?>
                    <option value="<?= $inst['id'] ?>">
                        <?= htmlspecialchars($inst['last_name'] . ", " . $inst['first_name']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
            <input type="submit" value="Remove Instructor">
        </form>
    </div>

    <div style="text-align: center; margin-top: 30px;">
        <a href="admin-dashboard.php" class="nav-btn">✅ Finished Updating</a>
    </div>
</body>
</html>

