<?php
    include "../../db/connection.php";

    $type_id = isset($_GET['type_id']) ? $_GET['type_id'] : '';
    $back_url = 'dronetype_list.php';
    
    $row1 = [];
    $query1 = "SELECT id, type_id, type_of_drone, category FROM type_of_drones WHERE type_id = '$type_id'";
    $result1 = mysqli_query($conn, $query1);
    if ($result1 && mysqli_num_rows($result1) > 0) {
        $row1 = mysqli_fetch_assoc($result1);
    } 
    
    $selectedCharactristics = [];
    $query2 = "SELECT id, charactristics FROM type_drone_charactristics WHERE drone_type = '$type_id' AND deletion = 0";
    $result2 = mysqli_query($conn, $query2);
    if ($result2 && mysqli_num_rows($result2) > 0) {
        while ($rowdept = mysqli_fetch_assoc($result2)) {
            $selectedCharactristics[] = $rowdept['charactristics'];
        }
    }
    
    $selectedUsecases = [];
    $query3 = "SELECT id, usecase FROM type_drone_usecase WHERE drone_type = '$type_id' AND deletion = 0";
    $result3 = mysqli_query($conn, $query3);
    if ($result3 && mysqli_num_rows($result3) > 0) {
        while ($rowcity = mysqli_fetch_assoc($result3)) {
            $selectedUsecases[] = $rowcity['usecase'];
        }
    }
    
    if (empty($row1)) {
        $savetype = "add_dronetype";
    } else {
        $savetype = "edit_dronetype";
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SkyBots</title>

    <?php include "../support_header.php"; ?>
    <link rel="stylesheet" href="../../assets/custom_css/other_styles.css">
</head>
<body>
    <div class="wrapper">
        <form id="saveForm" onsubmit="return add_form()" method="post" enctype="multipart/form-data">
            <div class="app-content-header">
                <div class="row">
                    <div class="col-6"><div class="heading">Save Drone Type</div></div>
                    <div class="col-6 text-right">
                        <button type="submit" class="btn btn-primary mr-2" name="submit">Save</button>
                        <a class="btn btn-secondary" href="<?php echo $back_url; ?>">Back</a>
                    </div>
                </div>
            </div>
            <div class="app-content">
                <div class="card">

                    <input type="hidden" id="save_type" name="save_type" class="form-control" value="<?php echo $savetype; ?>" />
                    <input type="hidden" id="type_id" name="type_id" class="form-control" value="<?php echo $row1['type_id'] ?? ''; ?>" />

                    <div class="row">
                        <div class="col-12">
                            <div class="form-group">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">Drone Type</span>
                                    </div>
                                    <input type="text" class="form-control" name="drone_type" id="drone_type" value="<?php echo $row1['type_of_drone'] ?? ''; ?>">
                                </div>
                                <div class="error" id="drone_type_error"></div>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-group">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">Category</span>
                                    </div>
                                    <select class="form-control selectpicker select2" name="category" id="category" data-live-search="true">
                                        <option value=""></option>
                                        <?php
                                            $sql = "SELECT category_id, category 
                                                    FROM drone_category 
                                                    WHERE deletion = 0";
                                            $res = mysqli_query($conn, $sql);
                                            if ($res && mysqli_num_rows($res) > 0) {
                                                while ($row = mysqli_fetch_assoc($res)) {
                                                    $selected = ($row['category_id'] == $row1['category']) ? 'selected' : '';
                                        ?>
                                                    <option value="<?php echo $row['category_id'] ?? ''; ?>" <?php echo $selected; ?> ><?php echo $row['category'] ?? ''; ?></option>
                                        <?php
                                                }
                                            }
                                        ?>
                                    </select>
                                </div>
                                <div class="error" id="category_error"></div>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-group">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">Characteristics</span>
                                    </div>
                                    <div class="form-control" style="height: auto;">
                                        <?php
                                            $sql = "SELECT charactristics_id, charactristics 
                                                    FROM drone_charactristics 
                                                    WHERE deletion = 0";
                                            $res = mysqli_query($conn, $sql);
                                            if ($res && mysqli_num_rows($res) > 0) {
                                                $inc = 1;
                                                while ($row = mysqli_fetch_assoc($res)) {
                                                    $selected = (in_array($row['charactristics_id'], $selectedCharactristics)) ? 'checked' : '';
                                        ?>
                                                    <label class="form-check-label" for="charactristics<?php echo $inc; ?>" style="width: 100%;">
                                                        <input class="form-check-input" type="checkbox" value="<?php echo $row['charactristics_id']; ?>" id="charactristics<?php echo $inc; ?>" name="charactristics[]" <?php echo $selected; ?> >
                                                        <?php echo $row['charactristics']; ?>
                                                    </label>
                                        <?php
                                                    $inc++;
                                                }
                                            }
                                        ?>
                                    </div>
                                </div>
                                <div class="error" id="charactristics_error"></div>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-group">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">Usecases</span>
                                    </div>
                                    <div class="form-control" style="height: auto;">
                                        <?php
                                            $sql = "SELECT usecase_id, usecase 
                                                    FROM drone_usecase 
                                                    WHERE deletion = 0";
                                            $res = mysqli_query($conn, $sql);
                                            if ($res && mysqli_num_rows($res) > 0) {
                                                $inc = 1;
                                                while ($row = mysqli_fetch_assoc($res)) {
                                                    $selected = (in_array($row['usecase_id'], $selectedUsecases)) ? 'checked' : '';
                                        ?>
                                                    <label class="form-check-label" for="usecases<?php echo $inc; ?>" style="width: 100%;">
                                                        <input class="form-check-input" type="checkbox" value="<?php echo $row['usecase_id']; ?>" id="usecases<?php echo $inc; ?>" name="usecases[]" <?php echo $selected; ?> >
                                                        <?php echo $row['usecase']; ?>
                                                    </label>
                                        <?php
                                                    $inc++;
                                                }
                                            }
                                        ?>
                                    </div>
                                </div>
                                <div class="error" id="usecase_error"></div>
                            </div>
                        </div>
                    </div>

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

    <?php include "../support_footer.php"; ?>

    <script> 
        function add_form() {
            
            $('.error').html('');
            var url = "<?php echo $back_url;?>";
            var save_type = $("#save_type").val().trim();
            var type_id = $("#type_id").val().trim();
            var drone_type = $("#drone_type").val().trim();
            var category = $("#category").val().trim();

            var formData = new FormData();
            formData.append("type", save_type); 
            formData.append("type_id", type_id); 
            formData.append("drone_type", drone_type);  
            formData.append("category", category); 
            $('input[name="charactristics[]"]:checked').each(function () {
                formData.append("charactristics[]", $(this).val());
            });
            $('input[name="usecases[]"]:checked').each(function () {
                formData.append("usecases[]", $(this).val());
            });
            
            // for (var pair of formData.entries()) {
            //     console.log(pair[0] + ': ' + pair[1]);
            // }

            showLoader();
            
            $.ajax({
                type: "POST",
                url: "query_function.php",
                data: formData,
                processData: false, 
                contentType: false, 
                dataType: "json",
                success: function (response) {
                    hideLoader();
                    // console.log("Server response:", response);
                    // alert(JSON.stringify(response));

                    if (response.status === 'success' && response.code === 11) {
                        window.parent.$("#successModal .alertTitle").html("Successfully Saved!");
                        window.parent.showModal('successModal');
                        window.parent.$('#successModal').off('hidden.bs.modal').on('hidden.bs.modal', function () {
                            window.parent.location.reload();
                        });
                        window.parent.location.reload();
                    } else if (response.status === 'error') {
                        $('.error').html(''); 
                        if (response.errors && response.errors.length > 0) {
                            response.errors.forEach(function(field) {
                                $('#' + field + '_error').html('*Required');
                            });
                        }
                    } else {
                        window.parent.$("#warningModal .alertTitle").html(response.message || "Not Added!");
                        window.parent.showModal('warningModal');
                    }
                },
                error: function (xhr, status, error) {
                    hideLoader();
                    console.error("AJAX Error:", status, error);
                    alert("Server Error: " + error);
                }
            });

            return false;
        }
    </script>

</body>
</html>