<?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'];
        } 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.0">
    <title>edit</title>
    <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">


</head>
<style>
    .gradient-custom {
        background-color: black;
        /* background: linear-gradient(90deg, rgba(2, 0, 36, 1) 1%, rgba(119, 119, 119, 1) 100%, rgba(0, 212, 255, 1) 100%); */
    }

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

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

<body>
    <section class="vh-100 bg-image gradient-custom">
        <div class="mask d-flex align-items-center h-100 gradient-custom-3">
            <div class="container h-100">
                <div class="row d-flex justify-content-center align-items-center h-100">
                    <div class="col-12 col-md-9 col-lg-7 col-xl-6">
                        <div class="card" style="border-radius: 15px;">
                            <div class="card-body p-5">
                                <h2 class="text-uppercase text-center mb-5">Edit the changes</h2>

                                <form action="update.php" method="POST" enctype="multipart/form-data">

                                    <div class="row">
                                        <div class="col-md-6 mb-4">
                                            <div data-mdb-input-init class="form-outline">
                                                <label class="form-label" for="firstName">Qualified Exam</label>
                                                <select class="select 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>
                                                    
                                                    <option value="USS" <?php if (isset($exam) && $exam == 'USS') {
                                                        echo 'selected';
                                                    } ?>>USS</option>
                                                    
      <option value="LSS" <?php if (isset($exam) && $exam == 'LSS') {
          echo 'selected';
      } ?>>LSS</option>   
      
         <option value="NMMS" <?php if (isset($exam) && $exam == 'NMMS') {
             echo 'selected';
         } ?>>NMMS</option>                                        
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-4">
                                            <div data-mdb-input-init class="form-outline">
                                                <label class="form-label" for="firstName">Register Number</label>
                                                <input type="text" id="regnumber" name="regnumber" class="form-control form-control" required value="<?php echo isset($regnumber) ? $regnumber : ''; ?>" />
                                                <div class="" id="message"></div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-4">
                                            <div data-mdb-input-init class="form-outline">
                                                <label class="form-label" for="lastName">Name</label>
                                                <input type="text" id="name" name="name" class="form-control form-control" required value="<?php echo isset($name) ? $name : ''; ?>" />
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-4">
                                            <div data-mdb-input-init class="form-outline">
                                                <label class="form-label" for="lastName">Father's Name</label>
                                                <input type="text" id="fathername" name="fathername" class="form-control form-control" required value="<?php echo isset($fathername) ? $fathername : ''; ?>" />
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-4">
                                            <div data-mdb-input-init class="form-outline">
                                                <label class="form-label" for="lastName">Mobile number</label>
                                                <input type="tel" id="number" name="number" class="form-control form-control" required value="<?php echo isset($number) ? $number : ''; ?>" />
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-4 pb-2">
                                            <div data-mdb-input-init class="form-outline">
                                                <label class="form-label" for="emailAddress">Address</label>
                                                <input type="text" id="Address" name="address" class="form-control form-control" required value="<?php echo isset($address) ? $address : ''; ?>" />
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-4 pb-2">
                                            <div data-mdb-input-init class="form-outline">
                                                <label class="form-label" for="panchayath">Panchayath</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>


                                        <div class="col-md-6 mb-4 pb-2">
                                            <div data-mdb-input-init class="form-outline">
                                                <label class="form-label" for="ward">Ward</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>
                                    <div class="row">
                                        <div class="col-md-6 mb-4 pb-2">

                                            <div data-mdb-input-init class="form-outline">
                                                <label class="form-label" for="emailAddress">Photo Upload </label>
                                                <input type="file" id="imageInput" name="image" class="form-control form-control imageInput" />
                                                <span style="color:grey;font-size:12px">*Only Upload (JPEG,JPG,PNG) format file</span>
                                                <input type="hidden" id="croppedImage" name="croppedImage">
                                                 <input type="hidden" id="editid" name="editid" value="<?php echo isset($id) ? $id : ''; ?>">
                                            </div>

                                        </div>

                                        <div class="col-md-6 mb-4 pb-2">

                                            <div data-mdb-input-init class="form-outline">
                                                <label class="form-label" for="phoneNumber">Mark list Upload</label>
                                                <input type="file" id="marklistInput" name="marklist" class="form-control form-control marklistInput" />
                                                <span style="color:grey;font-size:12px">*Only Upload (PDF,JPEG,JPG,PNG) file</span>

                                            </div>

                                        </div>
                                    </div>

                                    <div class="mt-2 pt-2">
                                        <input data-mdb-ripple-init class="btn btn-primary btn-lg " type="submit" value="Submit" />
                                    </div>

                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <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>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div class="img-container">
                                <div class="row">
                                    <div class="col-md-8">
                                        <!--  default image where we will set the src via jquery-->
                                        <img id="image">
                                    </div>
                                    <div class="col-md-4">
                                        <div class="preview"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="clearFileInput()">Cancel</button> <button type="button" class="btn btn-primary" id="crop">crop</button>
                        </div>
                    </div>
                </div>
            </div>

    </section>
    <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://kpamajeedmla.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() {
            $('#panchayath').on('change', function() {
                var panchayath = this.value;
                $.ajax({
                    url: "panchayathward.php",
                    type: "POST",
                    data: {
                        panchayath: panchayath
                    },
                    cache: false,
                    success: function(result) {
                        $("#ward").html(result);
                    }
                });
            });
        });
    </script>
    <!-- cropperjs -->

    <script>
        var bs_modal = $('#modal');
        var image = document.getElementById('image');
        var cropper, reader, file;

        // Image input change event
        $("body").on("change", "#imageInput", function(e) {
            var files = e.target.files;
            var done = function(url) {
                image.src = url;
                bs_modal.modal('show');
            };

            if (files && files.length > 0) {
                file = files[0];
                var fileType = file.type;

                if (fileType == 'image/jpeg' || fileType == 'image/png') {
                    if (URL) {
                        done(URL.createObjectURL(file));
                    } else if (FileReader) {
                        reader = new FileReader();
                        reader.onload = function(e) {
                            done(reader.result);
                        };
                        reader.readAsDataURL(file);
                    }
                } else {
                    swal({
                        title: "Alert",
                        text: "Please upload a JPEG or PNG image.",
                        icon: "error",
                    });
                    // Clear the input
                    $("#imageInput").val('');
                }
            }
        });

        // Marklist input change event
        $("body").on("change", "#marklistInput", function(e) {
            var files = e.target.files;
            var fileType, isSupported;

            if (files && files.length > 0) {
                file = files[0];
                fileType = file.type;
                isSupported = fileType == 'application/pdf' ||
                    fileType == 'image/jpeg' ||
                    fileType == 'image/jpg' ||
                    fileType == 'image/png';

                if (!isSupported) {
                    swal({
                        title: "Alert",
                        text: "Please upload a PDF, JPEG, JPG, or PNG file for the marklist.",
                        icon: "error",
                    });
                    // Clear the input
                    $("#marklistInput").val('');
                }
            }
        });

        bs_modal.on('shown.bs.modal', function() {
            cropper = new Cropper(image, {
                aspectRatio: 9.5 / 12.5,
                viewMode: 3,
                preview: '.preview'
            });
        }).on('hidden.bs.modal', function() {
            cropper.destroy();
            cropper = null;
        });

        $("#crop").click(function() {
            canvas = cropper.getCroppedCanvas({
                width: 260,
                height: 160,
            });

            canvas.toBlob(function(blob) {
                url = URL.createObjectURL(blob);
                var reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onloadend = function() {
                    var base64data = reader.result;
                    // Store the base64 data in the hidden input field
                    $('#croppedImage').val(base64data);
                    bs_modal.modal('hide');
                };
            });
        });

        function enableFileInput() {
            document.getElementById('imageInput').removeAttribute('disabled');
        }

        // Function to clear file input field
        function clearFileInput() {
            document.getElementById('imageInput').value = '';
        }
    </script>

</body>

</html>