<?php
session_start();

// Database connection
include_once 'connect.php';

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Collect form data
    $school_name = $conn->real_escape_string($_POST['school_name']);
    $school_gender = $conn->real_escape_string($_POST['school_gender']);
    $school_type = $conn->real_escape_string($_POST['school_type']);
    $emis_code = $conn->real_escape_string($_POST['emis_code']);
    $ddo_code = $conn->real_escape_string($_POST['ddo_code']);
    $village = $conn->real_escape_string($_POST['village']);
    $post_office = $conn->real_escape_string($_POST['post_office']);
    $district = $conn->real_escape_string($_POST['districts_dropdown']);
    $tehsil = $conn->real_escape_string($_POST['tehsil_dropdown'] ?? '');
    $constituency = $conn->real_escape_string($_POST['constituency_dropdown'] ?? '');
    $union_council = $conn->real_escape_string($_POST['union_councils_dropdown'] ?? '');
    $contact_no = $conn->real_escape_string($_POST['contact_no']);
    $level = $conn->real_escape_string($_POST['level']);
    $email = $conn->real_escape_string($_POST['email']);
    $locality = $conn->real_escape_string($_POST['locality']);
    $distance = $conn->real_escape_string($_POST['distance']);
    $zone = $conn->real_escape_string($_POST['zone']);
    $status = $conn->real_escape_string($_POST['status']);
    
    // Insert into database
    $sql = "INSERT INTO school_profile (
        school_name, school_gender, school_type, emis_code, ddo_code, 
        village, post_office, district_id, tehsil_id, constituency_id, 
        union_council_id, contact_no, level, email, locality, 
        distance, zone, status, created_at
    ) VALUES (
        '$school_name', '$school_gender', '$school_type', '$emis_code', '$ddo_code',
        '$village', '$post_office', '$district', '$tehsil', '$constituency',
        '$union_council', '$contact_no', '$level', '$email', '$locality',
        '$distance', '$zone', '$status', NOW()
    )";
    
    if ($conn->query($sql) === TRUE) {
        $success_message = "School registered successfully!";
        // Clear form after successful submission
        $_POST = array();
    } else {
        $error_message = "Error: " . $conn->error;
    }
    
    $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 Profile Registration</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            padding: 25px;
            background: linear-gradient(135deg, #2c3e50, #4a6491);
            color: white;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }

        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }

        .header p {
            opacity: 0.9;
            font-size: 16px;
        }

        .form-container {
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            margin-bottom: 30px;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group.full-width {
            grid-column: 1 / -1;
        }

        label {
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
            font-size: 14px;
        }

        input[type="text"],
        input[type="email"],
        select {
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 15px;
            transition: all 0.3s ease;
            background-color: white;
            width: 100%;
        }

        input[type="text"]:focus,
        input[type="email"]:focus,
        select:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }

        select {
            cursor: pointer;
            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.14L2.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 15px center;
            background-size: 12px;
            padding-right: 40px;
            appearance: none;
        }

        . ::after {
            content: " *";
            color: #e74c3c;
        }

        .form-section {
            margin-bottom: 30px;
            padding-bottom: 25px;
            border-bottom: 1px solid #eee;
        }

        .form-section:last-child {
            border-bottom: none;
        }

        .section-title {
            font-size: 18px;
            color: #2c3e50;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #3498db;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .section-title i {
            color: #3498db;
        }

        .submit-btn {
            display: block;
            width: 200px;
            margin: 30px auto 0;
            padding: 15px 30px;
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-align: center;
        }

        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(52, 152, 219, 0.3);
            background: linear-gradient(135deg, #2980b9, #1f6399);
        }

        .submit-btn:active {
            transform: translateY(0);
        }

        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
            vertical-align: middle;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .helper-text {
            font-size: 12px;
            color: #7f8c8d;
            margin-top: 5px;
        }

        .alert {
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
            text-align: center;
            font-weight: 500;
        }

        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .dropdown-container {
            position: relative;
        }

        @media (max-width: 768px) {
            .form-grid {
                grid-template-columns: 1fr;

                gap: 15px;
            }
            
            .form-container {
                padding: 20px;
            }
            
            .header h1 {
                font-size: 24px;
            }
            
            input[type="text"],
            input[type="email"],
            select {
                padding: 10px 12px;
                font-size: 14px;
            }
            
            .submit-btn {
                width: 100%;
                max-width: 300px;
            }
        }

        @media (max-width: 480px) {
            .container {
                padding: 10px;
            }
            
            .form-container {
                padding: 15px;
            }
            
            .header {
                padding: 15px;
            }
        }

        .form-control {
            margin-bottom: 15px;
        }

        .school-info {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
            border-left: 4px solid #3498db;
        }

        .school-info h3 {
            color: #2c3e50;
            margin-bottom: 10px;
            font-size: 16px;
        }

        .school-info p {
            color: #666;
            font-size: 14px;
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>

<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-school"></i> School Profile Registration</h1>
            <p>Register a new school in the system</p>
        </div>

        <?php if(isset($success_message)): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
            </div>
        <?php endif; ?>

        <?php if(isset($error_message)): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i> <?php echo $error_message; ?>
            </div>
        <?php endif; ?>

        <div class="form-container">
            <form method="POST" action="" id="schoolForm">
                <div class="school-info">
                    <h3><i class="fas fa-info-circle"></i> School Information</h3>
                    <p>Fill in all   fields to register the school profile. All fields marked with * are  .</p>
                </div>

                <div class="form-section">
                    <h3 class="section-title"><i class="fas fa-info-circle"></i> Basic Information</h3>
                    <div class="form-grid">
                        <div class="form-group full-width">
                            <label for="school_name" class=" ">School Name</label>
                            <input id="school_name" name="school_name" type="text"   
                                   placeholder="Enter official school name" 
                                   value="<?php echo htmlspecialchars($_POST['school_name'] ?? ''); ?>">
                            <div class="helper-text">Enter the complete official name of the school</div>
                        </div>

                        <div class="form-group">
                            <label for="school_gender" class=" ">Gender</label>
                            <select id="school_gender" name="school_gender"  >
                                <option value="">Select Gender...</option>
                                <option value="Male" <?php echo ($_POST['school_gender'] ?? '') == 'Male' ? 'selected' : ''; ?>>Male</option>
                                <option value="Female" <?php echo ($_POST['school_gender'] ?? '') == 'Female' ? 'selected' : ''; ?>>Female</option>
                                <option value="Co-Education" <?php echo ($_POST['school_gender'] ?? '') == 'Co-Education' ? 'selected' : ''; ?>>Co-Education</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="school_type" class=" ">School Type</label>
                            <select id="school_type" name="school_type"  >
                                <option value="">Select Type...</option>
                                <option value="Government" <?php echo ($_POST['school_type'] ?? '') == 'Government' ? 'selected' : ''; ?>>Government</option>
                                <option value="Semi Government" <?php echo ($_POST['school_type'] ?? '') == 'Semi Government' ? 'selected' : ''; ?>>Semi Government</option>
                                <option value="Private" <?php echo ($_POST['school_type'] ?? '') == 'Private' ? 'selected' : ''; ?>>Private</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="level" class=" ">Education Level</label>
                            <select id="level" name="level"  >
                                <option value="">Select Level...</option>
                                <option value="Masjid School" <?php echo ($_POST['level'] ?? '') == 'Masjid School' ? 'selected' : ''; ?>>Masjid School</option>
                                <option value="Primary" <?php echo ($_POST['level'] ?? '') == 'Primary' ? 'selected' : ''; ?>>Primary</option>
                                <option value="Middle" <?php echo ($_POST['level'] ?? '') == 'Middle' ? 'selected' : ''; ?>>Middle</option>
                                <option value="High" <?php echo ($_POST['level'] ?? '') == 'High' ? 'selected' : ''; ?>>High</option>
                                <option value="Higher Secondary" <?php echo ($_POST['level'] ?? '') == 'Higher Secondary' ? 'selected' : ''; ?>>Higher Secondary</option>
                                <option value="Inter College" <?php echo ($_POST['level'] ?? '') == 'Inter College' ? 'selected' : ''; ?>>Inter College</option>
                                <option value="Degree College" <?php echo ($_POST['level'] ?? '') == 'Degree College' ? 'selected' : ''; ?>>Degree College</option>
                                <option value="Elementary College" <?php echo ($_POST['level'] ?? '') == 'Elementary College' ? 'selected' : ''; ?>>Elementary College</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <h3 class="section-title"><i class="fas fa-id-card"></i> Official Codes</h3>
                    <div class="form-grid">
                        <div class="form-group">
                            <label for="emis_code" class=" ">EMIS Code</label>
                            <input id="emis_code" name="emis_code" type="text"   
                                   placeholder="Enter EMIS Code" pattern="[A-Za-z0-9]{6,12}"
                                   value="<?php echo htmlspecialchars($_POST['emis_code'] ?? ''); ?>">
                            <div class="helper-text">6-12 characters, letters and numbers only</div>
                        </div>

                        <div class="form-group">
                            <label for="ddo_code" class=" ">DDO Code</label>
                            <input id="ddo_code" name="ddo_code" type="text"   
                                   placeholder="Enter DDO Code" pattern="[A-Za-z0-9]{4,10}"
                                   value="<?php echo htmlspecialchars($_POST['ddo_code'] ?? ''); ?>">
                            <div class="helper-text">4-10 characters, letters and numbers only</div>
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <h3 class="section-title"><i class="fas fa-map-marker-alt"></i> Location Information</h3>
                    <div class="form-grid">
                        <div class="form-group">
                            <label for="village" class=" ">Village/Town</label>
                            <input id="village" name="village" type="text"   
                                   placeholder="Enter village/town name"
                                   value="<?php echo htmlspecialchars($_POST['village'] ?? ''); ?>">
                        </div>

                        <div class="form-group">
                            <label for="post_office" class=" ">Post Office</label>
                            <input id="post_office" name="post_office" type="text"   
                                   placeholder="Enter post office"
                                   value="<?php echo htmlspecialchars($_POST['post_office'] ?? ''); ?>">
                        </div>

                        <div class="form-group">
                            <label for="locality" class=" ">Locality</label>
                            <select id="locality" name="locality"  >
                                <option value="">Select Locality...</option>
                                <option value="Rural" <?php echo ($_POST['locality'] ?? '') == 'Rural' ? 'selected' : ''; ?>>Rural</option>
                                <option value="Urban" <?php echo ($_POST['locality'] ?? '') == 'Urban' ? 'selected' : ''; ?>>Urban</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="distance" class=" ">Distance from Main Road (km)</label>
                            <input id="distance" name="distance" type="text"   
                                   placeholder="Enter distance in kilometers" pattern="[0-9.]*"
                                   value="<?php echo htmlspecialchars($_POST['distance'] ?? ''); ?>">
                            <div class="helper-text">Enter distance in kilometers (e.g., 2.5)</div>
                        </div>

                        <div class="form-group">
                            <label for="zone" class=" ">Zone</label>
                            <select id="zone" name="zone"  >
                                <option value="">Select Zone...</option>
                                <option value="Winter Station" <?php echo ($_POST['zone'] ?? '') == 'Winter Station' ? 'selected' : ''; ?>>Winter Station</option>
                                <option value="Summer Station" <?php echo ($_POST['zone'] ?? '') == 'Summer Station' ? 'selected' : ''; ?>>Summer Station</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <h3 class="section-title"><i class="fas fa-globe"></i> Administrative Information</h3>
                    <div class="form-grid">
                        <div class="form-group">
                            <label for="district" class=" ">District</label>
                            <div class="dropdown-container">
                                <select id="district" name="districts_dropdown"  >
                                    <option value="">Select District...</option>
                                    <?php
                                    include_once 'connect.php';
                                    $query = "SELECT * FROM districts WHERE status = 1 ORDER BY district_name ASC";
                                    $result = $conn->query($query);
                                    if ($result->num_rows > 0) {
                                        while ($row = $result->fetch_assoc()) {
                                            $selected = ($_POST['districts_dropdown'] ?? '') == $row['district_id'] ? 'selected' : '';
                                            echo '<option value="' . $row['district_id'] . '" ' . $selected . '>' . $row['district_name'] . '</option>';
                                        }
                                    } else {
                                        echo '<option value="">District Not Available</option>';
                                    }
                                    $conn->close();
                                    ?>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="tehsil">Tehsil</label>
                            <div class="dropdown-container">
                                <select id="tehsil" name="tehsil_dropdown">
                                    <option value="">Select District First...</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="constituency">Constituency</label>
                            <div class="dropdown-container">
                                <select id="constituency" name="constituency_dropdown">
                                    <option value="">Select Tehsil First...</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="union_councils">Union Council</label>
                            <div class="dropdown-container">
                                <select id="union_councils" name="union_councils_dropdown">
                                    <option value="">Select Constituency First...</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <h3 class="section-title"><i class="fas fa-address-book"></i> Contact Information</h3>
                    <div class="form-grid">
                        <div class="form-group">
                            <label for="contact_no" class=" ">Phone Number</label>
                            <input id="contact_no" name="contact_no" type="text"   
                                   placeholder="Enter head phone number" pattern="[0-9+]{10,15}"
                                   value="<?php echo htmlspecialchars($_POST['contact_no'] ?? ''); ?>">
                            <div class="helper-text">Format: +923001234567 or 03001234567</div>
                        </div>

                        <div class="form-group">
                            <label for="email" class=" ">Email Address</label>
                            <input id="email" name="email" type="email"   
                                   placeholder="Enter school email address"
                                   value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
                            <div class="helper-text">We'll send confirmation to this email</div>
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <h3 class="section-title"><i class="fas fa-cog"></i> Status Information</h3>
                    <div class="form-grid">
                        <div class="form-group">
                            <label for="status" class=" ">School Status</label>
                            <select id="status" name="status"  >
                                <option value="">Select Status...</option>
                                <option value="Active" <?php echo ($_POST['status'] ?? '') == 'Active' ? 'selected' : ''; ?>>Active</option>
                                <option value="Closed" <?php echo ($_POST['status'] ?? '') == 'Closed' ? 'selected' : ''; ?>>Closed</option>
                                <option value="Under Construction" <?php echo ($_POST['status'] ?? '') == 'Under Construction' ? 'selected' : ''; ?>>Under Construction</option>
                                <option value="Temporary Closed" <?php echo ($_POST['status'] ?? '') == 'Temporary Closed' ? 'selected' : ''; ?>>Temporary Closed</option>
                            </select>
                        </div>
                    </div>
                </div>

                <button type="submit" class="submit-btn" id="submitBtn">
                    <span id="btnText"><i class="fas fa-save"></i> Register School</span>
                    <span id="btnLoading" style="display: none;">
                        <span class="loading-spinner"></span> Processing...
                    </span>
                </button>
            </form>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            // Form validation
            $('#schoolForm').on('submit', function(e) {
                let isValid = true;
                
                // Clear previous error styling
                $('input[ ], select[ ]').css('border-color', '#e0e0e0');
                
                // Basic validation
                $('input[ ], select[ ]').each(function() {
                    if (!$(this).val()) {
                        isValid = false;
                        $(this).css('border-color', '#e74c3c');
                    }
                });
                
                // Pattern validation
                $('#emis_code, #ddo_code, #contact_no').each(function() {
                    const pattern = new RegExp($(this).attr('pattern'));
                    const value = $(this).val();
                    if (value && !pattern.test(value)) {
                        isValid = false;
                        $(this).css('border-color', '#e74c3c');
                    }
                });
                
                // Email validation
                const email = $('#email').val();
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (email && !emailRegex.test(email)) {
                    isValid = false;
                    $('#email').css('border-color', '#e74c3c');
                }
                
                if (!isValid) {
                    e.preventDefault();
                    alert('Please fill all   fields correctly.');
                    return false;
                }
                
                // Show loading state
                $('#btnText').hide();
                $('#btnLoading').show();
                $('#submitBtn').prop('disabled', true);
            });

            // District change handler
            $('#district').on('change', function() {
                var districtID = $(this).val();
                if (districtID) {
                    $.ajax({
                        type: 'POST',
                        url: 'ajaxData.php',
                        data: {district_id: districtID},
                        success: function(html) {
                            $('#tehsil').html(html);
                            $('#constituency').html('<option value="">Select Tehsil First...</option>');
                            $('#union_councils').html('<option value="">Select Constituency First...</option>');
                        },
                        error: function() {
                            $('#tehsil').html('<option value="">Error loading data</option>');
                        }
                    });
                } else {
                    $('#tehsil').html('<option value="">Select District First...</option>');
                    $('#constituency').html('<option value="">Select Tehsil First...</option>');
                    $('#union_councils').html('<option value="">Select Constituency First...</option>');
                }
            });

            // Tehsil change handler
            $('#tehsil').on('change', function() {
                var tehsilID = $(this).val();
                if (tehsilID) {
                    $.ajax({
                        type: 'POST',
                        url: 'ajaxData.php',
                        data: {tehsil_id: tehsilID},
                        success: function(html) {
                            $('#constituency').html(html);
                            $('#union_councils').html('<option value="">Select Constituency First...</option>');
                        },
                        error: function() {
                            $('#constituency').html('<option value="">Error loading data</option>');
                        }
                    });
                } else {
                    $('#constituency').html('<option value="">Select Tehsil First...</option>');
                    $('#union_councils').html('<option value="">Select Constituency First...</option>');
                }
            });

            // Constituency change handler
            $('#constituency').on('change', function() {
                var consID = $(this).val();
                if (consID) {
                    $.ajax({
                        type: 'POST',
                        url: 'ajaxData.php',
                        data: {cons_id: consID},
                        success: function(html) {
                            $('#union_councils').html(html);
                        },
                        error: function() {
                            $('#union_councils').html('<option value="">Error loading data</option>');
                        }
                    });
                } else {
                    $('#union_councils').html('<option value="">Select Constituency First...</option>');
                }
            });

            // Phone number formatting
            $('#contact_no').on('input', function() {
                let phone = $(this).val().replace(/\D/g, '');
                if (phone.length > 0 && !phone.startsWith('+')) {
                    if (phone.length <= 10) {
                        phone = '+92' + phone;
                    }
                }
                $(this).val(phone);
            });

            // Real-time validation feedback
            $('input[pattern]').on('input', function() {
                const pattern = new RegExp($(this).attr('pattern'));
                const value = $(this).val();
                
                if (value === '') {
                    $(this).css('border-color', '#e0e0e0');
                } else if (pattern.test(value)) {
                    $(this).css('border-color', '#2ecc71');
                } else {
                    $(this).css('border-color', '#e74c3c');
                }
            });
        });
    </script>
</body>
</html>