<?php
    include('../session_timeout.php');
    include "../../db/connection.php";

    $login_user_id = $_SESSION['skybots_user_id'];
    $login_role = $_SESSION['skybots_role'];

    $type = $_POST['type'];

    date_default_timezone_set("Asia/Kolkata");
    $currentdatetime = date("Y-m-d H:i:s");
    $currentdate = date("Y-m-d");
    $currenttime = date("H-i-s");

    if ($type == 'add_variant') {
        $errors = [];

        $variant_id       = trim($_POST['variant_id'] ?? '');
        $brand       = trim($_POST['brand'] ?? '');
        $model       = trim($_POST['model'] ?? '');
        $variant       = trim($_POST['variant'] ?? '');
        $price       = trim($_POST['price'] ?? '');
        $short_description       = trim($_POST['short_description'] ?? '');

        if ($brand === '') { $errors[] = 'brand'; }
        if ($model === '') { $errors[] = 'model'; }
        if ($variant === '') { $errors[] = 'variant'; }
        if ($price === '') { $errors[] = 'price'; }
        if ($short_description === '') { $errors[] = 'short_description'; }

        if (!empty($errors)) {
            echo json_encode(['status' => 'error', 'errors' => $errors]);
            exit;
        }

        // --- Check duplicate ---
        $check_sql = "SELECT id 
                        FROM variant 
                        WHERE deletion = 0 
                            AND variant = ? AND model = ? AND brand = ?"; 
        $stmt_check = $conn->prepare($check_sql);
        $stmt_check->bind_param("sss", $variant, $model, $brand);
        $stmt_check->execute();
        $result_check = $stmt_check->get_result();

        if ($result_check->num_rows > 0) {
            echo json_encode(['status' => 'exists', 'message' => 'Already Available..!']);
            exit;
        }

        // --- Insert new record ---
        $insert_sql = "INSERT INTO variant (variant_id, variant, brand, model, short_description, price, added_by, added_time)
                        VALUES ('NA', ?, ?, ?, ?, ?, ?, ?)";
        $stmt_insert = $conn->prepare($insert_sql);
        $stmt_insert->bind_param(
            "sssssss",
            $variant,
            $brand,
            $model,
            $short_description,
            $price,
            $login_user_id,
            $currentdatetime
        );

        if ($stmt_insert->execute()) {
            $last_id = $conn->insert_id;
            $variant_id = 'variant_' . $last_id;
            
            $update_sql = "UPDATE variant 
                        SET variant_id = ? 
                        WHERE id = ?";
            $stmt_update = $conn->prepare($update_sql);
            $stmt_update->bind_param("si",$variant_id, $last_id);
            if ($stmt_update->execute()) {

                $insert_sql1 = "INSERT INTO drone_specification (variant, added_by, added_time)
                                VALUES (?,?,?)";
                $stmt_insert1 = $conn->prepare($insert_sql1);
                $stmt_insert1->bind_param(
                    "sss",
                    $variant_id,
                    $login_user_id,
                    $currentdatetime
                );

                if ($stmt_insert1->execute()) {
                    echo json_encode(['status' => 'success', 'code' => 11]);
                } else {
                    echo json_encode(['status' => 'error', 'message' => $conn->error, 'code' => 00]);
                }

            } else {
                echo json_encode(['status' => 'error', 'message' => $conn->error, 'code' => 00]);
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => $conn->error, 'code' => 00]);
        }

        $stmt_insert->close();
        $stmt_check->close();
    }
    else if ($type == 'edit_variant') {
        $errors = [];

        $variant_id       = trim($_POST['variant_id'] ?? '');
        $brand       = trim($_POST['brand'] ?? '');
        $model       = trim($_POST['model'] ?? '');
        $variant       = trim($_POST['variant'] ?? '');
        $price       = trim($_POST['price'] ?? '');
        $short_description       = trim($_POST['short_description'] ?? '');

        if ($variant_id === '') { $errors[] = 'variant'; }
        if ($brand === '') { $errors[] = 'brand'; }
        if ($model === '') { $errors[] = 'model'; }
        if ($variant === '') { $errors[] = 'variant'; }
        if ($price === '') { $errors[] = 'price'; }
        if ($short_description === '') { $errors[] = 'short_description'; }

        if (!empty($errors)) {
            echo json_encode(['status' => 'error', 'errors' => $errors]);
            exit;
        }
            
        $update_sql = "UPDATE variant 
                    SET variant = ?, brand = ?, model = ?, short_description = ?, price = ?  
                    WHERE variant_id = ?";
        $stmt_update = $conn->prepare($update_sql);
        $stmt_update->bind_param("ssssss", $variant, $brand, $model, $short_description, $price, $variant_id);
        if ($stmt_update->execute()) {
            echo json_encode(['status' => 'success', 'code' => 11]);
        } else {
            echo json_encode(['status' => 'error', 'message' => $conn->error, 'code' => 00]);
        }
        
    }
    else if ($type == 'delete_variant') {
        $id = $_POST['id'];
        $sql = "UPDATE variant SET deleted_by = '$login_user_id', deleted_time = '$currentdatetime', deletion = 1 WHERE variant_id = '$id'";
        if ($conn->query($sql) === TRUE) {
            $sql = "UPDATE drone_specification SET deleted_by = '$login_user_id', deleted_time = '$currentdatetime', deletion = 1 WHERE variant = '$id'";
            if ($conn->query($sql) === TRUE) {
                $sql = "UPDATE drone_images SET deleted_by = '$login_user_id', deleted_time = '$currentdatetime', deletion = 1 WHERE variant_id = '$id'";
                if ($conn->query($sql) === TRUE) {
                    echo "11";
                } else {
                    echo $conn->error;
                } 
            } else {
                echo $conn->error;
            } 
        } else {
            echo $conn->error;
        }
    } 
    else if ($type == 'edit_specification') {
        $errors = [];

        $variant_id       = trim($_POST['variant_id'] ?? '');

        if ($variant_id === '') { $errors[] = 'weight'; }

        if (!empty($errors)) {
            echo json_encode(['status' => 'error', 'errors' => $errors]);
            exit;
        }

        function val($key) {
            return isset($_POST[$key]) && $_POST[$key] !== '' ? $_POST[$key] : NULL;
        }

        $weight               = val('weight');
        $dimensions           = val('dimensions');
        $frame_material       = val('frame_material');
        $mtow                 = val('mtow');
        $payload_capacity     = val('payload_capacity');
        $flight_time          = val('max_flight_time');
        $max_speed            = val('max_speed');
        $max_range            = val('max_range');
        $max_altitude         = val('max_altitude');
        $temp_range           = val('operating_temp');
        $wind_resistance      = val('wind_resistance');

        $battery_type         = val('battery_type');
        $battery_capacity     = val('battery_capacity');
        $battery_voltage      = val('battery_voltage');
        $charging_time        = val('charging_time');
        $charger_type         = val('charger_type');

        $gps_gnss             = val('gps_support');
        $return_home          = val('rth');
        $flight_modes         = val('flight_modes');
        $obstacle_avoidance   = val('obstacle_avoidance');
        $controller_type      = val('controller_type');
        $mobile_app_support   = val('mobile_app');

        $camera_available     = val('camera_available');
        $camera_resolution    = val('camera_resolution');
        $video_resolution     = val('video_resolution');
        $gimbal_type          = val('gimbal_type');
        $camera_sensors       = val('camera_sensors');
        $fpv_support          = val('fpv_support');

        $frequency            = val('frequency');
        $live_video_range     = val('live_video_range');
        $signal_encryption    = val('signal_encryption');

        $safety_features      = val('safety_features');
        $ai_features          = val('software_features');
        $certifications       = val('certifications');
        $package_contents     = val('package_contents');
        $warranty_support     = val('warranty_support');

        $area_spraying_rate   = val('area_spraying_rate');
        $spray_tank_capacity  = val('spray_tank_capacity');
        $no_of_nozzles        = val('no_of_nozzles');
        $spray_width          = val('spray_width');
        $spray_volume         = val('spray_volume');
        $gps_accuracy         = val('gps_accuracy');
        $terrain_following    = val('terrain_following');

        /* =========================
        UPDATE QUERY
        ========================= */
        $sql = "UPDATE drone_specification SET
            weight=?, dimensions=?, frame_material=?, take_off_Weight=?, payload_capacity=?,
            flight_time=?, max_speed=?, max_range=?, max_altitude=?, temp_range=?, wind_resistance_level=?,
            battery_type=?, battery_capacity=?, battery_voltage=?, charging_time=?, charger_type=?,
            GPS_GNSS=?, return_home=?, flight_modes=?, obstacle_avoidance=?, controller_type=?, mobile_app_support=?,
            camera_available=?, camera_resolution=?, video_resolution=?, gimbal_type=?, camera_sensors=?, FPV_support=?,
            transmission_frequency=?, live_video_range=?, signal_encryption=?,
            safety_features=?, AI_software_features=?, certifications=?, package_contents=?, warranty_support=?,
            area_spraying_rate=?, spray_tank_capacity=?, No_of_Nozzles=?, spray_width=?, spray_volume=?,
            GPS_accuracy=?, terrain_following=?,
            modifty_by=?, modifty_time=?
            WHERE variant=?";

        $stmt = $conn->prepare($sql);

        if (!$stmt) {
            echo json_encode(['status' => 'error', 'message' => 'Prepare failed']);
            exit;
        }

        $stmt->bind_param(
            "ssssssssssssssssssssssssssssssssssssssssssssss",
            $weight,
            $dimensions,
            $frame_material,
            $mtow,
            $payload_capacity,
            $flight_time,
            $max_speed,
            $max_range,
            $max_altitude,
            $temp_range,
            $wind_resistance,
            $battery_type,
            $battery_capacity,
            $battery_voltage,
            $charging_time,
            $charger_type,
            $gps_gnss,
            $return_home,
            $flight_modes,
            $obstacle_avoidance,
            $controller_type,
            $mobile_app_support,
            $camera_available,
            $camera_resolution,
            $video_resolution,
            $gimbal_type,
            $camera_sensors,
            $fpv_support,
            $frequency,
            $live_video_range,
            $signal_encryption,
            $safety_features,
            $ai_features,
            $certifications,
            $package_contents,
            $warranty_support,
            $area_spraying_rate,
            $spray_tank_capacity,
            $no_of_nozzles,
            $spray_width,
            $spray_volume,
            $gps_accuracy,
            $terrain_following,
            $login_user_id,
            $currentdatetime,
            $variant_id
        );
        
        if ($stmt->execute()) {
            echo json_encode(['status' => 'success', 'code' => 11]);
        } else {
            echo json_encode(['status' => 'error', 'message' => $conn->error, 'code' => 00]);
        }
    }
?>