<?php
require 'db_connection.php';

$message = '';
$message_type = 'success';

$edit_mode = false;
$edit_id = 0;
$edit_name = '';
$edit_section = 'primary';

/* =========================
   HANDLE FORM ACTIONS
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $action = $_POST['action'] ?? '';

    /* ===== ADD SUBJECT ===== */
    if ($action === 'add') {

        $name = trim($_POST['subject_name']);
        $section = $_POST['section'];

        $stmt = $conn->prepare("INSERT INTO subject (subject_name, section) VALUES (?, ?)");
        $stmt->bind_param("ss", $name, $section);

        if ($stmt->execute()) {
            $message = "Subject added successfully.";
        } else {
            $message = "Failed to add subject.";
            $message_type = "error";
        }
    }

    /* ===== UPDATE SUBJECT ===== */
    if ($action === 'update') {

        $id = intval($_POST['subject_id']);
        $name = trim($_POST['subject_name']);
        $section = $_POST['section'];

        $stmt = $conn->prepare("
            UPDATE subject 
            SET subject_name = ?, section = ?
            WHERE subject_id = ?
        ");
        $stmt->bind_param("ssi", $name, $section, $id);

        if ($stmt->execute()) {
            $message = "Subject updated successfully.";
        } else {
            $message = "Update failed.";
            $message_type = "error";
        }
    }

    /* ===== DELETE SUBJECT ===== */
    if ($action === 'delete') {

        $id = intval($_POST['subject_id']);

        $stmt = $conn->prepare("SELECT COUNT(*) FROM class_subject WHERE subject_id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->bind_result($total);
        $stmt->fetch();
        $stmt->close();

        if ($total > 0) {
            $message = "Cannot delete: Subject is assigned to a class.";
            $message_type = "error";
        } else {
            $stmt = $conn->prepare("DELETE FROM subject WHERE subject_id = ?");
            $stmt->bind_param("i", $id);

            if ($stmt->execute()) {
                $message = "Subject deleted successfully.";
            } else {
                $message = "Delete failed.";
                $message_type = "error";
            }
        }
    }
}

/* =========================
   EDIT MODE
========================= */
if (isset($_GET['edit'])) {

    $id = intval($_GET['edit']);

    $stmt = $conn->prepare("SELECT subject_id, subject_name, section FROM subject WHERE subject_id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();

    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        $edit_mode = true;
        $edit_id = $row['subject_id'];
        $edit_name = $row['subject_name'];
        $edit_section = $row['section'];
    }
}

/* =========================
   FETCH SUBJECTS
========================= */
$subjects = $conn->query("SELECT * FROM subject ORDER BY subject_name ASC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Subject Management</title>

<style>
body {
    font-family: Arial, sans-serif;
    margin: 0;
    background: #f4f6f9;
}

/* HEADER */
.header {
    background: #2c3e50;
    color: white;
    padding: 15px 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header h1 {
    margin: 0;
    font-size: 20px;
}

.nav a {
    color: white;
    margin-left: 20px;
    text-decoration: none;
    font-weight: bold;
}

.nav a:hover {
    text-decoration: underline;
}

/* CONTAINER */
.container {
    width: 90%;
    margin: 30px auto;
}

/* CARD */
.card {
    background: white;
    padding: 20px;
    border-radius: 6px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.1);
    margin-bottom: 20px;
}

/* FORM */
input, select {
    padding: 10px;
    width: 100%;
    margin-top: 10px;
    margin-bottom: 15px;
}

button {
    padding: 10px 15px;
    border: none;
    background: #3498db;
    color: white;
    cursor: pointer;
}

button:hover {
    background: #2980b9;
}

/* TABLE */
table {
    width: 100%;
    border-collapse: collapse;
}

table th, table td {
    padding: 12px;
    border-bottom: 1px solid #ddd;
}

table th {
    background: #ecf0f1;
}

/* MESSAGE */
.message {
    padding: 10px;
    margin-bottom: 15px;
    border-radius: 5px;
}

.success {
    background: #d4edda;
    color: #155724;
}

.error {
    background: #f8d7da;
    color: #721c24;
}
</style>
</head>

<body>

<div class="header">
    <h1>School Management System</h1>
    <div class="nav">
        <a href="admin_dashboard.php">Dashboard</a>
        <a href="manage_students.php">Students</a>
        <a href="add_class.php">Classes</a>
        <a href="add_subject.php">Subjects</a>
        <a href="logout.php">Logout</a>
    </div>
</div>

<div class="container">

    <div class="card">
        <h2><?php echo $edit_mode ? 'Edit Subject' : 'Add New Subject'; ?></h2>

        <?php if ($message): ?>
            <div class="message <?php echo $message_type; ?>">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>

        <form method="POST">
            <input type="hidden" name="action" value="<?php echo $edit_mode ? 'update' : 'add'; ?>">
            <input type="hidden" name="subject_id" value="<?php echo $edit_id; ?>">

            <label>Subject Name</label>
            <input type="text" name="subject_name" value="<?php echo htmlspecialchars($edit_name); ?>" required>

            <label>Section</label>
            <select name="section">
                <option value="primary" <?php if($edit_section=='primary') echo 'selected'; ?>>Primary</option>
                <option value="lower secondary" <?php if($edit_section=='lower secondary') echo 'selected'; ?>>Lower Secondary</option>
                <option value="secondary" <?php if($edit_section=='secondary') echo 'selected'; ?>>Secondary</option>
            </select>

            <button type="submit">
                <?php echo $edit_mode ? 'Update Subject' : 'Add Subject'; ?>
            </button>
        </form>
    </div>

    <div class="card">
        <h2>All Subjects</h2>

        <table>
            <tr>
                <th>Subject Name</th>
                <th>Section</th>
                <th>Action</th>
            </tr>

            <?php while ($row = $subjects->fetch_assoc()): ?>
            <tr>
                <td><?php echo htmlspecialchars($row['subject_name']); ?></td>
                <td><?php echo htmlspecialchars($row['section']); ?></td>
                <td>
                    <a href="?edit=<?php echo $row['subject_id']; ?>">Edit</a>

                    <form method="POST" style="display:inline;" 
                          onsubmit="return confirm('Are you sure you want to delete this subject?');">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="subject_id" value="<?php echo $row['subject_id']; ?>">
                        <button type="submit" style="background:#e74c3c;">Delete</button>
                    </form>
                </td>
            </tr>
            <?php endwhile; ?>

        </table>
    </div>

</div>

</body>
</html>