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

    $brand_id = isset($_GET['brand_id']) ? $_GET['brand_id'] : '';
    $back_url = 'brand_list.php';
    
    $row1 = [];
    $query1 = "SELECT id, brand_id, brand FROM brand WHERE brand_id = '$brand_id'";
    $result1 = mysqli_query($conn, $query1);
    if ($result1 && mysqli_num_rows($result1) > 0) {
        $row1 = mysqli_fetch_assoc($result1);
    } 
    
    if (empty($row1)) {
        $savetype = "add_brand";
    } else {
        $savetype = "edit_brand";
    }
?>

<!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 Brand</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="brand_id" name="brand_id" class="form-control" value="<?php echo $row1['brand_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>
                                    <input type="text" class="form-control" name="brand_type" id="brand_type" value="<?php echo $row1['brand'] ?? ''; ?>">
                                </div>
                                <div class="error" id="brand_type_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 brand_id = $("#brand_id").val().trim();
            var brand_type = $("#brand_type").val().trim();
            
            var count = 0;

            if (brand_type == '') { $('#brand_type_error').html('*Required'); count++; }
            
            if (count > 0) return false;

            var formData = new FormData();
            formData.append("type", save_type); 
            formData.append("brand_id", brand_id); 
            formData.append("brand_type", brand_type);  
            
            // 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>