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

    $variant_id = isset($_GET['variant_id']) ? $_GET['variant_id'] : '';
    $back_url = 'variant_list.php';
    
    $row1 = [];
    $query1 = "SELECT id, variant_id, variant, brand, model, short_description, price FROM variant WHERE variant_id = '$variant_id'";
    $result1 = mysqli_query($conn, $query1);
    if ($result1 && mysqli_num_rows($result1) > 0) {
        $row1 = mysqli_fetch_assoc($result1);
    } 
    
    if (empty($row1)) {
        $savetype = "add_variant";
    } else {
        $savetype = "edit_variant";
    }
?>

<!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 Variant</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="variant_id" name="variant_id" class="form-control" value="<?php echo $row1['variant_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">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 class="col-12">
                            <div class="form-group">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">Model</span>
                                    </div>
                                    <select class="form-control selectpicker select2" name="model" id="model" data-live-search="true">
                                        <option value=""></option>
                                        <?php
                                            $sql = "SELECT model_id, model 
                                                    FROM model 
                                                    WHERE deletion = 0";
                                            $res = mysqli_query($conn, $sql);
                                            if ($res && mysqli_num_rows($res) > 0) {
                                                while ($row = mysqli_fetch_assoc($res)) {
                                                    $selected = ($row['model_id'] == $row1['model']) ? 'selected' : '';
                                        ?>
                                                    <option value="<?php echo $row['model_id'] ?? ''; ?>" <?php echo $selected; ?> ><?php echo $row['model'] ?? ''; ?></option>
                                        <?php
                                                }
                                            }
                                        ?>
                                    </select>
                                </div>
                                <div class="error" id="model_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">Variant</span>
                                    </div>
                                    <input type="text" class="form-control" name="variant" id="variant" value="<?php echo $row1['variant'] ?? ''; ?>">
                                </div>
                                <div class="error" id="variant_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">Price</span>
                                    </div>
                                    <input type="text" class="form-control" name="price" id="price" value="<?php echo $row1['price'] ?? ''; ?>">
                                </div>
                                <div class="error" id="price_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">Description</span>
                                    </div>
                                    <textarea class="form-control" name="short_description" id="short_description"><?php echo $row1['short_description'] ?? ''; ?></textarea>
                                </div>
                                <div class="error" id="short_description_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 variant_id = $("#variant_id").val().trim();
            var brand = $("#brand").val().trim();
            var model = $("#model").val().trim();
            var variant = $("#variant").val().trim();
            var price = $("#price").val().trim();
            var short_description = $("#short_description").val().trim();

            var formData = new FormData();
            formData.append("type", save_type); 
            formData.append("variant_id", variant_id);  
            formData.append("brand", brand);   
            formData.append("model", model); 
            formData.append("variant", variant);  
            formData.append("price", price);  
            formData.append("short_description", short_description);  
            
            // 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>