<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "../include/config.php";

// Check login and instructor role
if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit();
}

// Check if user is admin or instructor
$email = $_SESSION['email'];
 
$role = $_SESSION['role'];

$success = "";
$error = "";
$edit_mode = false;
$edit_id = 0;
$edit_program = "";

// Handle Add/Edit Program
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_program'])) {
        $program_name = trim($_POST['program_name']);
        
        if (empty($program_name)) {
            $error = "Program name is required!";
        } else {
            // Convert to uppercase
            $program_name = strtoupper($program_name);
            $program_esc = $conn->real_escape_string($program_name);
            
            // Check if program already exists
            $check_sql = "SELECT id FROM programs WHERE program = '$program_esc'";
            $check_result = $conn->query($check_sql);
            
            if ($check_result->num_rows > 0) {
                $error = "Program '$program_name' already exists!";
            } else {
                $insert_sql = "INSERT INTO programs (program) VALUES ('$program_esc')";
                if ($conn->query($insert_sql)) {
                    $success = "Program '$program_name' added successfully!";
                } else {
                    $error = "Error adding program: " . $conn->error;
                }
            }
        }
    }
    
    // Handle Edit Program
    if (isset($_POST['edit_program'])) {
        $edit_id = intval($_POST['edit_id']);
        $program_name = trim($_POST['program_name']);
        
        if (empty($program_name)) {
            $error = "Program name is required!";
        } else {
            // Convert to uppercase
            $program_name = strtoupper($program_name);
            $program_esc = $conn->real_escape_string($program_name);
            
            // Check if program already exists (excluding current one)
            $check_sql = "SELECT id FROM programs WHERE program = '$program_esc' AND id != $edit_id";
            $check_result = $conn->query($check_sql);
            
            if ($check_result->num_rows > 0) {
                $error = "Program '$program_name' already exists!";
            } else {
                $update_sql = "UPDATE programs SET program = '$program_esc' WHERE id = $edit_id";
                if ($conn->query($update_sql)) {
                    $success = "Program updated successfully to '$program_name'!";
                    $edit_mode = false;
                    $edit_id = 0;
                    $edit_program = "";
                } else {
                    $error = "Error updating program: " . $conn->error;
                }
            }
        }
    }
    
    // Handle Cancel Edit
    if (isset($_POST['cancel_edit'])) {
        $edit_mode = false;
        $edit_id = 0;
        $edit_program = "";
    }
}

// Handle Delete Program
if (isset($_GET['delete_program'])) {
    $delete_id = intval($_GET['delete_program']);
    
    // Check if program is being used in students table
    $check_usage = $conn->query("SELECT COUNT(*) as count FROM students WHERE program = (SELECT program FROM programs WHERE id = $delete_id)");
    $usage_data = $check_usage->fetch_assoc();
    
    if ($usage_data['count'] > 0) {
        $_SESSION['error'] = "Cannot delete program! It is being used by " . $usage_data['count'] . " student(s).";
    } else {
        // Check if program is being used in assignments table
        $check_assignments = $conn->query("SELECT COUNT(*) as count FROM assignments WHERE program = (SELECT program FROM programs WHERE id = $delete_id)");
        $assign_data = $check_assignments->fetch_assoc();
        
        if ($assign_data['count'] > 0) {
            $_SESSION['error'] = "Cannot delete program! It is being used in " . $assign_data['count'] . " assignment(s).";
        } else {
            $delete_sql = "DELETE FROM programs WHERE id = $delete_id";
            if ($conn->query($delete_sql)) {
                $_SESSION['success'] = "Program deleted successfully!";
            } else {
                $_SESSION['error'] = "Error deleting program: " . $conn->error;
            }
        }
    }
    
    header("Location: programs_manager.php");
    exit();
}

// Handle Edit Request
if (isset($_GET['edit_program'])) {
    $edit_id = intval($_GET['edit_program']);
    $edit_sql = "SELECT program FROM programs WHERE id = $edit_id";
    $edit_result = $conn->query($edit_sql);
    
    if ($edit_result->num_rows > 0) {
        $edit_data = $edit_result->fetch_assoc();
        $edit_program = $edit_data['program'];
        $edit_mode = true;
    } else {
        $_SESSION['error'] = "Program not found!";
        header("Location: programs_manager.php");
        exit();
    }
}

// Fetch all programs
$programs_sql = "SELECT id, program FROM programs ORDER BY program";
$programs_result = $conn->query($programs_sql);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Programs</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background-color: #f8f9fa; }
        .card { border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .table th { background-color: #343a40; color: white; }
        .btn-action { width: 80px; }
        .program-badge { 
            background-color: #e9ecef; 
            color: #495057; 
            padding: 5px 10px; 
            border-radius: 5px; 
            font-weight: bold;
            text-transform: uppercase;
        }
        .modal-header { background-color: #dc3545; color: white; }
    </style>
</head>
<body>
<?php include "../include/nav.php"; ?>
<div class="container mt-4">
    <div class="row">
        <div class="col-md-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-graduation-cap"></i> Manage Programs</h2>
                <a href="dashboard.php" class="btn btn-outline-primary">
                    <i class="fas fa-arrow-left"></i> Back to Dashboard
                </a>
            </div>
            
            <!-- Display success/error messages -->
            <?php if (isset($_SESSION['success'])): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if (isset($_SESSION['error'])): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-triangle"></i> <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle"></i> <?php echo $success; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="row">
        <!-- Add/Edit Program Form -->
        <div class="col-md-4 mb-4">
            <div class="card">
                <div class="card-header <?php echo $edit_mode ? 'bg-warning text-dark' : 'bg-primary text-white'; ?>">
                    <h5 class="mb-0">
                        <i class="fas <?php echo $edit_mode ? 'fa-edit' : 'fa-plus-circle'; ?>"></i>
                        <?php echo $edit_mode ? 'Edit Program' : 'Add New Program'; ?>
                    </h5>
                </div>
                <div class="card-body">
                    <form method="POST" id="programForm">
                        <?php if ($edit_mode): ?>
                            <input type="hidden" name="edit_id" value="<?php echo $edit_id; ?>">
                        <?php endif; ?>
                        
                        <div class="mb-3">
                            <label for="program_name" class="form-label">
                                Program Name <span class="text-danger">*</span>
                                <small class="text-muted">(Will be saved in CAPITAL LETTERS)</small>
                            </label>
                            <input type="text" 
                                   class="form-control" 
                                   id="program_name" 
                                   name="program_name" 
                                   value="<?php echo htmlspecialchars($edit_program); ?>" 
                                   required
                                   placeholder="e.g., COM210-COMPUTER SCIENCE"
                                   oninput="this.value = this.value.toUpperCase()">
                            <div class="form-text">Enter program name. It will be automatically converted to uppercase.</div>
                        </div>
                        
                        <div class="d-grid gap-2">
                            <?php if ($edit_mode): ?>
                                <button type="submit" name="edit_program" class="btn btn-warning">
                                    <i class="fas fa-save"></i> Update Program
                                </button>
                                <button type="submit" name="cancel_edit" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> Cancel Edit
                                </button>
                            <?php else: ?>
                                <button type="submit" name="add_program" class="btn btn-primary">
                                    <i class="fas fa-plus-circle"></i> Add Program
                                </button>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- Instructions Card -->
            <div class="card mt-4">
                <div class="card-header bg-info text-white">
                    <h6 class="mb-0"><i class="fas fa-info-circle"></i> Instructions</h6>
                </div>
                <div class="card-body">
                    <ul class="mb-0">
                        <li>Program names are automatically saved in CAPITAL LETTERS</li>
                        <li>Click <i class="fas fa-edit text-warning"></i> to edit a program</li>
                        <li>Click <i class="fas fa-trash text-danger"></i> to delete a program</li>
                        <li>Programs cannot be deleted if they have students or assignments</li>
                        <li>Use clear, descriptive program names</li>
                    </ul>
                </div>
            </div>
        </div>
        
        <!-- Programs List -->
        <div class="col-md-8">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0"><i class="fas fa-list"></i> All Programs (<?php echo $programs_result->num_rows; ?>)</h5>
                </div>
                <div class="card-body">
                    <?php if ($programs_result->num_rows > 0): ?>
                        <div class="table-responsive">
                            <table class="table table-hover table-striped">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Program Name</th>
                                        <th>Students Count</th>
                                        <th>Assignments Count</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $count = 1;
                                    while($program = $programs_result->fetch_assoc()): 
                                        // Count students in this program
                                        $program_name = $program['program'];
                                        $students_count = $conn->query("SELECT COUNT(*) as count FROM students WHERE program = '$program_name'")->fetch_assoc()['count'];
                                        
                                        // Count assignments for this program
                                        $assignments_count = $conn->query("SELECT COUNT(*) as count FROM assignments WHERE program = '$program_name'")->fetch_assoc()['count'];
                                    ?>
                                        <tr>
                                            <td><?php echo $count++; ?></td>
                                            <td>
                                                <span class="program-badge">
                                                    <?php echo htmlspecialchars($program['program']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge bg-primary"><?php echo $students_count; ?> student(s)</span>
                                            </td>
                                            <td>
                                                <span class="badge bg-info"><?php echo $assignments_count; ?> assignment(s)</span>
                                            </td>
                                            <td>
                                                <div class="btn-group" role="group">
                                                    <a href="?edit_program=<?php echo $program['id']; ?>" 
                                                       class="btn btn-sm btn-warning" 
                                                       title="Edit Program">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <button type="button" 
                                                            class="btn btn-sm btn-danger" 
                                                            onclick="confirmDelete(<?php echo $program['id']; ?>, '<?php echo htmlspecialchars($program['program']); ?>', <?php echo $students_count; ?>, <?php echo $assignments_count; ?>)" 
                                                            title="Delete Program"
                                                            <?php echo ($students_count > 0 || $assignments_count > 0) ? 'disabled' : ''; ?>>
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-4">
                            <i class="fas fa-graduation-cap fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">No programs found</h5>
                            <p class="text-muted">Add your first program using the form on the left</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-exclamation-triangle text-danger"></i> Confirm Delete</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="deleteMessage"></div>
                <div class="alert alert-danger mt-3">
                    <i class="fas fa-warning"></i> <strong>Warning:</strong> This action cannot be undone!
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <a href="#" id="confirmDeleteBtn" class="btn btn-danger">Delete Program</a>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Auto-uppercase input
document.getElementById('program_name').addEventListener('input', function() {
    this.value = this.value.toUpperCase();
});

// Delete confirmation
function confirmDelete(programId, programName, studentsCount, assignmentsCount) {
    let message = `Are you sure you want to delete the program: <strong>${programName}</strong>?`;
    
    if (studentsCount > 0) {
        message += `<br><span class="text-danger"><i class="fas fa-users"></i> This program has ${studentsCount} student(s) assigned to it.</span>`;
    }
    
    if (assignmentsCount > 0) {
        message += `<br><span class="text-danger"><i class="fas fa-file-alt"></i> This program has ${assignmentsCount} assignment(s) associated with it.</span>`;
    }
    
    if (studentsCount > 0 || assignmentsCount > 0) {
        message += `<br><br><strong>You cannot delete this program until all students and assignments are removed or reassigned.</strong>`;
    }
    
    document.getElementById('deleteMessage').innerHTML = message;
    document.getElementById('confirmDeleteBtn').href = `programs_manager.php?delete_program=${programId}`;
    
    // Disable delete button if program has students or assignments
    if (studentsCount > 0 || assignmentsCount > 0) {
        document.getElementById('confirmDeleteBtn').disabled = true;
        document.getElementById('confirmDeleteBtn').className = 'btn btn-danger disabled';
    } else {
        document.getElementById('confirmDeleteBtn').disabled = false;
        document.getElementById('confirmDeleteBtn').className = 'btn btn-danger';
    }
    
    const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    deleteModal.show();
}

// Auto-focus on program name input
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('program_name').focus();
});
</script>
</body>
</html>

<?php
$conn->close();
ob_end_flush();
?>