<?php
include_once 'connect.php';

// Fetch school types
$cate_result = $conn->query("SELECT cate_id, school_type FROM school_cate");

// Fetch level names
$level_result = $conn->query("SELECT level_id, level_name FROM school_level");

$message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $emis_code = isset($_POST['emis_code']) ? $_POST['emis_code'] : '';
    $school_name = isset($_POST['school_name']) ? $_POST['school_name'] : '';
    $cate_id = isset($_POST['school_type']) ? $_POST['school_type'] : '';
    $level_id = isset($_POST['level_name']) ? $_POST['level_name'] : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    $repeat_password = isset($_POST['repeat_password']) ? $_POST['repeat_password'] : '';

    if (empty($cate_id)) {
        $message = "Please select school type.";
    } elseif (empty($level_id)) {
        $message = "Please select level name.";
    } elseif ($password !== $repeat_password) {
        $message = "Passwords do not match.";
    } else {
        // Check if EMIS code exists in registrations
        $stmt = $conn->prepare("SELECT emis_code FROM registrations WHERE emis_code = ?");
        $stmt->bind_param("s", $emis_code);
        $stmt->execute();
        
        if ($stmt->fetch()) {
            $message = "This EMIS code has already been registered.";
            $stmt->close();
        } else {
            $stmt->close();
            
            // Verify EMIS code against school_emis
            $stmt = $conn->prepare("SELECT school_name, cate_id, level_id FROM school_emis WHERE emis_code = ?");
            $stmt->bind_param("s", $emis_code);
            $stmt->execute();
            $stmt->bind_result($school_name_db, $cate_id_db, $level_id_db);
            
            if ($stmt->fetch()) {
                if ($cate_id != $cate_id_db || $level_id != $level_id_db) {
                    $message = "School type or level doesn't match official records.";
                } else {
                    // All validations passed - register
                    $hashed_password = password_hash($password, PASSWORD_BCRYPT);
                    $stmt->close();
                    
                    $stmt = $conn->prepare("INSERT INTO registrations (emis_code, school_name, cate_id, level_id, password) VALUES (?, ?, ?, ?, ?)");
                    $stmt->bind_param("sssss", $emis_code, $school_name_db, $cate_id, $level_id, $hashed_password);
                    
                    if ($stmt->execute()) {
                        $message = "Registration submitted! Account activation requires administrator approval.";
                    } else {
                        $message = "Error: " . $stmt->error;
                    }
                }
            } else {
                $message = "Invalid EMIS code. Please verify and try again.";
            }
            $stmt->close();
        }
    }
}

// AJAX endpoint for school name lookup
if (isset($_GET['emis_code'])) {
    $emis_code = $_GET['emis_code'];
    $stmt = $conn->prepare("SELECT school_name FROM school_emis WHERE emis_code = ?");
    $stmt->bind_param("s", $emis_code);
    $stmt->execute();
    $stmt->bind_result($school_name);
    if ($stmt->fetch()) {
        echo $school_name;
    } else {
        echo "School not found";
    }
    $stmt->close();
    $conn->close();
    exit();
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>School Registration</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-LN+7fdVzj6u52u30Kp6M/trliBMCMKTyK833zpbD+pXdCLuTusPj697FH4R/5mcr" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js" integrity="sha384-ndDqU0Gzau9qJ1lfW4pNLlhNTkCfHzAVBReH9diLvGRem5+R9g2FzA8ZGN954O5Q" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/css/lightbox.min.css">
    <link href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet">
    
    <style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    
    body {
        background-color: #f5f7fa;
        min-height: 100vh;
    }
    
    .home-btn {
        position: fixed;
        top: 20px;
        left: 20px;
        background-color: #3498db;
        color: white;
        border: none;
        border-radius: 6px;
        padding: 10px 15px;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.3s;
        display: flex;
        align-items: center;
        gap: 5px;
        z-index: 10;
    }
    
    .home-btn:hover {
        background-color: #2980b9;
    }
    
    .registration-container {
        background-color: white;
        border-radius: 10px;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        height: 100%;
    }
    
    .registration-header {
        background: linear-gradient(135deg, #3498db, #2c3e50);
        color: white;
        padding: 10px;
        text-align: center;
    }
    
    .registration-header h1 {
        font-size: 46px;
        font-weight: 600;
        margin-bottom: 1px;
    }
    
    .registration-body {
        padding: 20px;
    }
    
    .form-group {
        margin-bottom: 1.5rem;
    }
    
    .form-control {
        width: 100%;
        padding: 12px 15px;
        border: 1px solid #ddd;
        border-radius: 6px;
        font-size: 16px;
        transition: all 0.3s;
    }
    
    .form-control:focus {
        border-color: #3498db;
        outline: none;
        box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
    }
    
    .input-group {
        position: relative;
        display: flex;
        align-items: center;
    }
    
    .input-group .form-control {
        flex: 1;
    }
    
    .toggle-password {
        position: absolute;
        right: 12px;
        cursor: pointer;
        color: #7f8c8d;
        font-size: 18px;
    }
    
    select.form-control {
        appearance: none;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%23333' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E");
        background-repeat: no-repeat;
        background-position: right 12px center;
        background-size: 16px;
    }
    
    .btn {
        display: inline-block;
        padding: 12px 20px;
        border: none;
        border-radius: 6px;
        font-size: 16px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s;
        text-align: center;
    }
    
    .btn-primary {
        background-color: #3498db;
        color: white;
    }
    
    .btn-primary:hover {
        background-color: #2980b9;
    }
    
    .btn-secondary {
        background-color: #95a5a6;
        color: white;
    }
    
    .btn-secondary:hover {
        background-color: #7f8c8d;
    }
    
    .btn-group {
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
    }
    
    ::placeholder {
        color: #6c757d;
        opacity: 1;
    }
    
    .image-container {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        padding: 40px;
        transition: all 0.3s ease;
    }
    
    .image-container img {
        max-width: 100%;
        max-height: 85vh;
        width: auto;
        object-fit: contain;
        border-radius: 12px;
        box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
        transition: all 0.4s ease;
    }
    
    .image-container:hover img {
        transform: scale(1.03);
    }
    
    .image-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(67, 97, 238, 0);
        border-radius: 12px;
        transition: all 0.3s ease;
    }
    
    .image-container:hover .image-overlay {
        background: rgba(67, 97, 238, 0.1);
    }
    
    .image-container:active {
        transform: scale(0.98);
    }
    
    /* Watermark background */
    body::before {
        content: "";
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-image: url('images/dsis.png');
        background-repeat: no-repeat;
        background-position: center;
        background-size: 100%;
        opacity: 0.08;
        z-index: -1;
        pointer-events: none;
    }
    
    @media (max-width: 992px) {
        .image-container {
            display: none;
        }
        
        body::before {
            background-size: 100%;
            opacity: 0.05;
        }
        
        .btn {
            width: 100%;
            margin-bottom: 10px;
            margin-right: 0;
        }
    }
</style>

</head>
<body>
	<div class="floating-decoration decoration-1"></div>
    <div class="floating-decoration decoration-2"></div>
    
	<button type="button" class="home-btn" onclick="window.location.href='index.php'">
        <i class="fas fa-arrow-left"></i> Back to Home
    </button>

    <div class="container-fluid h-100">
        <div class="row h-100 align-items-center">
        
            <!-- Left Column (Image) -->
            <div class="col-lg-6 d-flex justify-content-center align-items-center">
                <div class="image-container" onclick="window.location.href='register_test.php'" style="cursor: pointer;">
                    <img src="images/dsis.png" alt="DSIS System" class="img-fluid" style="max-height: 85vh; width: auto;">
                    <div class="image-overlay"></div>
                </div>
            </div>
            
            <!-- Right Column (Registration Form) -->
            <div class="col-lg-6 py-4">
                <div class="registration-container mx-auto" style="max-width: 500px;">
                    <div class="registration-header">
                        <h1><strong style="text-decoration: underline;">School Registration</strong></h1>
                        <h4>District School's Information System AJ&K </h4>
                    </div>
                    
                    <div class="registration-body">
                        <form id="registration_form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" onsubmit="return validateForm()">
                            <!-- EMIS Code -->
                            <div class="form-group">
                                <input type="text" id="emis_code" name="emis_code" class="form-control" 
                                       placeholder="Enter 11 Digits School EMIS Code" required oninput="fetchSchoolName()" 
                                       maxlength="11" onkeydown="restrictInput(event)" 
                                       onpaste="return handlePaste(event)" tabindex="1">
                            </div>
                            
                             <!-- School Name Display -->
                            <div class="form-group">
                                <input type="text" id="school_name_display" class="form-control" 
                                       placeholder="School Name will be Fetched Automatically" readonly
                                       style="font-weight: bold;">
                                <input type="hidden" id="school_name" name="school_name">
                            </div>

                            <!-- School Type -->
                            <div class="form-group">
                                <select id="school_type" name="school_type" class="form-control" required tabindex="2">
                                    <option value="" selected disabled hidden>Select School Type</option>
                                    <?php 
                                    $cate_result->data_seek(0);
                                    while ($row = $cate_result->fetch_assoc()): ?>
                                        <option value="<?= $row['cate_id'] ?>"><?= $row['school_type'] ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>

                            <!-- Level Name -->
                            <div class="form-group">
                                <select id="level_name" name="level_name" class="form-control" required tabindex="3">
                                    <option value="" selected disabled hidden>Select Level Name</option>
                                    <?php 
                                    $level_result->data_seek(0);
                                    while ($row = $level_result->fetch_assoc()): ?>
                                        <option value="<?= $row['level_id'] ?>"><?= $row['level_name'] ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>

                            <!-- Password -->
                            <div class="form-group">
                                <div class="input-group">
                                    <input type="password" id="password" name="password" class="form-control" 
                                           placeholder="Enter Password" required tabindex="4">
                                    <i class='bx bx-show toggle-password' onclick="togglePasswordVisibility('password')"></i>
                                </div>
                            </div>

                            <!-- Confirm Password -->
                            <div class="form-group">
                                <div class="input-group">
                                    <input type="password" id="repeat_password" name="repeat_password" 
                                           class="form-control" placeholder="Confirm Password" required tabindex="5">
                                    <i class='bx bx-show toggle-password' onclick="togglePasswordVisibility('repeat_password')"></i>
                                </div>
                            </div>

                            <!-- Form Buttons -->
                            <div class="btn-group row g-2">
                                <div class="col">
                                    <button type="submit" class="btn btn-primary w-100 py-2" tabindex="6">
                                        <i class="fas fa-user-plus me-1"></i> Register
                                    </button>
                                </div>
                                <div class="col">
                                    <button type="button" class="btn btn-secondary w-100 py-2" onclick="resetForm()" tabindex="7">
                                        <i class="fas fa-redo me-1"></i> Reset
                                    </button>
                                </div>
                                <div class="col">
                                    <button type="button" class="btn btn-secondary w-100 py-2" onclick="cancelRegistration()" tabindex="8">
                                        <i class="fas fa-times me-1"></i> Cancel
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function fetchSchoolName() {
            const emis_code = document.getElementById('emis_code').value;
            if (emis_code.length === 11 && /^\d+$/.test(emis_code)) {
                fetch(`<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>?emis_code=${emis_code}`)
                    .then(response => response.text())
                    .then(schoolName => {
                        document.getElementById('school_name_display').value = schoolName;
                        document.getElementById('school_name').value = schoolName;
                    })
                    .catch(error => console.error('Error:', error));
            } else {
                document.getElementById('school_name_display').value = '';
                document.getElementById('school_name').value = '';
            }
        }

        function resetForm() {
            document.getElementById('registration_form').reset();
            document.getElementById('school_name_display').value = '';
            document.getElementById('school_name').value = '';
        }

        function cancelRegistration() {
            if (confirm('Are you sure you want to cancel registration?')) {
                window.location.href = 'index.php';
            }
        }

        function validateForm() {
            const emis_code = document.getElementById('emis_code').value;
            if (emis_code.length !== 11 || !/^\d+$/.test(emis_code)) {
                alert('EMIS Code must be exactly 11 digits.');
                return false;
            }
            
            if (!document.getElementById('school_type').value) {
                alert('Please select school type.');
                return false;
            }
            
            if (!document.getElementById('level_name').value) {
                alert('Please select level name.');
                return false;
            }
            
            const password = document.getElementById('password').value;
            const repeat_password = document.getElementById('repeat_password').value;
            
            if (password !== repeat_password) {
                alert('Passwords do not match.');
                return false;
            }
            
            return true;
        }

        function restrictInput(event) {
            const allowedKeys = ['Delete', 'Backspace', 'Tab', 'ArrowLeft', 'ArrowRight', 'Home', 'End'];
            if (!((event.key >= '0' && event.key <= '9') || allowedKeys.includes(event.key))) {
                event.preventDefault();
            }
        }

        function handlePaste(event) {
            const clipboardData = event.clipboardData || window.clipboardData;
            const pastedData = clipboardData.getData('Text');
            if (!/^\d+$/.test(pastedData)) {
                event.preventDefault();
            }
        }

        function togglePasswordVisibility(fieldId) {
            const passwordField = document.getElementById(fieldId);
            const icon = passwordField.nextElementSibling;
            
            if (passwordField.type === 'password') {
                passwordField.type = 'text';
                icon.classList.replace('bx-show', 'bx-hide');
            } else {
                passwordField.type = 'password';
                icon.classList.replace('bx-hide', 'bx-show');
            }
        }
        
        // Show alert message if exists
        window.onload = function() {
            <?php if (!empty($message)): ?>
                alert('<?php echo addslashes($message); ?>');
            <?php endif; ?>
        };
    </script>
</body>
</html>