<?php

if (!isset($_SESSION)) {
    session_start();
}



if (!isset($_SESSION['neetuser'])) {
    session_destroy();
    echo("<script LANGUAGE='JavaScript'>
    window.location.href='https://www.keralaneetmodelexam.in/login.php';
    </script>");
}


?>


<?php
require_once('lib/dbclass.php');
$key = 567;
function xor_encode($input, $key)
{
    $encoded = '';
    for ($i = 0; $i < strlen($input); $i++) {
        $encoded .= chr(ord($input[$i]) ^ $key);
    }

    return $encoded;
}
function xor_decode($input, $key)
{
    return xor_encode($input, $key); // XOR is symmetric
}


$course  = ['' => 'Select', 1 => '12th student', '12th completed', 'Repeater', 'Rerepeater', 'Other'];
$state   = ['' => 'Select','Kerala' => 'Kerala','Tamilnadu' => 'Tamilnadu'];
$referal = get_option('tbl_referal', 'name');

// Get districts for all states (pre-load all possible options)
$districts_Kerala = [
    'Thiruvananthapuram', 'Kollam', 'Pathanamthitta', 'Alappuzha', 'Kottayam', 'Idukki',
    'Ernakulam', 'Thrissur', 'Palakkad', 'Malappuram', 'Kozhikode', 'Wayanad', 'Kannur', 'Kasaragod',
];

$districts_Tamilnadu = [
    'Ariyalur', 'Chennai', 'Coimbatore', 'Cuddalore', 'Dharmapuri', 'Dindigul', 'Erode', 'Kanchipuram', 'Kanyakumari',
    'Karur', 'Krishnagiri', 'Madurai', 'Nagapattinam', 'Namakkal', 'Perambalur', 'Pudukkottai', 'Ramanathapuram', 'Salem',
    'Sivagangai', 'Tenkasi', 'Thanjavur', 'Theni', 'Thoothukudi', 'Tiruchirappalli', 'Tirunelveli', 'Tiruppur', 'Vellore',
    'Villupuram', 'Virudhunagar', 'Chengalpattu', 'Kallakurichi', 'Tiruvallur', 'Tirupattur', 'Ranipet', 'Ariyalur', 'Nilgiris',
    'Tiruchirapalli', 'Kanchipuram',
];
$id = 0;

if ($_GET['id']) {
    $encoded_id = $_GET['id'];  // Get the encoded id from the URL
    $id         = xor_decode($encoded_id, $key);  // Decode the id


    if ($id < 0) {
        session_destroy();
        echo("<script LANGUAGE='JavaScript'>
    window.location.href='https://www.keralaneetmodelexam.in/login.php';
    </script>");
    }


    $data = findQuery("select * from  tbl_candidates where id=$id");

    $courseid         = $data[0]['course'];
    $stateid          = $data[0]['state'];
    $referalid        = $data[0]['referal'];
    $selecteddistrict = $data[0]['district'];

    if ($stateid == 'Kerala') {
        $districts = [
         'Thiruvananthapuram', 'Kollam', 'Pathanamthitta', 'Alappuzha', 'Kottayam', 'Idukki',
         'Ernakulam', 'Thrissur', 'Palakkad', 'Malappuram', 'Kozhikode', 'Wayanad', 'Kannur', 'Kasaragod',
];
    } else {
        $districts = [
        'Ariyalur', 'Chennai', 'Coimbatore', 'Cuddalore', 'Dharmapuri', 'Dindigul', 'Erode', 'Kanchipuram', 'Kanyakumari',
        'Karur', 'Krishnagiri', 'Madurai', 'Nagapattinam', 'Namakkal', 'Perambalur', 'Pudukkottai', 'Ramanathapuram', 'Salem',
        'Sivagangai', 'Tenkasi', 'Thanjavur', 'Theni', 'Thoothukudi', 'Tiruchirappalli', 'Tirunelveli', 'Tiruppur', 'Vellore',
        'Villupuram', 'Virudhunagar', 'Chengalpattu', 'Kallakurichi', 'Tiruvallur', 'Tirupattur', 'Ranipet', 'Ariyalur', 'Nilgiris',
        'Tiruchirapalli', 'Kanchipuram',
];
    }
}


?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kerala NEET Model Exam</title>
    <link rel="shortcut icon" href="logo.png" type="image/x-icon" sizes="16x16">
    <link rel="stylesheet" href="style.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script>
    <script src="cropperjs/dist/cropper.js"></script>
    <link rel="stylesheet" href="cropperjs/dist/cropper.css">

    <style>
        img {
            display: block;
            max-width: 100%;
        }

        .preview {
            overflow: hidden;
            width: 160px;
            height: 160px;
            margin: 10px;
            border: 1px solid red;
        }

        .reg_container {
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
        }

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

        .modal-content {
            max-width: 100%;
        }

        .modal-body img {
            max-width: 100%;
        }

        @media (max-width: 768px) {
            .reg_container {
                padding: 10px;
            }

            .modal-content {
                width: 90%;
            }
        }

        @media (max-width: 576px) {
            .form-group {
                margin-bottom: 10px;
            }

            .modal-content {
                width: 95%;
            }
        }
    </style>
</head>

<body>
    <div class="reg_container">
        <h4 class="text-center mb-4">ALL KERALA NEET MODEL EXAM REGISTRATION 2025</h4>
        <p class="indi text-center">"<span>*</span>" Indicates required fields</p>

        <form action="save.php" method="post" enctype="multipart/form-data">
            <div class="row">
                <div class="col-12">
                    <label for="name">Full Name<span>*</span></label><br>
                    <input type="text" id="name" name="name" maxlength="250" class="form-control" required value="<?php echo $data[0]['name'] ?>">
                </div>

                <div class="col-12 col-md-6">
                    <label for="mobile">Mobile Number<span>*</span></label><br>
                    <input type="text" id="mobile" name="mobile" pattern="^[6-9]\d{9}$" class="form-control" required placeholder="Enter 10-digit mobile number" value="<?php echo $data[0]['mobile'] ?>">
                </div>

                <div class="col-12 col-md-6">
                    <label>Course <span>*</span></label><br>
                    <select name="course" required id="course" class="form-control">
                        <?php echo array_options($course, $courseid); ?>
                    </select>
                </div>

                <div class="col-12">
                    <label for="school">Institution/ School<span>*</span></label><br>
                    <input type="text" id="school" name="school" maxlength="250" class="form-control" required value="<?php echo $data[0]['school'] ?>">
                </div>

                <div class="col-12 col-md-6">
                    <label for="Country">Country<span>*</span></label><br>
                    <input type="text" id="Country" name="Country" value="India" class="form-control" disabled required maxlength="200">
                </div>

                <div class="col-12 col-md-6">
                    <label>State <span>*</span></label><br>
                    <select name="state" required id="state" class="form-control" onchange="updateDistricts()">
                        <?php echo array_options($state, $stateid); ?>
                    </select>
                </div>

                <div class="col-12">
                    <label>District <span>*</span></label><br>
                    <select name="district" required id="district" class="form-control">
                       
                      <?php
                        if ($id > 0) {
                            foreach ($districts as $row) : ?>
                                                        <option value="<?php echo $row; ?>" <?php echo ($selecteddistrict == $row) ? 'selected' : ''; ?>>
                                                            <?php echo $row; ?>
                                                        </option>
                                                    <?php endforeach;
                        } else {
                            ?>
                         <option value="">Select</option>
                         <?php
                        }
?>
                    </select>
                </div>

                <div class="col-12">
                    <label for="neetscore">Previous Year NEET Score</label><br>
                    <input type="text" id="neetscore" name="neetscore" maxlength="200" class="form-control"   value="<?php echo $data[0]['neetscore'] ?>">
                </div>

                <div class="col-12">
                    <label>Referral Code <span>*</span></label><br>
                    <select name="referal" required id="referal" class="form-control">
                        <?php echo array_options($referal, $referalid); ?>
                    </select>
                </div>

                <div class="col-12">
    <label class="form-label" for="imageInput">Photo Upload</label>
    <input type="file" id="imageInput" name="image" class="form-control" autocomplete="off"  />
    <span style="color:grey;font-size:12px">*Only Upload (JPEG, JPG, PNG) format file</span>
    
    <!-- Display current photo if available -->
    <?php if (!empty($data[0]['photo'])): ?>
        <div id="current-photo" class="mt-3">
            <label>Current Photo</label><br>
            <img src="uploads/<?php echo $data[0]['photo']; ?>" alt="Current Photo" style="max-width: 200px; max-height: 200px;">
        </div>
    <?php endif; ?>

    <!-- Hidden input for cropped image -->
    <input type="hidden" id="croppedImage" name="croppedImage">
</div>
                
               
               
 <input type="hidden" id="id" name="id" value="<?php echo $data[0]['id'] ?>">
                <div class="col-6">
                    <button type="submit" class="btn btn-primary w-100">Submit</button>
                </div>
            </div>
        </form>
    </div>

    <!-- Modal for Image Crop -->
<head>
    <style>
        /* Custom modal size */
        .modal-dialog {
            max-width: 400px;  /* Set custom width */
        }

        /* Make the image inside the modal scale responsively */
        .modal-body {
            text-align: center; /* Center the image */
        }

        .modal-body img {
            max-width: 100%;  /* Make sure image is responsive and scales with the modal size */
            max-height: 300px;  /* Limit the height of the image */
            width: auto;  /* Maintain the aspect ratio */
            height: auto;
        }

        /* Optionally, you can also add a border or other styles to the image */
        .img-container {
            width: 100%;
            overflow: hidden;
            text-align: center;
        }
    </style>
</head>

<body>
    <!-- Modal Structure -->
    <div class="modal" id="modal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Crop Image</h5>
                </div>
                <div class="modal-body">
                    <div class="img-container">
                        <img id="image" src="" alt="Image to crop">
                    </div>
                     <div class="col-md-4">
                                        <div class="preview"></div>
                                    </div>
                </div>
                <div class="modal-footer d-flex justify-content-start">
                    <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal" onclick="clearFileInput()">Cancel</button>
                    <button type="button" class="btn btn-primary btn-sm" id="crop">Crop</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Include the necessary JS files (for Bootstrap, Cropper, etc.) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="cropperjs/dist/cropper.js"></script>
    <link rel="stylesheet" href="cropperjs/dist/cropper.css">
</body>




    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="sweetalert.js"></script>

    <script>
        function clearFileInput() {
            document.getElementById('imageInput').value = '';
        }

        // Initialize modal with custom options to prevent closing on outside click
$(document).ready(function() {
    // Modal behavior on open
    $('#modal').modal({
        backdrop: 'static',  // Disables closing the modal when clicking outside
        keyboard: false      // Disables closing the modal when pressing the escape key
    });

    // Handling file input change event
    $("body").on("change", "#imageInput", function(e) {
    var files = e.target.files;
    var file = files[0];

    // Check if the file is of type JPEG, JPG, or PNG
    var fileType = file.type;
    if (fileType != 'image/jpeg' && fileType != 'image/png') {
        swal({
            title: "Alert",
            text: "Please upload a JPEG or PNG image.",
            icon: "error",
        });
        $("#imageInput").val('');  // Clear file input
        return;
    }

    // Check if the file size is greater than 1 MB
    if (file.size > 1024 * 1024) {
        swal({
            title: "Alert",
            text: "File size must be less than 1 MB.",
            icon: "error",
        });
        $("#imageInput").val('');  // Clear file input
        return;
    }

    var done = function(url) {
        image.src = url;
        $('#modal').modal('show');  // Open modal
    };

    // Load the image to the modal if file is valid
    if (URL) {
        done(URL.createObjectURL(file));
    } else if (FileReader) {
        var reader = new FileReader();
        reader.onload = function(e) {
            done(reader.result);
        };
        reader.readAsDataURL(file);
    }
});

    // Initialize the cropper when modal is shown
    var cropper;
    var image = document.getElementById('image');
    $('#modal').on('shown.bs.modal', function() {
        cropper = new Cropper(image, {
            aspectRatio: 3.5 / 4.5, // Aspect ratio of the image to crop
            viewMode: 3, // Set to 3 for more control over the image
            preview: '.preview' // Preview the cropped image in the preview box
        });
    });

    // Destroy the cropper when modal is hidden
    $('#modal').on('hidden.bs.modal', function() {
        cropper.destroy();
        cropper = null;
    });

    // Handle the crop button click
    $('#crop').click(function() {
        var canvas;
        canvas = cropper.getCroppedCanvas({
            width: 400,
            height: 533
        });

        canvas.toBlob(function(blob) {
            var reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onloadend = function() {
                var base64data = reader.result;
                $('#croppedImage').val(base64data); // Set the cropped image to the hidden input
                $('#modal').modal('hide'); // Hide the modal after cropping
            };
        });
    });
});

        const districtsKerala = <?php echo json_encode($districts_Kerala); ?>;
        const districtsTamilnadu = <?php echo json_encode($districts_Tamilnadu); ?>;

        function updateDistricts() {
            const state = document.getElementById('state').value;
            const districtSelect = document.getElementById('district');

            districtSelect.innerHTML = '<option value="">Select</option>';

            let districts = [];
            if (state == 'Kerala') {
                districts = districtsKerala;
            } else if (state == 'Tamilnadu') {
                districts = districtsTamilnadu;
            }

            districts.forEach(function(district) {
                const option = document.createElement('option');
                option.value = district;
                option.textContent = district;
                districtSelect.appendChild(option);
            });
        }
    </script>

    <script src="script.js"></script>
</body>
</html>
