<?php
// index.php
session_start();

// Initialize JSON file if it doesn't exist
if (!file_exists('data/students.json')) {
    file_put_contents('data/students.json', json_encode([]));
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $studentData = [
        'prime_id' => $_POST['prime_id'],
        'surname' => $_POST['surname'],
        'other_names' => $_POST['other_names'],
        'sex' => $_POST['sex'],
        'dob' => $_POST['dob'],
        'religion' => $_POST['religion'],
        'father_phone' => $_POST['father_phone'],
        'mother_phone' => $_POST['mother_phone'] ?? '',
        'previous_class' => $_POST['previous_class'],
        'proposed_class' => $_POST['proposed_class'],
        'state_origin' => $_POST['state_origin'],
        'home_town' => $_POST['home_town'] ?? '',
        'parent_email' => $_POST['parent_email'] ?? '',
        'home_address' => $_POST['home_address'],
        'previous_school' => $_POST['previous_school'],
        'status' => $_POST['status'],
        'registration_date' => date('Y-m-d H:i:s')
    ];

    // Handle photo upload
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = 'uploads/';
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        
        $fileExtension = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
        $fileName = $studentData['prime_id'] . '.' . $fileExtension;
        $uploadPath = $uploadDir . $fileName;
        
        if (move_uploaded_file($_FILES['photo']['tmp_name'], $uploadPath)) {
            $studentData['photo'] = $fileName;
        }
    }

    // Save to JSON
    $students = json_decode(file_get_contents('data/students.json'), true);
    $students[] = $studentData;
    file_put_contents('data/students.json', json_encode($students, JSON_PRETTY_PRINT));
    
    $_SESSION['success'] = "Student registered successfully! Prime ID: " . $studentData['prime_id'];
    header('Location: index.php');
    exit;
}

// Handle delete request
if (isset($_GET['delete'])) {
    $primeId = $_GET['delete'];
    $students = json_decode(file_get_contents('data/students.json'), true);
    
    $updatedStudents = array_filter($students, function($student) use ($primeId) {
        return $student['prime_id'] !== $primeId;
    });
    
    file_put_contents('data/students.json', json_encode(array_values($updatedStudents), JSON_PRETTY_PRINT));
    $_SESSION['success'] = "Student record deleted successfully!";
    header('Location: index.php');
    exit;
}

// Function to generate a unique PRIME ID
function generatePrimeId($existingStudents) {
    $existingIds = [];
    foreach ($existingStudents as $student) {
        $existingIds[] = $student['prime_id'];
    }
    
    $prefix = "PRIME";
    $maxAttempts = 1000;
    $attempt = 0;
    
    do {
        $number = str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        $newId = $prefix . $number;
        $attempt++;
        
        if ($attempt > $maxAttempts) {
            return null; // Safety fallback
        }
    } while (in_array($newId, $existingIds));
    
    return $newId;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ENROLMENT SYSTEM [SAS-V2]</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@7.2.96/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="css/style.css">
    <style>
        .prime-id-generator {
            position: relative;
        }
        .generate-btn {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            z-index: 5;
        }
        .modal-prime-id {
            font-size: 2.5rem;
            font-weight: bold;
            text-align: center;
            color: #0d6efd;
            margin: 20px 0;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 8px;
            border: 2px dashed #0d6efd;
        }
        .copy-success {
            display: none;
            color: #198754;
            text-align: center;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <div class="card shadow">
                    <div class="card-header bg-primary text-white">
                        <h3 class="card-title"><i class="mdi mdi-account-plus"></i> PGA ENROLMENT FORM</h3>
                    </div>
                    <div class="card-body">
                        <?php if (isset($_SESSION['success'])): ?>
                            <div class="alert alert-success"><?= $_SESSION['success']; unset($_SESSION['success']); ?></div>
                        <?php endif; ?>
                        
                        <form method="POST" enctype="multipart/form-data" id="studentForm">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3 prime-id-generator">
                                        <label for="prime_id" class="form-label">PRIME ID <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="prime_id" name="prime_id" required>
                                        <button type="button" class="btn btn-outline-primary generate-btn" data-bs-toggle="modal" data-bs-target="#primeIdModal">
                                            <i class="mdi mdi-auto-fix"></i> Generate
                                        </button>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="surname" class="form-label">Surname <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="surname" name="surname" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="other_names" class="form-label">Other Names <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="other_names" name="other_names" required>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label for="sex" class="form-label">Sex <span class="text-danger">*</span></label>
                                        <select class="form-select" id="sex" name="sex" required>
                                            <option value="">Select Sex</option>
                                            <option value="Male">Male</option>
                                            <option value="Female">Female</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label for="dob" class="form-label">Date of Birth <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" id="dob" name="dob" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="religion" class="form-label">Religion <span class="text-danger">*</span></label>
                                        <select class="form-select" id="religion" name="religion" required>
                                            <option value="">Select Religion</option>
                                            <option value="Christianity">Christianity</option>
                                            <option value="Islam">Islam</option>
                                            <option value="Other">Other</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="father_phone" class="form-label">Father's Phone (11 digits) <span class="text-danger">*</span></label>
                                        <input type="tel" class="form-control" id="father_phone" name="father_phone" pattern="[0-9]{11}" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="mother_phone" class="form-label">Mother's Phone (11 digits)</label>
                                        <input type="tel" class="form-control" id="mother_phone" name="mother_phone" pattern="[0-9]{11}">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="previous_class" class="form-label">Previous Class <span class="text-danger">*</span></label>
                                        <select class="form-select" id="previous_class" name="previous_class" required>
                                            <option value="">Select Previous Class</option>
                                            <option value="BG1">BG1</option>
                                            <option value="BG2">BG2</option>
                                            <option value="KG">KG</option>
                                            <option value="Nur1">Nur1</option>
                                            <option value="Nur2">Nur2</option>
                                            <option value="Pry1">Pry1</option>
                                            <option value="Pry2">Pry2</option>
                                            <option value="Pry3">Pry3</option>
                                            <option value="Pry4">Pry4</option>
                                            <option value="Pry5">Pry5</option>
                                            <option value="Pry6">Pry6</option>
                                            <option value="JSS1">JSS1</option>
                                            <option value="JSS2">JSS2</option>
                                            <option value="JSS3">JSS3</option>
                                            <option value="SSS1">SSS1</option>
                                            <option value="SSS2">SSS2</option>
                                            <option value="SSS3">SSS3</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="proposed_class" class="form-label">Proposed Class <span class="text-danger">*</span></label>
                                        <select class="form-select" id="proposed_class" name="proposed_class" required>
                                            <option value="">Select Proposed Class</option>
                                            <option value="BG1">BG1</option>
                                            <option value="BG2">BG2</option>
                                            <option value="KG">KG</option>
                                            <option value="Nur1">Nur1</option>
                                            <option value="Nur2">Nur2</option>
                                            <option value="Pry1">Pry1</option>
                                            <option value="Pry2">Pry2</option>
                                            <option value="Pry3">Pry3</option>
                                            <option value="Pry4">Pry4</option>
                                            <option value="Pry5">Pry5</option>
                                            <option value="Pry6">Pry6</option>
                                            <option value="JSS1">JSS1</option>
                                            <option value="JSS2">JSS2</option>
                                            <option value="JSS3">JSS3</option>
                                            <option value="SSS1">SSS1</option>
                                            <option value="SSS2">SSS2</option>
                                            <option value="SSS3">SSS3</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="state_origin" class="form-label">State of Origin <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="state_origin" name="state_origin" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="home_town" class="form-label">Home Town</label>
                                        <input type="text" class="form-control" id="home_town" name="home_town">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="parent_email" class="form-label">Parent Email</label>
                                <input type="email" class="form-control" id="parent_email" name="parent_email">
                            </div>
                            
                            <div class="mb-3">
                                <label for="home_address" class="form-label">Home Address <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="home_address" name="home_address" rows="3" required></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label for="previous_school" class="form-label">Previous School Attended <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="previous_school" name="previous_school" required>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="photo" class="form-label">Photo <span class="text-danger">*</span></label>
                                        <input type="file" class="form-control" id="photo" name="photo" accept="image/*" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="status" class="form-label">Status <span class="text-danger">*</span></label>
                                        <select class="form-select" id="status" name="status" required>
                                            <option value="">Select Status</option>
                                            <option value="qualified">Qualified</option>
                                            <option value="disqualified">Disqualified</option>
                                            <option value="probation">Probation</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-primary btn-lg"><i class="mdi mdi-content-save"></i> Register Student</button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- Display all students with edit/delete options -->
                <div class="card shadow mt-4">
                    <div class="card-header bg-info text-white">
                        <h3 class="card-title"><i class="mdi mdi-account-multiple"></i> Registered Students</h3>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>Prime ID</th>
                                        <th>Name</th>
                                        <th>Class</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $students = json_decode(file_get_contents('data/students.json'), true);
                                    foreach ($students as $student): 
                                    ?>
                                        <tr>
                                            <td><?= $student['prime_id'] ?></td>
                                            <td><?= $student['surname'] . ' ' . $student['other_names'] ?></td>
                                            <td><?= $student['proposed_class'] ?></td>
                                            <td>
                                                <span class="badge 
                                                    <?= $student['status'] == 'qualified' ? 'bg-success' : 
                                                        ($student['status'] == 'disqualified' ? 'bg-danger' : 'bg-warning') ?>">
                                                    <?= ucfirst($student['status']) ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="edit_student.php?prime_id=<?= $student['prime_id'] ?>" class="btn btn-sm btn-outline-primary">
                                                    <i class="mdi mdi-pencil"></i> Edit
                                                </a>
                                                <a href="index.php?delete=<?= $student['prime_id'] ?>" class="btn btn-sm btn-outline-danger" 
                                                   onclick="return confirm('Are you sure you want to delete this student record?')">
                                                    <i class="mdi mdi-delete"></i> Delete
                                                </a>
                                                <a href="id_card.php?prime_id=<?= $student['prime_id'] ?>" class="btn btn-sm btn-outline-info">
                                                    <i class="mdi mdi-card-account-details"></i> ID Card
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- PRIME ID Generator Modal -->
    <div class="modal fade" id="primeIdModal" tabindex="-1" aria-labelledby="primeIdModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="primeIdModalLabel"><i class="mdi mdi-auto-fix"></i> Generate PRIME ID</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <p>Click the button below to generate a unique PRIME ID</p>
                    <button type="button" class="btn btn-primary btn-lg" id="generatePrimeIdBtn">
                        <i class="mdi mdi-auto-fix"></i> Generate PRIME ID
                    </button>
                    <div class="modal-prime-id" id="generatedPrimeId"></div>
                    <div class="copy-success" id="copySuccess">
                        <i class="mdi mdi-check-circle"></i> PRIME ID copied to clipboard!
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-success" id="usePrimeIdBtn" disabled>Use This ID</button>
                </div>
            </div>
        </div>
    </div>
    
    <?php include 'includes/footer.php'; ?>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.1/build/qrcode.min.js"></script>
    <script>
        // PRIME ID Generation functionality
        document.addEventListener('DOMContentLoaded', function() {
            const generateBtn = document.getElementById('generatePrimeIdBtn');
            const useIdBtn = document.getElementById('usePrimeIdBtn');
            const primeIdField = document.getElementById('prime_id');
            const generatedPrimeId = document.getElementById('generatedPrimeId');
            const copySuccess = document.getElementById('copySuccess');
            const primeIdModal = new bootstrap.Modal(document.getElementById('primeIdModal'));
            
            generateBtn.addEventListener('click', function() {
                // AJAX request to generate a PRIME ID
                fetch('generate_prime_id.php')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            generatedPrimeId.textContent = data.prime_id;
                            useIdBtn.disabled = false;
                            
                            // Copy to clipboard automatically
                            navigator.clipboard.writeText(data.prime_id).then(() => {
                                copySuccess.style.display = 'block';
                                setTimeout(() => {
                                    primeIdField.value = data.prime_id;
                                    primeIdModal.hide();
                                    copySuccess.style.display = 'none';
                                }, 1500);
                            });
                        } else {
                            alert('Error generating PRIME ID: ' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('Error generating PRIME ID. Please try again.');
                    });
            });
            
            useIdBtn.addEventListener('click', function() {
                primeIdField.value = generatedPrimeId.textContent;
                primeIdModal.hide();
            });
        });
        
        // Form validation
        const form = document.getElementById('studentForm');
        if (form) {
            form.addEventListener('submit', function(e) {
                // Validate phone numbers
                const fatherPhone = document.getElementById('father_phone');
                const motherPhone = document.getElementById('mother_phone');
                
                if (fatherPhone.value && !/^\d{11}$/.test(fatherPhone.value)) {
                    e.preventDefault();
                    alert('Father\'s phone must be exactly 11 digits');
                    fatherPhone.focus();
                    return false;
                }
                
                if (motherPhone.value && !/^\d{11}$/.test(motherPhone.value)) {
                    e.preventDefault();
                    alert('Mother\'s phone must be exactly 11 digits');
                    motherPhone.focus();
                    return false;
                }
                
                return true;
            });
        }
        
        // Auto-format phone numbers
        const phoneInputs = document.querySelectorAll('input[type="tel"]');
        phoneInputs.forEach(input => {
            input.addEventListener('input', function(e) {
                this.value = this.value.replace(/\D/g, '').substring(0, 11);
            });
        });
    </script>
</body>
</html>