<?php
include '../includes/db.php';
include 'includes/header.php';
include 'includes/excel_export.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 Status Toggle
if (isset($_GET['toggle'])) {
    $id = $_GET['toggle'];
    $sql = "UPDATE programs SET is_active = NOT is_active WHERE id = $id";
    $conn->query($sql);
    header("Location: programs.php");
    exit();
}

// Fetch Programs
$sql = "SELECT * FROM programs ORDER BY department, program_name";
$result = $conn->query($sql);

// Handle Excel Export
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    $export_data = [];
    $headers = ['Program Name', 'Degree Level', 'Duration', 'Department', 'Fee Per Semester', 'Admission Criteria', 'Status'];
    
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $export_data[] = [
                cleanForExcel($row['program_name']),
                cleanForExcel($row['degree_level']),
                cleanForExcel($row['duration']),
                cleanForExcel($row['department']),
                cleanForExcel($row['fee_per_semester']),
                cleanForExcel($row['admission_criteria']),
                $row['is_active'] ? 'Active' : 'Inactive'
            ];
        }
    }
    
    // Reset result pointer for normal display
    $result->data_seek(0);
    
    $filename = 'Programs_' . date('Y-m-d_H-i-s') . '.xls';
    exportToExcel($export_data, $filename, $headers);
}
?>

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

    <div class="main-content">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Manage Programs</h3>
                <div style="display: flex; gap: 10px;">
                    <a href="?export=excel" class="btn-success" style="padding: 5px 15px; font-size: 0.9rem; text-decoration: none; color: white;"><i class="fas fa-file-excel"></i> Export to Excel</a>
                    <button onclick="showAddForm()" class="btn-primary" style="padding: 5px 15px; text-decoration: none; border: none; cursor: pointer;">
                        <i class="fas fa-plus"></i> Add New
                    </button>
                </div>
            </div>

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

            <!-- Add/Edit Program Form -->
            <div id="program-form" style="display: none; background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 30px; border: 1px solid #ddd;">
                <h4 style="margin-top: 0; margin-bottom: 20px;" id="form-title">Add New Program</h4>
                <form method="POST" action="">
                    <input type="hidden" name="add_program" id="action_add" value="1">
                    <input type="hidden" name="update_program" id="action_update" disabled>
                    <input type="hidden" name="program_id" id="program_id">
                    
                    <div style="display: flex; gap: 20px; flex-wrap: wrap;">
                        <div class="form-group" style="flex: 1;">
                            <label>Program Name</label>
                            <input type="text" name="program_name" id="program_name" class="form-control" required>
                        </div>
                        <div class="form-group" style="flex: 1;">
                            <label>Department</label>
                            <input type="text" name="department" id="department" class="form-control" required>
                        </div>
                    </div>
                    
                    <div style="display: flex; gap: 20px; flex-wrap: wrap;">
                        <div class="form-group" style="flex: 1;">
                            <label>Degree Level</label>
                            <select name="degree_level" id="degree_level" class="form-control" required>
                                <option value="Bachelor">Bachelor</option>
                                <option value="Master">Master</option>
                                <option value="PhD">PhD</option>
                                <option value="Diploma">Diploma</option>
                            </select>
                        </div>
                        <div class="form-group" style="flex: 1;">
                            <label>Duration</label>
                            <input type="text" name="duration" id="duration" class="form-control" placeholder="e.g. 4 Years" required>
                        </div>
                        <div class="form-group" style="flex: 1;">
                            <label>Fee Per Semester</label>
                            <input type="number" name="fee" id="fee" class="form-control" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Admission Criteria</label>
                        <textarea name="admission_criteria" id="admission_criteria" class="form-control" rows="4" required></textarea>
                    </div>

                    <div style="text-align: right;">
                        <button type="button" onclick="closeForm()" class="btn-outline" style="padding: 8px 20px; margin-right: 10px;">Cancel</button>
                        <button type="submit" class="btn-primary" style="padding: 8px 20px;" id="submit-btn">Save Program</button>
                    </div>
                </form>
            </div>

            <script>
            function showAddForm() {
                document.getElementById('program-form').style.display = 'block';
                document.getElementById('form-title').innerText = 'Add New Program';
                document.getElementById('action_add').disabled = false;
                document.getElementById('action_update').disabled = true;
                document.getElementById('submit-btn').innerText = 'Save Program';
                
                // Clear fields
                document.getElementById('program_id').value = '';
                document.getElementById('program_name').value = '';
                document.getElementById('department').value = '';
                document.getElementById('degree_level').value = 'Bachelor';
                document.getElementById('duration').value = '';
                document.getElementById('fee').value = '';
                document.getElementById('admission_criteria').value = '';
            }

            function showEditForm(id, name, dept, level, duration, fee, criteria) {
                document.getElementById('program-form').style.display = 'block';
                document.getElementById('form-title').innerText = 'Edit Program';
                document.getElementById('action_add').disabled = true;
                document.getElementById('action_update').disabled = false;
                document.getElementById('submit-btn').innerText = 'Update Program';

                // Populate fields
                document.getElementById('program_id').value = id;
                document.getElementById('program_name').value = name;
                document.getElementById('department').value = dept;
                document.getElementById('degree_level').value = level;
                document.getElementById('duration').value = duration;
                document.getElementById('fee').value = fee;
                document.getElementById('admission_criteria').value = criteria;
                
                // Scroll to form
                document.getElementById('program-form').scrollIntoView({behavior: 'smooth'});
            }

            function closeForm() {
                document.getElementById('program-form').style.display = 'none';
            }
            </script>

            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Program Name</th>
                        <th>Department</th>
                        <th>Level</th>
                        <th>Fee</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($result->num_rows > 0): ?>
                        <?php while($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo $row['id']; ?></td>
                            <td><?php echo $row['program_name']; ?></td>
                            <td><?php echo $row['department']; ?></td>
                            <td><?php echo $row['degree_level']; ?></td>
                            <td><?php echo number_format($row['fee_per_semester']); ?></td>
                            <td>
                                <?php if($row['is_active']): ?>
                                    <span class="badge badge-success">Active</span>
                                <?php else: ?>
                                    <span class="badge badge-danger">Inactive</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <button onclick="showEditForm(<?php echo $row['id']; ?>, '<?php echo addslashes($row['program_name']); ?>', '<?php echo addslashes($row['department']); ?>', '<?php echo $row['degree_level']; ?>', '<?php echo addslashes($row['duration']); ?>', '<?php echo $row['fee_per_semester']; ?>', '<?php echo str_replace(array("\r", "\n"), array('\r', '\n'), addslashes($row['admission_criteria'])); ?>')" class="btn-primary" style="padding: 5px 10px; font-size: 0.8rem; margin-right: 5px;">
                                    Edit
                                </button>
                                <a href="programs.php?toggle=<?php echo $row['id']; ?>" style="color: <?php echo $row['is_active'] ? '#d32f2f' : '#388e3c'; ?>; text-decoration: none; font-weight: bold;">
                                    <?php echo $row['is_active'] ? 'Deactivate' : 'Activate'; ?>
                                </a>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="text-center">No programs found.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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