<?php
// edit_student.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([]));
}

$students = json_decode(file_get_contents('data/students.json'), true);
$student = null;

// Get student data for editing
if (isset($_GET['prime_id'])) {
    $primeId = $_GET['prime_id'];
    foreach ($students as $s) {
        if ($s['prime_id'] === $primeId) {
            $student = $s;
            break;
        }
    }
}

// Handle form submission for updates
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $updatedData = [
        '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' => $_POST['registration_date']
    ];

    // Handle photo upload if a new one is provided
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = 'uploads/';
        $fileExtension = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
        $fileName = $updatedData['prime_id'] . '.' . $fileExtension;
        $uploadPath = $uploadDir . $fileName;
        
        if (move_uploaded_file($_FILES['photo']['tmp_name'], $uploadPath)) {
            $updatedData['photo'] = $fileName;
        }
    } else {
        // Keep the existing photo if no new one is uploaded
        $updatedData['photo'] = $student['photo'] ?? '';
    }

    // Update the student in the array
    foreach ($students as &$s) {
        if ($s['prime_id'] === $updatedData['prime_id']) {
            $s = $updatedData;
            break;
        }
    }

    // Save to JSON
    file_put_contents('data/students.json', json_encode($students, JSON_PRETTY_PRINT));
    
    $_SESSION['success'] = "Student record updated successfully!";
    header('Location: index.php');
    exit;
}

// If student not found, redirect
if (!$student) {
    $_SESSION['error'] = "Student record not found!";
    header('Location: index.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Student Record</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">
</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-warning text-dark">
                        <h3 class="card-title"><i class="mdi mdi-account-edit"></i> Edit Student Record</h3>
                    </div>
                    <div class="card-body">
                        <form method="POST" enctype="multipart/form-data" id="studentForm">
                            <input type="hidden" name="registration_date" value="<?= $student['registration_date'] ?>">
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <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" 
                                               value="<?= $student['prime_id'] ?>" required readonly>
                                    </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" 
                                               value="<?= $student['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" 
                                               value="<?= $student['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" <?= $student['sex'] == 'Male' ? 'selected' : '' ?>>Male</option>
                                            <option value="Female" <?= $student['sex'] == 'Female' ? 'selected' : '' ?>>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" 
                                               value="<?= $student['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" <?= $student['religion'] == 'Christianity' ? 'selected' : '' ?>>Christianity</option>
                                            <option value="Islam" <?= $student['religion'] == 'Islam' ? 'selected' : '' ?>>Islam</option>
                                            <option value="Other" <?= $student['religion'] == 'Other' ? 'selected' : '' ?>>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" 
                                               value="<?= $student['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" 
                                               value="<?= $student['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>
                                            <?php
                                            $classes = ['BG1', 'BG2', 'KG', 'Nur1', 'Nur2', 'Pry1', 'Pry2', 'Pry3', 'Pry4', 'Pry5', 'Pry6', 
                                                       'JSS1', 'JSS2', 'JSS3', 'SSS1', 'SSS2', 'SSS3'];
                                            foreach ($classes as $class): 
                                            ?>
                                                <option value="<?= $class ?>" <?= $student['previous_class'] == $class ? 'selected' : '' ?>>
                                                    <?= $class ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </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>
                                            <?php foreach ($classes as $class): ?>
                                                <option value="<?= $class ?>" <?= $student['proposed_class'] == $class ? 'selected' : '' ?>>
                                                    <?= $class ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </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" 
                                               value="<?= $student['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" 
                                               value="<?= $student['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" 
                                       value="<?= $student['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><?= $student['home_address'] ?></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" 
                                       value="<?= $student['previous_school'] ?>" required>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="photo" class="form-label">Photo</label>
                                        <input type="file" class="form-control" id="photo" name="photo" accept="image/*">
                                        <?php if (isset($student['photo']) && file_exists('uploads/' . $student['photo'])): ?>
                                            <div class="mt-2">
                                                <img src="uploads/<?= $student['photo'] ?>" alt="Current Photo" class="img-thumbnail" style="max-height: 150px;">
                                                <small class="form-text text-muted">Current photo</small>
                                            </div>
                                        <?php endif; ?>
                                    </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" <?= $student['status'] == 'qualified' ? 'selected' : '' ?>>Qualified</option>
                                            <option value="disqualified" <?= $student['status'] == 'disqualified' ? 'selected' : '' ?>>Disqualified</option>
                                            <option value="probation" <?= $student['status'] == 'probation' ? 'selected' : '' ?>>Probation</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                <a href="index.php" class="btn btn-secondary me-md-2">Cancel</a>
                                <button type="submit" class="btn btn-primary">Update Student Record</button>
                            </div>
                        </form>
                    </div>
                </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="js/script.js"></script>
</body>
</html>