<?php
session_start();

// Check if the user is logged in by verifying the session variable
if (!isset($_SESSION['school_name']) || !isset($_SESSION['emis_code'])) {
    // Redirect to login page if the session is not set
    header("Location: login.php");
    exit();
}

// Retrieve the session variables
$school_name = $_SESSION['school_name'];
$emis_code = $_SESSION['emis_code'];
$cate_id = $_SESSION['cate_id'] ;        // Store school Category in session
$level_id = $_SESSION['level_id'];      // Store school Level in session
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Student Profile</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
   
<!--	//styles for Go Back To School Dashboard Button-->
	<style>
    .btn-custom {
        background: linear-gradient(45deg, #4a90e2, #9013fe);
        border: none;
        color: white;
        padding: 10px 20px;
        font-size: 16px;
        font-weight: bold;
        border-radius: 25px;
        transition: background 0.3s ease, transform 0.3s ease;
        box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
    }

    .btn-custom:hover {
        background: linear-gradient(45deg, #9013fe, #4a90e2);
        transform: translateY(-2px);
        box-shadow: 0px 6px 8px rgba(0, 0, 0, 0.15);
    }

    .btn-custom:focus {
        outline: none;
        box-shadow: 0px 0px 10px rgba(144, 19, 254, 0.5);
    }
</style>
	<style>
        .container {
            max-width: 800px;
            margin-top: 0px;
			margin-bottom: 50px;
        }
        .form-border {
            border: 2px solid #ddd;
            padding: 20px;
            border-radius: 10px;
            background-color: #f9f9f9;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: flex-start;
            flex-direction: row;
            gap: 20px;
        }
        .form-group {
            margin-bottom: 0.5rem;
        }
        .form-group1 {
            text-align: right;
            display: flex;
            flex-direction: column;
            align-items: flex-end;
        }
        #fileDisplayArea {
            width: 1.5in;
            height: 2.0in;
            border: 1px solid #ddd;
            overflow: hidden;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 10px;
            background-color: #f9f9f9;
        }
        #fileDisplayArea img {
            max-width: 100%;
            max-height: 100%;
        }
        .compact-form label {
            font-size: 0.9rem;
        }
        .compact-form input, .compact-form select, .compact-form button {
            font-size: 0.9rem;
        }
        .form-check-inline {
            margin-right: 10px;
        }
        .gender-group {
            display: flex;
            flex-direction: column;
        }
        .gender-options {
            display: flex;
            flex-direction: row;
            margin-top: 0.5rem;
        }
        .hidden {
            visibility: hidden;
            height: 0;
            overflow: hidden;
        }
        .error-message {
            color: red;
            font-size: 0.8rem;
        }
    </style>
    <script>
        function showImagePreview(input) {
            var fileInput = input;
            var fileDisplayArea = document.getElementById('fileDisplayArea');
            var file = fileInput.files[0];

            if (file) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    fileDisplayArea.innerHTML = "<img src='" + e.target.result + "' alt='Student Picture' />";
                };
                reader.readAsDataURL(file);
            } else {
                fileDisplayArea.innerHTML = "No Picture Selected";
            }
        }

	document.addEventListener("DOMContentLoaded", function() {
    var today = new Date().toISOString().split('T')[0];
    var dobInput = document.getElementById("stbirthday");
    var doaInput = document.getElementById("doadm");

    dobInput.setAttribute("max", today);
    doaInput.setAttribute("max", today);

    var timeoutId;

    dobInput.addEventListener("input", function() {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(function() {
            doaInput.setAttribute("min", dobInput.value);
            validateDates();
        }, 500);
    });

    doaInput.addEventListener("input", function() {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(function() {
            dobInput.setAttribute("max", doaInput.value);
            validateDates();
        }, 1000);
    });

    function validateDates() {
        var dob = new Date(dobInput.value);
        var doa = new Date(doaInput.value);

        if (dobInput.value && doaInput.value) {
            var age = doa.getFullYear() - dob.getFullYear();
            var monthDifference = doa.getMonth() - dob.getMonth();
            var dayDifference = doa.getDate() - dob.getDate();

            if (monthDifference < 0 || (monthDifference === 0 && dayDifference < 0)) {
                age--;
            }

            if (age < 4) {
                alert("You have entered incorrect Date of Birth or Date of Admission, or the Student is Underage.");
                dobInput.value = ""; // Resetting DOB to prompt user to enter a new date
                doaInput.value = ""; // Resetting DOA to prompt user to enter a new date
            }
        }
    }
		
});	
		$(document).ready(function() {
    $('#classadm').on('change', function() {
        var admittedClass = parseInt($(this).val());

        // Clear and repopulate the Present Class dropdown based on the selected Admitted Class
        $('#stclass').empty().append('<option value="">Select Class</option>');

        $('#classadm option').each(function() {
            var classId = parseInt($(this).val());
            if (classId >= admittedClass) {
                $('#stclass').append('<option value="' + classId + '">' + $(this).text() + '</option>');
            }
        });
    });
});
	
function validateNameInput(input) {
            // Allow only alphabets, hyphens, and spaces
    var value = input.value;
    var regex = /^[a-zA-Z\- ]+$/;
    if (!regex.test(value)) {
        input.value = value.replace(/[^a-zA-Z\- ]/g, '');
    }
	// Capitalize the first letter of each word
    input.value = input.value
        .toLowerCase()
        .replace(/(^|\s)\S/g, function(letter) {
            return letter.toUpperCase();
		 });
//        }).trim();
        }

        $(document).ready(function(){
            $('#stname, #stfname').on('input', function() {
                validateNameInput(this);
            });
		

            $('#stbfno').on('input', function() {
                var stbfno = $(this).val();
                var errorMsg = $('#cnic-error');
                
                // Allow only digits and limit to 13 digits
                $(this).val(stbfno.replace(/\D/g, '').substring(0, 13));
                
                if (stbfno.length < 13) {
                    errorMsg.text('CNIC must have 13 digits').show();
                } else {
                    errorMsg.hide();
                }
            }).on('blur', function(){
                var stbfno = $(this).val();
                var errorMsg = $('#cnic-error');

                // Check if the CNIC has exactly 13 digits
                if (stbfno.length < 13) {
                    errorMsg.text('CNIC must have 13 digits').show();
                    $('#stbfno').focus();
                    return;
                }

                // Make an AJAX request to check if the number already exists in the database
                $.ajax({
                    type: 'POST',
                    url: 'checkFormB.php',
                    data: { stbfno: stbfno },
                    success: function(response) {
                        if (response === 'exists') {
                            errorMsg.text('Form B already registered').show();
                            $('#stbfno').val('').focus(); // Clear the input and move the cursor back to the CNIC field
                        } else {
                            errorMsg.hide();
                        }
                    }
                });
            });

            $('#stmobno').on('input', function() {
                var stmobno = $(this).val();
                var errorMsg = $('#mobile-error');
                
                // Allow only digits and limit to 11 digits
                $(this).val(stmobno.replace(/\D/g, '').substring(0, 11));
                
                if (stmobno.length < 11) {
                    errorMsg.text('Mobile number must have 11 digits').show();
                } else {
                    errorMsg.hide();
                }
            }).on('blur', function(){
                var stmobno = $(this).val();
                var errorMsg = $('#mobile-error');

                // Check if the mobile number has exactly 11 digits
                if (stmobno.length < 11) {
                    errorMsg.text('Mobile number must have 11 digits').show();
                    $('#stmobno').focus();
                } else {
                    errorMsg.hide();
                }
            });

            $('#stclass').on('change', function() {
                var selectedClass = $(this).val();
                if (selectedClass && parseInt(selectedClass) > 12) {
                    $('#stgroup').removeClass('hidden');
                } else {
                    $('#stgroup').addClass('hidden');
                }
            });

            $('#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>');
                        }
                    });
                } 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').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>');
                        }
                    });
                } else {
                    $('#constituency').html('<option value="">Select Tehsil First</option>');
                    $('#union_councils').html('<option value="">Select Constituency First</option>');
                }
            });

            $('#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);
                        }
                    });
                } else {
                    $('#union_councils').html('<option value="">Select Constituency First...</option>');
                }
            });
			
		function validateForm() {
                var isValid = true;

                // Check if all required fields are filled
                document.querySelectorAll("input[required], select[required]").forEach(function(element) {
                    if (!element.value) {
                        isValid = false;
                    }
                });

                // Enable or disable the submit button based on validation
                document.getElementById("submitButton").disabled = !isValid;
            }

            // Add event listeners to all inputs and selects
            document.querySelectorAll("input[required], select[required]").forEach(function(element) {
                element.addEventListener("input", validateForm);
                element.addEventListener("change", validateForm);
            });	
        });
    </script>
</head>
<body>
	<br>
<div class="col-sm-12 text-left">
    <button type="button" class="btn btn-custom" onclick="window.location.href='dashboard_school.php'">
        Go Back To School Dashboard
    </button>
</div>
	
<div class="container">
    <div class="form-border">
        <div class="form-content">
            <h1 class="text-center"><strong>Student Profile</strong></h1>
            <form action="save_student_data.php" method="post" enctype="multipart/form-data" class="compact-form">
                <div class="form-group1">
                    <div id="fileDisplayArea">No Picture Selected
                        <!-- Image will be displayed here -->
                    </div>
                    <input id="stpic" name="stpic" type="file" required onchange="showImagePreview(this);">
                </div>
                <div class="row row-cols-2">
                    <div class="col form-group">
                        <label for="stname" class="col-form-label">Student Name</label>
                        <input type="text" class="form-control" id="stname" name="stname" oninput="validateNameInput(this);" required>
                    </div>
                    <div class="col form-group">
                        <label for="stfname" class="col-form-label">Father Name</label>
                        <input type="text" class="form-control" id="stfname" name="stfname" oninput="validateNameInput(this);" required>
                    </div>
                    <div class="col form-group">
                        <div class="gender-group">
                            <label for="stgender" class="col-form-label">Gender</label>
                            <div id="stgender" class="gender-options">
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="stge" id="male" value="Male" required>
                                    <label class="form-check-label" for="male">Male</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="stge" id="female" value="Female" required>
                                    <label class="form-check-label" for="female">Female</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="stge" id="other" value="Other" required>
                                    <label class="form-check-label" for="other">Other</label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col form-group">
						<label for="stbirthday" class="col-form-label">Date of Birth</label>
						<input type="date" class="form-control" id="stbirthday" name="stbirthday" required>
					</div>
                    <div class="col form-group">
                        <label for="stbfno" class="col-form-label">Form B No.</label>
                        <input type="text" class="form-control" id="stbfno" name="stbfno" required>
						<span id="cnic-error" class="error-message"></span>
                    </div>
					
					<div class="col form-group">
                        <label for="strel" class="col-form-label">Religion</label>
                        <select class="form-control" id="strel" name="strel" required>
                            <option value="" disabled selected>Select Religion</option>
                            <option value="Islam">Islam</option>
                            <option value="Christianity">Christianity</option>
                            <option value="Hinduism">Hinduism</option>
                            <option value="Other">Other</option>
                        </select>
                    </div>
					
                    <div class="col form-group">
                        <label for="stmobno" class="col-form-label">Parent's Mobile No.</label>
                        <input type="text" class="form-control" id="stmobno" name="stmobno" required>
						<span id="mobile-error" class="error-message"></span>
                    </div>
                 <div class="col form-group">
    <label for="classadm" class="col-form-label">Class Admitted</label>
    <select class="form-control" id="classadm" name="classadm" required>
        <option value="">Select Class</option>
        <?php
        // Connection to Database
        include_once 'connect.php';

        // Fetch class data
        $sql = "SELECT * FROM class ORDER BY class_id ASC";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            // Output data of each row
            while($row = $result->fetch_assoc()) {
                echo '<option value="' . $row['class_id'] . '">' . $row['class_name'] . '</option>';
            }
        } else {
            echo '<option value="">No Classes Available</option>';
        }
        ?>
    </select>
</div>
					<div class="col form-group">
						<label for="doadm" class="col-form-label">Date of Admission</label>
						<input type="date" class="form-control" id="doadm" name="doadm" required>
					</div>
					<div class="col form-group">
                        <label for="admno" class="col-form-label">Admission No.</label>
                        <input type="text" class="form-control" id="admno" name="admno" required>
                    </div>			
			
					<div class="col form-group">
    <label for="stclass" class="col-form-label">Present Class</label>
    <select class="form-control" id="stclass" name="stclass" required>
        <option value="">Select Class</option>
        <?php
        // Fetch class data again for Present Class
        $sql = "SELECT * FROM class ORDER BY class_id ASC";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            // Output data of each row
            while($row = $result->fetch_assoc()) {
                echo '<option value="' . $row['class_id'] . '">' . $row['class_name'] . '</option>';
            }
        } else {
            echo '<option value="">No Classes Available</option>';
        }
        ?>
    </select>
</div>

					<div class="col form-group">
                        <label for="stcsec" class="col-form-label">Section</label>
                        <select class="form-control" id="stcsec" name="stcsec" required>
                            <option value="">Select Section</option>
                            <option value="A">A</option>
                            <option value="B">B</option>
                            <option value="C">C</option>
                            <option value="D">D</option>
							<option value="E">E</option>
                        </select>
                    </div>
                    <div class="col form-group">
                        <label for="stcno" class="col-form-label">Class Roll No.</label>
                        <input type="number" class="form-control" id="stcno" name="stcno" value="1" min="1" required >
                    </div>
							
						<div id="stgroup" class="col form-group hidden">
                        <label for="stgroup" class="col-form-label">Group</label>
                        <select id="stgroup" name="stgroup" class="form-control">
                        <option value=""disabled selected>Select Group</option>
                    <?php
					// Connection to Database
					include_once 'connect.php';
					
                    // Fetch class data
                    $sql = "SELECT group_name FROM subject_group";
                    $result = $conn->query($sql);

                    if ($result->num_rows > 0) {
                        // Output data of each row
                        while($row = $result->fetch_assoc()) {
                            echo '<option value="' . $row["group_name"] . '">' . $row["group_name"] . '</option>';
                        }
                    } else {
                        echo '<option value="">No Groups Available</option>';
                    }
                    ?>
                </select>
            </div>
					
                    <div class="col form-group">
                        <label for="stvillage" class="col-form-label">Village</label>
                        <input type="text" class="form-control" id="stvillage" name="stvillage">
                    </div>
                    <div class="col form-group">
                        <label for="stpo" class="col-form-label">Post Office</label>
                        <input type="text" class="form-control" id="stpo" name="stpo" required>
                    </div>
					
                  <div class="col form-group">
                        <label for="district" class="col-form-label">District</label>
                        <select class="form-control" id="district" name="districts_dropdown" required>
                            <option value="">Select one District...</option>
                            <?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()) {
                                    echo '<option value="' . $row['district_id'] . '">' . $row['district_name'] . '</option>';
                                }
                            } else {
                                echo '<option value="">District Not Available</option>';
                            }
							
							// Connection to Database Closed Here
                            $conn->close();
                            ?>
                        </select>
                    </div>
                    <div class="col form-group">
                        <label for="tehsil" class="col-form-label">Tehsil</label>
                        <select class="form-control" id="tehsil" name="tehsil_dropdown" required>
                            <option value="">Select District First...</option>
                        </select>
                    </div>
                    <div class="col form-group">
                        <label for="constituency" class="col-form-label">Constituency</label>
                        <select class="form-control" id="constituency" name="constituency_dropdown" required>
                            <option value="">Select Tehsil First...</option>
                        </select>
                    </div>
                    <div class="col form-group">
                        <label for="union_councils" class="col-form-label">U.C/Ward</label>
                        <select class="form-control" id="union_councils" name="union_councils_dropdown" required>
                            <option value="">Select Constituency First...</option>
                        </select>
                    </div>
                </div>
				<br>
               <!-- The form tag should wrap around all the form elements including the submit button -->
<form action="save_student_data.php" method="POST">
    <div class="form-group row">
        <div class="col-sm-12 text-center">
            <!-- Hidden field to pass EMIS code -->
            <input type="hidden" name="emis_code" value="<?php echo htmlspecialchars($emis_code); ?>">

            <!-- Submit button -->
            <button type="submit" class="btn btn-custom" id="submitButton" disabled>Save Profile</button>
        </div>
    </div>
</form>
            </form>
        </div>
    </div>
</div>
</body>
</html>