<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['admin', 'system_admin', 'super_admin'])) {
    header("Location: login.php");
    exit();
}

include '../includes/db.php';
include 'includes/header.php';

$message = "";

// Handle Add Program
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_program'])) {
    $program_name = $conn->real_escape_string($_POST['program_name']);
    $degree_level = $conn->real_escape_string($_POST['degree_level']);
    $duration = $conn->real_escape_string($_POST['duration']);
    $department = $conn->real_escape_string($_POST['department']);
    $fee = $conn->real_escape_string($_POST['fee']);
    $admission_criteria = $conn->real_escape_string($_POST['admission_criteria']);

    $sql = "INSERT INTO programs (program_name, degree_level, duration, department, fee_per_semester, admission_criteria) 
            VALUES ('$program_name', '$degree_level', '$duration', '$department', '$fee', '$admission_criteria')";
    
    if ($conn->query($sql) === TRUE) {
        $message = "Program added successfully!";
    } else {
        $message = "Error adding program: " . $conn->error;
    }
}

// Handle Update Program
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_program'])) {
    $id = intval($_POST['program_id']);
    $program_name = $conn->real_escape_string($_POST['program_name']);
    $degree_level = $conn->real_escape_string($_POST['degree_level']);
    $duration = $conn->real_escape_string($_POST['duration']);
    $department = $conn->real_escape_string($_POST['department']);
    $fee = $conn->real_escape_string($_POST['fee']);
    $admission_criteria = $conn->real_escape_string($_POST['admission_criteria']);

    $sql = "UPDATE programs SET 
            program_name='$program_name', 
            degree_level='$degree_level', 
            duration='$duration', 
            department='$department', 
            fee_per_semester='$fee',
            admission_criteria='$admission_criteria' 
            WHERE id=$id";
    
    if ($conn->query($sql) === TRUE) {
        $message = "Program updated successfully!";
    } else {
        $message = "Error updating program: " . $conn->error;
    }
}

// Handle Delete Program
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $sql = "DELETE FROM programs WHERE id = $id";
    $conn->query($sql);
    header("Location: manage_programs.php");
    exit();
}

// Handle Edit Program - fetch program data
$edit_program = null;
if (isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $edit_sql = "SELECT * FROM programs WHERE id = $edit_id";
    $edit_result = $conn->query($edit_sql);
    $edit_program = $edit_result->fetch_assoc();
}

// Handle filters
$filter_degree = $_GET['filter_degree'] ?? '';
$filter_department = $_GET['filter_department'] ?? '';

// Build query with filters
$where_clause = "";
if (!empty($filter_degree)) {
    $where_clause .= " WHERE degree_level = '$filter_degree'";
}
if (!empty($filter_department)) {
    $where_clause .= ($where_clause ? " AND" : " WHERE") . " department = '$filter_department'";
}

// Get all programs with filters
$programs_sql = "SELECT * FROM programs $where_clause ORDER BY program_name";
$programs_result = $conn->query($programs_sql);

// Get unique degrees and departments for filters
$degrees_sql = "SELECT DISTINCT degree_level FROM programs ORDER BY degree_level";
$degrees_result = $conn->query($degrees_sql);

$departments_sql = "SELECT DISTINCT department FROM programs ORDER BY department";
$departments_result = $conn->query($departments_sql);
?>

<div class="dashboard-container">
    <div class="sidebar admin-sidebar">
        <?php include 'includes/sidebar.php'; ?>
    </div>

    <div class="main-content">
        <h2>Manage Programs</h2>
        
        <?php if($message): ?>
            <div class="alert alert-info"><?php echo $message; ?></div>
        <?php endif; ?>

        <!-- Filters Section -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Filter Programs</h3>
            </div>
            <div class="card-body">
                <form method="GET" action="">
                    <div style="display: grid; grid-template-columns: 1fr 1fr auto; gap: 15px; align-items: end;">
                        <div class="form-group">
                            <label>Degree Level</label>
                            <select name="filter_degree" class="form-control">
                                <option value="">All Levels</option>
                                <?php while($degree = $degrees_result->fetch_assoc()): ?>
                                    <option value="<?php echo $degree['degree_level']; ?>" 
                                            <?php echo ($filter_degree == $degree['degree_level']) ? 'selected' : ''; ?>>
                                        <?php echo $degree['degree_level']; ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Department</label>
                            <select name="filter_department" class="form-control">
                                <option value="">All Departments</option>
                                <?php while($dept = $departments_result->fetch_assoc()): ?>
                                    <option value="<?php echo $dept['department']; ?>" 
                                            <?php echo ($filter_department == $dept['department']) ? 'selected' : ''; ?>>
                                        <?php echo $dept['department']; ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <button type="submit" class="btn-primary">Apply Filters</button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h3 class="card-title"><?php echo $edit_program ? 'Edit Program' : 'Add New Program'; ?></h3>
            </div>
            <div class="card-body">
                <form method="POST" action="">
                    <?php if($edit_program): ?>
                        <input type="hidden" name="program_id" value="<?php echo $edit_program['id']; ?>">
                    <?php endif; ?>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                        <div class="form-group">
                            <label>Program Name</label>
                            <input type="text" name="program_name" class="form-control" 
                                   value="<?php echo $edit_program['program_name'] ?? ''; ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Degree Level</label>
                            <select name="degree_level" class="form-control" required>
                                <option value="">-- Select Level --</option>
                                <option value="Bachelor" <?php echo ($edit_program['degree_level'] ?? '') == 'Bachelor' ? 'selected' : ''; ?>>Bachelor</option>
                                <option value="Master" <?php echo ($edit_program['degree_level'] ?? '') == 'Master' ? 'selected' : ''; ?>>Master</option>
                                <option value="PhD" <?php echo ($edit_program['degree_level'] ?? '') == 'PhD' ? 'selected' : ''; ?>>PhD</option>
                                <option value="Diploma" <?php echo ($edit_program['degree_level'] ?? '') == 'Diploma' ? 'selected' : ''; ?>>Diploma</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Duration (Years)</label>
                            <input type="number" name="duration" class="form-control" min="1" max="10" 
                                   value="<?php echo $edit_program['duration'] ?? ''; ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Department</label>
                            <input type="text" name="department" class="form-control" 
                                   value="<?php echo $edit_program['department'] ?? ''; ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Fee per Semester</label>
                            <input type="number" name="fee" class="form-control" min="0" step="0.01" 
                                   value="<?php echo $edit_program['fee_per_semester'] ?? ''; ?>" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Admission Criteria</label>
                        <textarea name="admission_criteria" class="form-control" rows="3"><?php echo $edit_program['admission_criteria'] ?? ''; ?></textarea>
                    </div>
                    <button type="submit" name="<?php echo $edit_program ? 'update_program' : 'add_program'; ?>" class="btn-primary">
                        <?php echo $edit_program ? 'Update Program' : 'Add Program'; ?>
                    </button>
                    <?php if($edit_program): ?>
                        <a href="manage_programs.php" class="btn-outline" style="margin-left: 10px;">Cancel</a>
                    <?php endif; ?>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Existing Programs</h3>
            </div>
            <div class="card-body">
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Program Name</th>
                            <th>Degree Level</th>
                            <th>Duration</th>
                            <th>Department</th>
                            <th>Fee/Semester</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if($programs_result->num_rows > 0): ?>
                            <?php while($program = $programs_result->fetch_assoc()): ?>
                                <tr>
                                    <td>#<?php echo $program['id']; ?></td>
                                    <td><?php echo $program['program_name']; ?></td>
                                    <td><?php echo $program['degree_level']; ?></td>
                                    <td><?php echo $program['duration']; ?> years</td>
                                    <td><?php echo $program['department']; ?></td>
                                    <td>Rs. <?php echo number_format($program['fee_per_semester'], 2); ?></td>
                                    <td>
                                        <a href="?edit=<?php echo $program['id']; ?>" class="btn-primary" style="padding: 5px 10px; font-size: 0.9rem;">Edit</a>
                                        <a href="?delete=<?php echo $program['id']; ?>" 
                                           class="btn-danger" style="padding: 5px 10px; font-size: 0.9rem;"
                                           onclick="return confirm('Are you sure you want to delete this program?')">Delete</a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" style="text-align: center;">No programs found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
