<?php 
// student_registration_step1.php
session_start();
require_once 'db.php';
// Match floors.php auth check
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}
$pageTitle = 'Students Registration - Step 1';
require_once 'config.php'; // (must NOT echo anything)
include_once '_header.php';
include_once '_sidebar.php';
?>
<main class="container-fluid" id="appContent">
    <h5 class="mb-4">Student Registration - Step 1</h5>
    <div class="form-header">
        <h2>Student Details Form</h2>
    </div>
    <!-- Step Indicator -->

    <!-- Student Information Form -->
    <form id="studentRegistrationForm">
        <div class="row g-3 mb-4">
            <div class="col-md-6">
                <label for="fullName" class="form-label">Full Name of Student <span class="text-danger">*</span></label>
                <input type="text" class="form-control" id="fullName" name="fullName" required>
            </div>

            <div class="col-md-6">
                <label for="admissionNumber" class="form-label">Admission Number / Student ID <span class="text-danger">*</span></label>
                <input type="text" class="form-control" id="admissionNumber" name="admissionNumber" required>
            </div>

            <div class="col-md-6">
                <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 class="col-md-6">
                <label for="gender" class="form-label">Gender <span class="text-danger">*</span></label>
                <select class="form-select" id="gender" name="gender" required>
                    <option value="">Select Gender</option>
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                    <option value="Other">Other</option>
                </select>
            </div>

            <div class="col-md-6">
                <label for="bloodGroup" class="form-label">Blood Group</label>
                <input type="text" class="form-control" id="bloodGroup" name="bloodGroup" placeholder="e.g., A+, O-">
            </div>

            <div class="col-md-6">
                <label for="religion" class="form-label">Religion</label>
                <select class="form-control" id="religion" name="religion">
                    <option value="">Select Religion</option>
                    <option value="Hinduism">Hinduism</option>
                    <option value="Muslim">Muslim</option>
                    <option value="Christianity">Christianity</option>
                    <option value="Buddhism">Buddhism</option>
                    <option value="Sikhism">Sikhism</option>
                    <option value="Prefer not to say">Prefer Not To Say</option>
                    <option value="Other">Other</option>
                </select>
            </div>

            <div class="col-md-6">
                <label for="category" class="form-label">Category <span class="text-danger">*</span></label>
                <select class="form-select" id="category" name="category" required>
                    <option value="">Select Category</option>
                    <option value="General">General</option>
                    <option value="SC">SC</option>
                    <option value="ST">ST</option>
                    <option value="OBC">OBC</option>
                    <option value="Others">Others</option>
                </select>
            </div>

            <div class="col-md-6">
                <label for="aadharNumber" class="form-label">Aadhar Number (if available)</label>
                <input type="text" class="form-control" id="aadharNumber" name="aadharNumber" maxlength="12" pattern="[0-9]{12}" title="Aadhar number must be 12 digits">
            </div>

            <!-- Preferred Language -->
            <div class="col-md-6">
                <label for="preferredLanguage" class="form-label">Medium</label>
                <select class="form-select" id="preferredLanguage" name="preferredLanguage">
                    <option value="">-- Select --</option>
                    <option value="Hindi">Hindi</option>
                    <option value="English">English</option>
                </select>
            </div>

            <!-- Hobbies -->
            <div class="col-md-6">
                <label for="hobbies" class="form-label">Hobbies</label>
                <input type="text" class="form-control" id="hobbies" name="hobbies" placeholder="Enter hobbies">
            </div>

            <!-- Achievement -->
            <div class="col-md-6">
                <label for="achievementType" class="form-label">Achievement</label>
                <select class="form-select" id="achievementType" name="achievementType">
                    <option value="">-- Select --</option>
                    <option value="Academic">Academic</option>
                    <option value="Award">Award</option>
                    <option value="Sport">Sport</option>
                </select>
            </div>
            <!-- Siblings -->
            <div class="col-md-6">
                <label for="siblings" class="form-label">Siblings</label>
                <select class="form-select" id="siblings" name="siblings" onchange="toggleSiblingDetails()">
                    <option value="">-- Select --</option>
                    <option value="No">No</option>
                    <option value="Yes">Yes</option>
                </select>
            </div>

            <div class="col-md-12" id="siblingDetailsBox" style="display:none;">
                <label for="siblingDetails" class="form-label">Sibling Details</label>
                <textarea class="form-control" id="siblingDetails" name="siblingDetails" rows="3" placeholder="Enter sibling details"></textarea>
            </div>

            <!-- School Dropdown -->
            <div class="col-md-6">
                <label for="school" class="form-label">School <span class="text-danger">*</span></label>
                <select class="form-select" id="school" name="school" required>
                    <option value="">Select School</option>
                    <?php
                    $schoolQuery = $conn->query("SELECT school_name FROM schools ORDER BY school_name ASC");
                    if ($schoolQuery && $schoolQuery->num_rows > 0) {
                        while ($row = $schoolQuery->fetch_assoc()) {
                            echo '<option value="' . htmlspecialchars($row['school_name']) . '">' . htmlspecialchars($row['school_name']) . '</option>';
                        }
                    }
                    ?>
                </select>
            </div>

            <!-- Class / Grade -->
            <div class="col-md-6">
                <label for="classGrade" class="form-label">Class / Grade <span class="text-danger">*</span></label>
                <select class="form-select" id="classGrade" name="classGrade" required>
                    <option value="">-- Select Class --</option>
                    <?php
                    $classQuery = $conn->query("SELECT class_name FROM classes ORDER BY class_name ASC");
                    if ($classQuery && $classQuery->num_rows > 0) {
                        while ($row = $classQuery->fetch_assoc()) {
                            echo '<option value="' . htmlspecialchars($row['class_name']) . '">' . htmlspecialchars($row['class_name']) . '</option>';
                        }
                    }
                    ?>
                </select>
            </div>

            <div class="col-md-6">
                <label for="section" class="form-label">Section (if applicable)</label>
                <input type="text" class="form-control" id="section" name="section">
            </div>
              
            <div class="col-md-6">
                <label for="section" class="form-label">Reference</label>
                <input type="text" class="form-control" id="reference" name="reference">
            </div>

            <!-- Stationary -->
            <div class="col-md-12">
                <label for="stationary" class="form-label">Stationary (Details)</label>
                <textarea class="form-control" id="stationary" name="stationary" rows="3" placeholder="List stationary items or notes..."></textarea>
            </div>
            
        </div>

        <div class="d-flex justify-content-end">
            <button type="submit" class="btn btn-primary">Next Step <i class="fas fa-arrow-right ms-2"></i></button>
        </div>
    </form>

    <div id="generatedIdDisplay" class="generated-id-box alert alert-success mt-4" style="display:none;">
        <strong>Registration Successful!</strong>
        <div>Your Unique Registration Number: <span id="uniqueRegNumber" class="fw-bold"></span></div>
    </div>
</main>

<?php include_once 'footer.php'; ?>

<script>
function toggleSiblingDetails() {
    const val = document.getElementById('siblings').value;
    document.getElementById('siblingDetailsBox').style.display = (val === 'Yes') ? 'block' : 'none';
}

// Handle form submission with JSON
document.getElementById('studentRegistrationForm').addEventListener('submit', function (e) {
    e.preventDefault();
    const form = this;
    const formData = new FormData(form);

    fetch('student_registration_step1_action.php', {
        method: 'POST',
        body: formData,
        credentials: 'same-origin'
    })
    .then(res => res.text())
    .then(text => {
        console.debug('Raw response:', text);
        let data;
        try { data = JSON.parse(text); } 
        catch (err) {
            alert('Invalid response: ' + text);
            return;
        }

        if (data.status === 'success') {
            document.getElementById('uniqueRegNumber').textContent = data.uniqueId;
            document.getElementById('generatedIdDisplay').style.display = 'block';
            form.reset();
            window.location.href = 'student_registration_step2.php?reg=' + encodeURIComponent(data.uniqueId);
        } else {
            alert('Error: ' + (data.message || 'Unknown error'));
        }
    })
    .catch(err => {
        console.error(err);
        alert('Network error. Please try again.');
    });
});
</script>
