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

    $model_id = isset($_GET['model_id']) ? $_GET['model_id'] : '';
    $back_url = 'model_list.php';
    
    $row1 = [];
    $query1 = "SELECT id, model_id, model, brand, drone_type FROM model WHERE model_id = '$model_id'";
    $result1 = mysqli_query($conn, $query1);
    if ($result1 && mysqli_num_rows($result1) > 0) {
        $row1 = mysqli_fetch_assoc($result1);
    } 
    
    if (empty($row1)) {
        $savetype = "add_model";
    } else {
        $savetype = "edit_model";
    }
?>

<!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 Model</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="model_id" name="model_id" class="form-control" value="<?php echo $row1['model_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">Model</span>
                                    </div>
                                    <input type="text" class="form-control" name="model_type" id="model_type" value="<?php echo $row1['model'] ?? ''; ?>">
                                </div>
                                <div class="error" id="model_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">Drone Type</span>
                                    </div>
                                    <select class="form-control selectpicker select2" name="drone_type" id="drone_type" data-live-search="true">
                                        <option value=""></option>
                                        <?php
                                            $sql = "SELECT type_id, type_of_drone 
                                                    FROM type_of_drones 
                                                    WHERE deletion = 0";
                                            $res = mysqli_query($conn, $sql);
                                            if ($res && mysqli_num_rows($res) > 0) {
                                                while ($row = mysqli_fetch_assoc($res)) {
                                                    $selected = ($row['type_id'] == $row1['drone_type']) ? 'selected' : '';
                                        ?>
                                                    <option value="<?php echo $row['type_id'] ?? ''; ?>" <?php echo $selected; ?> ><?php echo $row['type_of_drone'] ?? ''; ?></option>
                                        <?php
                                                }
                                            }
                                        ?>
                                    </select>
                                </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">Brand</span>
                                    </div>
                                    <select class="form-control selectpicker select2" name="brand" id="brand" data-live-search="true">
                                        <option value=""></option>
                                        <?php
                                            $sql = "SELECT brand_id, brand 
                                                    FROM brand 
                                                    WHERE deletion = 0";
                                            $res = mysqli_query($conn, $sql);
                                            if ($res && mysqli_num_rows($res) > 0) {
                                                while ($row = mysqli_fetch_assoc($res)) {
                                                    $selected = ($row['brand_id'] == $row1['brand']) ? 'selected' : '';
                                        ?>
                                                    <option value="<?php echo $row['brand_id'] ?? ''; ?>" <?php echo $selected; ?> ><?php echo $row['brand'] ?? ''; ?></option>
                                        <?php
                                                }
                                            }
                                        ?>
                                    </select>
                                </div>
                                <div class="error" id="brand_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 model_id = $("#model_id").val().trim();
            var model_type = $("#model_type").val().trim();
            var drone_type = $("#drone_type").val().trim();
            var brand = $("#brand").val().trim();

            var formData = new FormData();
            formData.append("type", save_type); 
            formData.append("model_id", model_id); 
            formData.append("model_type", model_type);  
            formData.append("drone_type", drone_type);  
            formData.append("brand", brand);  
            
            // 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>