<?php
session_start();
include_once 'connect.php';

date_default_timezone_set('Asia/Karachi');

// 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') {
    // Sanitize inputs
    $emis_code = isset($_POST['emis_code']) ? trim($_POST['emis_code']) : '';
    $school_type_id = isset($_POST['school_type']) ? $_POST['school_type'] : '';
    $level_id = isset($_POST['level_name']) ? $_POST['level_name'] : '';
    $school_email = isset($_POST['school_email']) ? trim($_POST['school_email']) : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    $repeat_password = isset($_POST['repeat_password']) ? $_POST['repeat_password'] : '';

    // Validate EMIS Code (11 digits)
    if (empty($emis_code)) {
        $message = "Please enter EMIS code.";
    } elseif (!preg_match('/^\d{11}$/', $emis_code)) {
        $message = "EMIS code must be exactly 11 digits.";
    } elseif (empty($school_type_id)) {
        $message = "Please select school type.";
    } elseif (empty($level_id)) {
        $message = "Please select level name.";
    } elseif (empty($password) || empty($repeat_password)) {
        $message = "Please enter password in both fields.";
    } elseif ($password !== $repeat_password) {
        $message = "Passwords do not match.";
    } elseif (strlen($password) < 8) {
        $message = "Password must be at least 8 characters long.";
    } elseif (!preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/', $password)) {
        $message = "Password must contain at least one uppercase letter, one lowercase letter, and one number.";
    } elseif ($school_email !== '' && !filter_var($school_email, FILTER_VALIDATE_EMAIL)) {
        $message = "Invalid email address format.";
    } else {
        // Check if EMIS code already exists in registrations
        $check_stmt = $conn->prepare("SELECT emis_code FROM registrations WHERE emis_code = ?");
        $check_stmt->bind_param("s", $emis_code);
        $check_stmt->execute();
        $check_stmt->store_result();
        
        if ($check_stmt->num_rows > 0) {
            $message = "This EMIS code has already been registered.";
            $check_stmt->close();
        } else {
            $check_stmt->close();
            
            // Verify EMIS code against school_emis master table
            $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()) {
                // IMPORTANT: Close this statement before preparing new ones
                $stmt->close();
                
                // Validate selected type/level matches official records
                if ($school_type_id != $cate_id_db || $level_id != $level_id_db) {
                    $message = "School type or level doesn't match official records.";
                } else {
                    // Get descriptive names for email
                    $stmt_type = $conn->prepare("SELECT school_type FROM school_cate WHERE cate_id = ?");
                    $stmt_type->bind_param("i", $school_type_id);
                    $stmt_type->execute();
                    $stmt_type->bind_result($school_type_name);
                    $stmt_type->fetch();
                    $stmt_type->close();

                    $stmt_level = $conn->prepare("SELECT level_name FROM school_level WHERE level_id = ?");
                    $stmt_level->bind_param("i", $level_id);
                    $stmt_level->execute();
                    $stmt_level->bind_result($level_name_db);
                    $stmt_level->fetch();
                    $stmt_level->close();

                    // All validations passed - register
                    $hashed_password = password_hash($password, PASSWORD_BCRYPT);
                    
                    try {
                        $stmt = $conn->prepare("INSERT INTO registrations (emis_code, school_name, cate_id, level_id, school_email, password) VALUES (?, ?, ?, ?, ?, ?)");
                        $stmt->bind_param("ssssss", $emis_code, $school_name_db, $school_type_id, $level_id, $school_email, $hashed_password);
                        
                        if ($stmt->execute()) {
                            // ---------------- EMAIL CONFIGURATION (OFFICIAL DOMAIN) ----------------
                            $to_email   = 'mohsinbashirraja@dsisajk.net, wajidmuzaffar@dsisajk.net, amirhamzakhan@dsisajk.net, shirazahmad@dsisajk.net, kabirahmed@dsisajk.net';
                            $from_email = 'noreply@dsisajk.net';
                            $subject    = 'New School Registration Request';
                            
                            $email_body = "
A new school registration request has been submitted.
School Details:
------------------
EMIS Code       : $emis_code
School Name     : $school_name_db
School Type     : $school_type_name
Level           : $level_name_db
Email           : " . ($school_email ?: 'Not provided') . "
Status: Pending.... Waiting for Administrator Approval!
This is an automated message from the DSIS Registration System.
";

                            $headers = [];
                            $headers[] = "From: DSIS Registration System <$from_email>";
                            $headers[] = "Reply-To: $from_email";
                            $headers[] = "Return-Path: $from_email";
                            $headers[] = "MIME-Version: 1.0";
                            $headers[] = "Content-Type: text/plain; charset=UTF-8";
                            $headers[] = "X-Mailer: PHP/" . phpversion();

                            $mail_sent = mail($to_email, $subject, $email_body, implode("\r\n", $headers));
                            if (!$mail_sent) {
                                error_log('Registration email could not be sent to admin.');
                            }

                            $message = "School Registration submitted! School Account activation requires administrator approval.";
                            // Clear form on successful submission
                            $_POST = array();
                        } else {
                            $message = "Error: " . $stmt->error;
                        }
                        $stmt->close();
                    } catch (Exception $e) {
                        $message = "Error: " . $e->getMessage();
                    }
                }
            } else {
                $message = "Invalid EMIS code. Please verify and try again.";
                $stmt->close();
            }
        }
    }
}

// AJAX endpoint for school name lookup
if (isset($_GET['emis_code'])) {
    header('Content-Type: text/plain');
    $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 htmlspecialchars($school_name);
    } else {
        echo "School not found";
    }
    $stmt->close();
    exit();
}
?>
<!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>
<!-- Match Code 1 Libraries -->
<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">
<!-- Add jQuery UI for consistency with Code 1 -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<style>
/* Match Code 1 CSS Variables & Structure */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
:root {
    --primary: #3498db;
    --primary-dark: #2980b9;
    --secondary: #2c3e50;
    --light: #ecf0f1;
    --dark: #34495e;
    --success: #2ecc71;
    --warning: #f39c12;
    --danger: #e74c3c;
    --gray: #95a5a6;
    --light-gray: #f5f7fa;
    --border-radius: 8px;
    --box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    --transition: all 0.3s ease;
}
body {
    background-color: #f5f7fa;
    min-height: 100vh;
}
.home-btn {
    position: fixed;
    top: 20px;
    left: 20px;
    background-color: var(--primary);
    color: white;
    border: none;
    border-radius: 6px;
    padding: 10px 15px;
    font-size: 14px;
    cursor: pointer;
    transition: var(--transition);
    display: flex;
    align-items: center;
    gap: 5px;
    z-index: 10;
}
.home-btn:hover {
    background-color: var(--primary-dark);
}
.registration-container {
    background-color: white;
    border-radius: 10px;
    box-shadow: var(--box-shadow);
    overflow: hidden;
    height: 100%;
}
.registration-header {
    background: linear-gradient(135deg, var(--primary), var(--secondary));
    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;
    position: relative;
}
.form-control {
    width: 100%;
    padding: 12px 15px;
    border: 1px solid #ddd;
    border-radius: var(--border-radius);
    font-size: 16px;
    transition: var(--transition);
}
.form-control:focus {
    border-color: var(--primary);
    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: var(--gray);
    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: 14px 20px;
    border: none;
    border-radius: var(--border-radius);
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: var(--transition);
    display: inline-flex;
    align-items: center;
    justify-content: center;
}
.btn-primary {
    background: var(--primary);
    color: white;
}
.btn-primary:hover {
    background: var(--primary-dark);
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
}
.btn-secondary {
    background: var(--light-gray);
    color: var(--secondary);
    border: 1px solid #ddd;
}
.btn-secondary:hover {
    background: #eaeef2;
}
.btn-danger {
    background: var(--light-gray);
    color: var(--danger);
    border: 1px solid #ddd;
}
.btn-danger:hover {
    background: #fdecea;
}
.btn-group {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    gap: 10px;
}
::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);
}
/* Login link styling */
.login-link {
    text-align: center;
    font-size: 15px;
    color: var(--secondary);
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #eee;
}
.login-link a {
    color: var(--primary);
    text-decoration: none;
    font-weight: 500;
    transition: var(--transition);
}
.login-link a:hover {
    text-decoration: underline;
}
/* 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-group {
        flex-direction: column;
    }
    .btn {
        width: 100%;
        margin-bottom: 10px;
    }
    .form-control {
        font-size: 16px;
    }
}
</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.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 
                                maxlength="11" 
                                oninput="formatEMIS(this)"
                                value="<?php echo isset($_POST['emis_code']) ? htmlspecialchars($_POST['emis_code']) : ''; ?>">
                        </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; background-color: #f5f7fa; color: #2c3e50;">
                            <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>
                                <option value="" selected disabled hidden>Select School Type</option>
                                <?php
                                if ($cate_result) {
                                    $cate_result->data_seek(0);
                                    while ($row = $cate_result->fetch_assoc()): ?>
                                        <option value="<?= $row['cate_id'] ?>" 
                                            <?php echo (isset($_POST['school_type']) && $_POST['school_type'] == $row['cate_id']) ? 'selected' : ''; ?>>
                                            <?= htmlspecialchars($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>
                                <option value="" selected disabled hidden>Select Level Name</option>
                                <?php
                                if ($level_result) {
                                    $level_result->data_seek(0);
                                    while ($row = $level_result->fetch_assoc()): ?>
                                        <option value="<?= $row['level_id'] ?>" 
                                            <?php echo (isset($_POST['level_name']) && $_POST['level_name'] == $row['level_id']) ? 'selected' : ''; ?>>
                                            <?= htmlspecialchars($row['level_name']) ?>
                                        </option>
                                    <?php endwhile;
                                } ?>
                            </select>
                        </div>
                        <!-- School Email Address (Optional) -->
                        <div class="form-group">
                            <input type="email"
                                id="school_email"
                                name="school_email"
                                class="form-control"
                                placeholder="Enter School Email (Optional)"
                                pattern="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
                                title="Please enter a valid email address (e.g. name@example.com)"
                                value="<?php echo isset($_POST['school_email']) ? htmlspecialchars($_POST['school_email']) : ''; ?>">
                        </div>
                        <!-- Password -->
                        <div class="form-group">
                            <div class="input-group">
                                <input type="password" id="password" name="password" class="form-control"
                                    placeholder="Enter Password (Minimum 8 characters)" required>
                                <i class='bx bx-show toggle-password' onclick="togglePasswordVisibility('password')"></i>
                            </div>
                            <small style="color:red;">Must contain uppercase, lowercase letters and a number</small>
                        </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>
                                <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">
                                    <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()">
                                    <i class="fas fa-redo me-1"></i> Reset
                                </button>
                            </div>
                            <div class="col">
                                <button type="button" class="btn btn-danger w-100 py-2" onclick="cancelRegistration()">
                                    <i class="fas fa-times me-1"></i> Cancel
                                </button>
                            </div>
                        </div>
                        <!-- Login Link -->
                        <div class="login-link">
                            Already have a School Account? <a href="login.php">Login From Here</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add jQuery and jQuery UI -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<script>
function formatEMIS(input) {
    // Remove all non-digit characters
    let value = input.value.replace(/\D/g, '');
    // Ensure maximum length of 11 digits
    if (value.length > 11) {
        value = value.substring(0, 11);
    }
    // Update the input value
    input.value = value;
    // Fetch school name if length is 11
    if (value.length === 11) {
        fetchSchoolName(value);
    } else {
        document.getElementById('school_name_display').value = '';
        document.getElementById('school_name').value = '';
    }
}

function fetchSchoolName(emis_code) {
    if (!emis_code) 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;
                if (schoolName === "School not found") {
                    document.getElementById('school_name_display').style.color = 'var(--danger)';
                } else {
                    document.getElementById('school_name_display').style.color = '#2c3e50';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('school_name_display').value = 'Error fetching name';
            });
    }
}

function resetForm() {
    document.getElementById('registration_form').reset();
    document.getElementById('school_name_display').value = '';
    document.getElementById('school_name').value = '';
    document.getElementById('school_name_display').style.color = '#2c3e50';
}

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;
    }
    const school_name = document.getElementById('school_name').value;
    if (!school_name || school_name === "School not found") {
        alert('Invalid EMIS code. Please enter a valid 11-digit EMIS code.');
        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.length < 8) {
        alert('Password must be at least 8 characters long.');
        return false;
    }
    // Password strength validation
    const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
    if (!passwordRegex.test(password)) {
        alert('Password must contain at least one uppercase letter, one lowercase letter, and one number.');
        return false;
    }
    if (password !== repeat_password) {
        alert('Passwords do not match.');
        return false;
    }
    return true;
}

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>
<?php include 'visitor_counter.php'; ?>
<?php
// Close database connection at the very end
$conn->close();
?>