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

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

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $program_name = trim($_POST['program_name']);
    $program_id = $_POST['program_id'] ?? null;

    if (empty($program_name)) {
        $error = "Program name is required.";
    } else {
        if ($program_id) {
            // Update program
            $query = "UPDATE programs SET program_name = ? WHERE program_id = ?";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 'si', $program_name, $program_id);
            if (mysqli_stmt_execute($stmt)) {
                $success = "Program updated successfully!";
            } else {
                $error = "Failed to update program: " . mysqli_error($conn);
            }
        } else {
            // Create program
            $query = "INSERT INTO programs (program_name) VALUES (?)";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 's', $program_name);
            if (mysqli_stmt_execute($stmt)) {
                $success = "Program created successfully!";
            } else {
                $error = "Failed to create program: " . mysqli_error($conn);
            }
        }
    }
}

// Handle delete
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $program_id = $_GET['delete'];
    $query = "DELETE FROM programs WHERE program_id = ?";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, 'i', $program_id);
    if (mysqli_stmt_execute($stmt)) {
        $success = "Program deleted successfully!";
    } else {
        $error = "Failed to delete program: " . mysqli_error($conn);
    }
}

// Get all programs
$programs = mysqli_fetch_all(mysqli_query($conn, "SELECT * FROM programs"), MYSQLI_ASSOC);

// Get program for editing
$edit_program = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $query = "SELECT * FROM programs WHERE program_id = ?";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, 'i', $_GET['edit']);
    mysqli_stmt_execute($stmt);
    $edit_program = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Manage Programs</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/manageprog.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h2>Manage Programs</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 htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <!-- Create/Edit Form -->
        <form method="POST">
            <div class="form-group">
                <label>Program Name</label>
                <input type="text" name="program_name" class="form-control" value="<?php echo $edit_program ? htmlspecialchars($edit_program['program_name']) : ''; ?>" required>
                <?php if ($edit_program): ?>
                    <input type="hidden" name="program_id" value="<?php echo $edit_program['program_id']; ?>">
                <?php endif; ?>
            </div>
            <button type="submit" class="btn btn-primary"><?php echo $edit_program ? 'Update Program' : 'Create Program'; ?></button>
            <?php if ($edit_program): ?>
                <a href="program_manage.php" class="btn btn-secondary">Cancel</a>
            <?php endif; ?>
        </form>

        <!-- Program List -->
        <h3>Program List</h3>
        <?php if (empty($programs)): ?>
            <p>No programs found.</p>
        <?php else: ?>
            <table class="table">
                <thead>
                    <tr>
                        <th>Program Name</th>
                        <th>Created At</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($programs as $program): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($program['program_name']); ?></td>
                            <td><?php echo $program['created_at']; ?></td>
                            <td>
                                <a href="?edit=<?php echo $program['program_id']; ?>" class="btn btn-primary btn-sm">Edit</a>
                                <a href="?delete=<?php echo $program['program_id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure?');">Delete</a>
                            </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>