<?php include 'dbclass/dbclass.php';

// Fetch Panchayath data
$query          = 'SELECT * FROM panchayath';
$panchayathData = findQuery($query);
$query2         = 'SELECT * FROM ward';
$wardData       = findQuery($query2);

// Check if ID is present in the URL
if (isset($_GET['id'])) {
    // Retrieve the ID from the URL parameter
    $id = $_GET['id'];

    // Fetch record from the database based on the ID
    $query = "SELECT * FROM students WHERE id = '$id'";
    $data  = findQuery($query);

    // Check if query was successful
    if ($data) {
        // Check if record exists
        if (count($data) > 0) {
            // Fetch data
            $row = $data[0];

            // Assign data to variables
            $exam               = $row['exam'];
            $regnumber          = $row['regnumber'];
            $name               = $row['name'];
            $fathername         = $row['fathername'];
            $number             = $row['number'];
            $address            = $row['address'];
            $selectedPanchayath = $row['panchayath'];
            $selectedWard       = $row['ward'];
            $cnsno              = $row['school'];
        } else {
            echo 'Record not found.';
            exit;
        }
    } else {
        echo 'Error executing query.';
        exit;
    }
} else {
    echo 'ID parameter is missing.';
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <!-- Bootstrap 5 -->
    <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.bundle.min.js"></script>
    
    <!-- CropperJS CDN -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.js"></script>

    <link rel="icon" href="download.jpeg">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;500;600&display=swap" rel="stylesheet">

    <title>Registration</title>
    <style>
        body {
            background: linear-gradient(rgba(0,0,0,0.6), rgba(0,0,0,0.6)), 
                        url('https://mlavallikkunnu.in/trophy.jpg') no-repeat center center fixed;
            background-size: cover;
            font-family: 'Poppins', sans-serif;
        }
        .card-registration {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.18);
            color: white;
        }
        .form-label, .form-control {
            color: white;
        }
        select.form-control, input.form-control {
            background-color: rgba(255, 255, 255, 0.1);
            border: 1px solid #fff;
            color: white;
        }
        .img-container {
            max-width: 100%;
            max-height: 70vh;
            overflow: hidden;
            margin: auto;
        }
        .img-container img {
            width: 100%;
            height: auto;
            display: block;
        }
        #previewCropped {
            max-height: 200px;
            display: none;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <section class="vh-100">
        <div class="container py-5 h-100">
            <div class="row justify-content-center align-items-center h-100">
                <div class="col-12 col-lg-9 col-xl-7">
                    <div class="card shadow-2-strong card-registration" style="border-radius: 15px;">
                        <div class="card-body p-4 p-md-5">
                            <h3 class="mb-4 pb-2 pb-md-0 mb-md-5 text-center">Registration Form</h3>
                            <form action="update.php" method="POST" enctype="multipart/form-data" autocomplete="off">
                                <div class="row">
                                    <div class="col-md-6 mb-4">
                                        <label class="form-label">Qualified Exam<span style="color: red;"> *</span></label>
                                        <select class="form-control" name="exam" required>
                                            <option value="">Select Exam</option>
                                                    <option value="SSLC" <?php if (isset($exam) && $exam == 'SSLC') {
                                                        echo 'selected';
                                                    } ?>>SSLC</option>
                                                    <option value="PLUS TWO" <?php if (isset($exam) && $exam == 'PLUS TWO') {
                                                        echo 'selected';
                                                    } ?>>PLUS TWO</option>
                                                     
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-4">
                                        <label class="form-label">Register Number <span style="color: red;"> *</span></label>
                                        <input type="text" name="regnumber" class="form-control" required value="<?php echo $regnumber ?? ''; ?>" />
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-4">
                                        <label class="form-label">Student Name<span style="color: red;"> *</span></label>
                                        <input type="text" name="name" class="form-control" required maxlength="100" value="<?php echo $name ?? ''; ?>"  />
                                    </div>
                                    <div class="col-md-6 mb-4">
                                        <label class="form-label">Father's Name<span style="color: red;"> *</span></label>
                                        <input type="text" name="fathername" class="form-control" required maxlength="100" value="<?php echo $fathername ?? ''; ?>"  />
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-4">
                                        <label class="form-label">Mobile Number<span style="color: red;"> *</span></label>
                                       <input
  type="tel"
  name="number"
  class="form-control"
  maxlength="10"
  pattern="[6-9][0-9]{9}"
  inputmode="numeric"
  oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0,10)"
  title="Please enter a valid mobile number"
  required value="<?php echo $number ?? ''; ?>" 
/>

                                    </div>
                                    <div class="col-md-6 mb-4">
                                        <label class="form-label">House Name<span style="color: red;"> *</span></label>
                                        <input type="text" name="address" class="form-control"  maxlength="500" required value="<?php echo $address ?? ''; ?>"  />
                                    </div>
                                   
                                     <div class="col-md-6 mb-4">
                                        <label class="form-label">School<span style="color: red;"> *</span></label>
                                        <input type="text" name="school" class="form-control" required maxlength="500" required  value="<?php echo $cnsno ?? ''; ?>" />
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-4">
                                        <label class="form-label">Panchayath<span style="color: red;"> *</span></label>
                                        <select class="form-control" id="panchayath" name="panchayath" required>
                                                    <option value=''>Select Panchayath</option>
                                                    <?php foreach ($panchayathData as $row) : ?>
                                                        <option value="<?php echo $row['id']; ?>" <?php echo ($selectedPanchayath == $row['id']) ? 'selected' : ''; ?>>
                                                            <?php echo $row['panchayath']; ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                    </div>
                                    <div class="col-md-6 mb-4">
                                        <label class="form-label">Ward<span style="color: red;"> *</span></label>
                                        <select class="form-control" id="ward" name="ward" required>
                                           <option value="">Select Ward</option>
                                                    <?php
                                                    // Loop through ward data
                                                    foreach ($wardData as $ward) {
                                                        // Check if the ward is selected
                                                        $selected = ($ward['id'] == $selectedWard) ? 'selected' : '';
                                                        // Output the option with selected attribute if it's the selected ward
                                                        echo '<option value="' . $ward['id'] . '" ' . $selected . '>' . $ward['ward'] . '</option>';
                                                    }
?>
                                        </select>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-4">
                                        <label class="form-label">Photo Upload<span style="color: red;"> *</span></label>
                                        <input type="file" id="imageInput" class="form-control" accept="image/jpeg,image/png,image/jpg"  />
                                        <span class="text-muted small">*Only JPEG, JPG, PNG under 1MB</span>
                                        <input type="hidden" name="croppedImage" id="croppedImage">
                                        <input type="hidden" id="editid" name="editid" value="<?php echo $id ?? ''; ?>">
                                        <img id="previewCropped" src="#" />
                                    </div>
                                    <div class="col-md-6 mb-4">
                                        <label class="form-label">Mark List Upload<span style="color: red;"> *</span></label>
                                        <input type="file" id="marklistInput" name="marklist" class="form-control" accept="application/pdf,image/jpeg,image/png,image/jpg"  />
                                        <span class="text-muted small">*PDF, JPEG, JPG, PNG only</span>
                                    </div>
                                </div>
                                <div class="text-center">
                                    <input class="btn btn-primary btn-lg px-5" type="submit" value="Submit" />
                                </div>
                                <footer style="
  margin-top: 50px;
  padding: 15px;
  background-color: #f3f3fb;
  text-align: center;
  border-top: 1px solid #ccc;
  border-radius: 0 0 12px 12px;
  font-size: 16px;
  font-weight: bold;
">
  <span style="background: linear-gradient(90deg, #ff6a00, #ee0979, #00c3ff);
               -webkit-background-clip: text;
               -webkit-text-fill-color: transparent;
               display: inline-block;
               margin-right: 10px;">
    Powered by
  </span>
  <a href="https://workmateinfotech.com" target="_blank" style="display: inline-block; vertical-align: middle;">
    <img src="https://workmateinfotech.com/images/Workmate_Infotech_Private_Limited____Logo_1_-0_1__1_-removebg-preview%201%20(2).png" alt="Workmate Infotech Logo" style="height: 40px; vertical-align: middle;">
  </a>
</footer>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Crop Modal -->
        <div class="modal fade" id="modal" tabindex="-1">
            <div class="modal-dialog modal-dialog-centered modal-fullscreen-sm-down">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Crop image</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="img-container">
                            <img id="image">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" id="crop">Crop</button>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- JS Dependencies -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="sweetalert.js"></script>
    <script>
        window.onload = function() {
            // Get the values from the URL
            var message = getParameterByName('message');
            
            
            

            // Check for specific messages and handle accordingly
            if (message) {
                if (message == 'Unsupported file format' || message == 'Already registered with this register number') {
                    swal({
                        title: "Alert",
                        text: message,
                        icon: "error",
                    }).then(function() {
                        // Change the URL after the SweetAlert is closed
                        window.location.href = "https://mlavallikkunnu.in/index.php"; // Replace "https://example.com/new-url" with your desired URL
                    });
                }
                
                if (message == 'Registered Successfully') {
                    swal({
                        title: "Alert",
                        text: message,
                        icon: "success",
                    }).then(function() {
                        // Change the URL after the SweetAlert is closed
                        window.location.href = "https://mlavallikkunnu.in/index.php"; // Replace "https://example.com/new-url" with your desired URL
                    });
                }
            }

            // Function to get query parameters from the URL
            function getParameterByName(name, url) {
                if (!url) url = window.location.href;
                name = name.replace(/[\[\]]/g, '\\$&');
                var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
                    results = regex.exec(url);
                if (!results) return null;
                if (!results[2]) return '';
                return decodeURIComponent(results[2].replace(/\+/g, ' '));
            }
        };
    </script>
    <script>
    
   

        $(document).ready(function () {
            const image = document.getElementById('image');
            let cropper;
            let bsModal;

            $("#imageInput").on("change", function (e) {
                const file = e.target.files[0];
                if (!file || file.size > 1024 * 1024) {
                    swal({ title: "Error", text: "Image too large. Max 1MB.", icon: "error" });
                    $(this).val('');
                    return;
                }
                const reader = new FileReader();
                reader.onload = function (event) {
                    image.src = event.target.result;
                    bsModal = new bootstrap.Modal(document.getElementById('modal'));
                    bsModal.show();
                };
                reader.readAsDataURL(file);
            });

            document.getElementById('modal').addEventListener('shown.bs.modal', function () {
                cropper = new Cropper(image, {
                    aspectRatio: 739 / 881,
                    viewMode: 1,
                    responsive: true,
                    autoCropArea: 1,
                    background: false,
                    zoomOnTouch: true,
                    dragMode: 'move'
                });
            });

            document.getElementById('modal').addEventListener('hidden.bs.modal', function () {
                if (cropper) {
                    cropper.destroy();
                    cropper = null;
                }
            });

            $('#crop').click(function () {
                const canvas = cropper.getCroppedCanvas({
                    width: 260,
                    height: 310
                });
                canvas.toBlob(function (blob) {
                    const reader = new FileReader();
                    reader.onloadend = function () {
                        $('#croppedImage').val(reader.result);
                        $('#previewCropped').attr('src', reader.result).show();
                        bsModal.hide();
                    };
                    reader.readAsDataURL(blob);
                });
            });
            
             // When modal is hidden (closed by any means, including Cancel button)
$('#modal').on('hidden.bs.modal', function () {
    if (!$('#croppedImage').val()) { // if no cropped image value
        $('#imageInput').val('');
        $('#previewCropped').hide().attr('src', '#');
        $('#imageFileName').text(''); // clear file name display
    }
});





            $('#marklistInput').on('change', function () {
                const allowed = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png'];
                const type = this.files[0]?.type;
                if (!allowed.includes(type)) {
                    swal({ title: "Error", text: "Invalid marklist file.", icon: "error" });
                    $(this).val('');
                }
            });

            $('#panchayath').on('change', function () {
                const panchayath = $(this).val();
                $.post('panchayathward.php', { panchayath: panchayath }, function (data) {
                    $('#ward').html(data);
                });
            });
        });
        
        

    </script>
</body>
</html>
