<?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_category') {
        $errors = [];

        $category_id       = trim($_POST['category_id'] ?? '');
        $category_type       = trim($_POST['category_type'] ?? '');

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

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

        // --- Check duplicate ---
        $check_sql = "SELECT id 
                        FROM drone_category 
                        WHERE deletion = 0 
                            AND category = ?";
        $stmt_check = $conn->prepare($check_sql);
        $stmt_check->bind_param("s", $category_type);
        $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 drone_category (category_id, category, added_by, added_time)
                        VALUES ('NA', ?, ?, ?)";
        $stmt_insert = $conn->prepare($insert_sql);
        $stmt_insert->bind_param(
            "sss",
            $category_type,
            $login_user_id,
            $currentdatetime
        );

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

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

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

        $category_id       = trim($_POST['category_id'] ?? '');
        $category_type       = trim($_POST['category_type'] ?? '');
        
        if ($category_type === '') { $errors[] = 'category_type'; }

        if (!empty($errors)) {
            echo json_encode(['status' => 'error', 'errors' => $errors]);
            exit;
        }
            
        $update_sql = "UPDATE drone_category 
                    SET category = ? 
                    WHERE category_id = ?";
        $stmt_update = $conn->prepare($update_sql);
        $stmt_update->bind_param("ss",$category_type, $category_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_category') {
        $id = $_POST['id'];
        $sql = "UPDATE drone_category SET deleted_by = '$login_user_id', deleted_time = '$currentdatetime', deletion = 1 WHERE category_id = '$id'";
        if ($conn->query($sql) === TRUE) {
            echo "11";
        } else {
            echo $conn->error;
        }
    } 
    else if ($type == 'add_charactristics') {
        $errors = [];

        $charactristics_id       = trim($_POST['charactristics_id'] ?? '');
        $charactristics_type       = trim($_POST['charactristics_type'] ?? '');

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

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

        // --- Check duplicate ---
        $check_sql = "SELECT id 
                        FROM drone_charactristics 
                        WHERE deletion = 0 
                            AND charactristics = ?";
        $stmt_check = $conn->prepare($check_sql);
        $stmt_check->bind_param("s", $charactristics_type);
        $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 drone_charactristics (charactristics_id, charactristics, added_by, added_time)
                        VALUES ('NA', ?, ?, ?)";
        $stmt_insert = $conn->prepare($insert_sql);
        $stmt_insert->bind_param(
            "sss",
            $charactristics_type,
            $login_user_id,
            $currentdatetime
        );

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

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

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

        $charactristics_id       = trim($_POST['charactristics_id'] ?? '');
        $charactristics_type       = trim($_POST['charactristics_type'] ?? '');
        
        if ($charactristics_type === '') { $errors[] = 'charactristics_type'; }

        if (!empty($errors)) {
            echo json_encode(['status' => 'error', 'errors' => $errors]);
            exit;
        }
            
        $update_sql = "UPDATE drone_charactristics 
                    SET charactristics = ? 
                    WHERE charactristics_id = ?";
        $stmt_update = $conn->prepare($update_sql);
        $stmt_update->bind_param("ss",$charactristics_type, $charactristics_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_charactristics') {
        $id = $_POST['id'];
        $sql = "UPDATE drone_charactristics SET deleted_by = '$login_user_id', deleted_time = '$currentdatetime', deletion = 1 WHERE charactristics_id = '$id'";
        if ($conn->query($sql) === TRUE) {
            echo "11";
        } else {
            echo $conn->error;
        }
    } 
    else if ($type == 'add_usecase') {
        $errors = [];

        $usecase_id       = trim($_POST['usecase_id'] ?? '');
        $usecase_type       = trim($_POST['usecase_type'] ?? '');

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

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

        // --- Check duplicate ---
        $check_sql = "SELECT id 
                        FROM drone_usecase 
                        WHERE deletion = 0 
                            AND usecase = ?";
        $stmt_check = $conn->prepare($check_sql);
        $stmt_check->bind_param("s", $usecase_type);
        $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 drone_usecase (usecase_id, usecase, added_by, added_time)
                        VALUES ('NA', ?, ?, ?)";
        $stmt_insert = $conn->prepare($insert_sql);
        $stmt_insert->bind_param(
            "sss",
            $usecase_type,
            $login_user_id,
            $currentdatetime
        );

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

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

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

        $usecase_id       = trim($_POST['usecase_id'] ?? '');
        $usecase_type       = trim($_POST['usecase_type'] ?? '');
        
        if ($usecase_type === '') { $errors[] = 'usecase_type'; }

        if (!empty($errors)) {
            echo json_encode(['status' => 'error', 'errors' => $errors]);
            exit;
        }
            
        $update_sql = "UPDATE drone_usecase 
                    SET usecase = ? 
                    WHERE usecase_id = ?";
        $stmt_update = $conn->prepare($update_sql);
        $stmt_update->bind_param("ss",$usecase_type, $usecase_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_usecase') {
        $id = $_POST['id'];
        $sql = "UPDATE drone_usecase SET deleted_by = '$login_user_id', deleted_time = '$currentdatetime', deletion = 1 WHERE usecase_id = '$id'";
        if ($conn->query($sql) === TRUE) {
            echo "11";
        } else {
            echo $conn->error;
        }
    } 
    else if ($type == 'add_dronetype') {
        $errors = [];

        $type_id       = trim($_POST['type_id'] ?? '');
        $drone_type       = trim($_POST['drone_type'] ?? '');
        $category       = trim($_POST['category'] ?? '');
        $charactristics = isset($_POST['charactristics']) ? $_POST['charactristics'] : [];
        $usecases = isset($_POST['usecases']) ? $_POST['usecases'] : [];

        if ($drone_type === '') { $errors[] = 'drone_type'; }
        if ($category === '') { $errors[] = 'category'; }

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

        // --- Check duplicate ---
        $check_sql = "SELECT id 
                        FROM type_of_drones 
                        WHERE deletion = 0 
                            AND type_of_drone = ?";
        $stmt_check = $conn->prepare($check_sql);
        $stmt_check->bind_param("s", $drone_type);
        $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 type_of_drones (type_id, type_of_drone, category, added_by, added_time)
                        VALUES ('NA', ?, ?, ?, ?)";
        $stmt_insert = $conn->prepare($insert_sql);
        $stmt_insert->bind_param(
            "ssss",
            $drone_type,
            $category,
            $login_user_id,
            $currentdatetime
        );

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

            if (!empty($charactristics)) {
                foreach ($charactristics as $charactristic) {
                    $insert_dt_sql = "INSERT INTO type_drone_charactristics 
                        (drone_type, charactristics, added_by, added_time)
                        VALUES (?, ?, ?, ?)";
                    $stmt_dt = $conn->prepare($insert_dt_sql);
                    $stmt_dt->bind_param("ssss", $type_id, $charactristic, $login_user_id, $currentdatetime);
                    $stmt_dt->execute();
                }
            }
            
            if (!empty($usecases)) {
                foreach ($usecases as $usecase) {
                    $insert_ct_sql = "INSERT INTO type_drone_usecase 
                        (drone_type, usecase, added_by, added_time)
                        VALUES (?, ?, ?, ?)";
                    $stmt_ct = $conn->prepare($insert_ct_sql);
                    $stmt_ct->bind_param("ssss", $type_id, $usecase, $login_user_id, $currentdatetime);
                    $stmt_ct->execute();
                }
            }

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

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

        $type_id       = trim($_POST['type_id'] ?? '');
        $drone_type       = trim($_POST['drone_type'] ?? '');
        $category       = trim($_POST['category'] ?? '');
        $charactristics = isset($_POST['charactristics']) ? $_POST['charactristics'] : [];
        $usecases = isset($_POST['usecases']) ? $_POST['usecases'] : [];

        if ($drone_type === '') { $errors[] = 'drone_type'; }
        if ($category === '') { $errors[] = 'category'; }

        if (!empty($errors)) {
            echo json_encode(['status' => 'error', 'errors' => $errors]);
            exit;
        }
            
        $update_sql = "UPDATE type_of_drones 
                    SET type_of_drone = ?, category = ? 
                    WHERE type_id = ?";
        $stmt_update = $conn->prepare($update_sql);
        $stmt_update->bind_param("sss",$drone_type, $category, $type_id);
        if ($stmt_update->execute()) {

            $existing_charactristics = [];

            $sql = "SELECT charactristics, deletion 
                    FROM type_drone_charactristics 
                    WHERE drone_type = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("s", $type_id);
            $stmt->execute();
            $res = $stmt->get_result();

            while ($row = $res->fetch_assoc()) {
                $existing_charactristics[$row['charactristics']] = $row['deletion'];
            }

            $new_charactristics = $charactristics; 
            
            foreach ($new_charactristics as $charactristic) { 
                if (!isset($existing_charactristics[$charactristic])) {
                    // Completely new → INSERT
                    $sql = "INSERT INTO type_drone_charactristics 
                            (drone_type, charactristics, deletion, added_by, added_time)
                            VALUES (?, ?, 0, ?, ?)";
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("ssss", $type_id, $charactristic, $login_user_id, $currentdatetime);
                    $stmt->execute();

                } elseif ($existing_charactristics[$charactristic] == 1) {
                    // Was deleted → RESTORE
                    $sql = "UPDATE type_drone_charactristics 
                            SET deletion = 0 
                            WHERE drone_type = ? AND charactristics = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("ss", $type_id, $charactristic);
                    $stmt->execute();
                }
            }

            foreach ($existing_charactristics as $charactristic => $del_status) { 
                if ($del_status == 0 && !in_array($charactristic, $new_charactristics)) {
                    // Previously active, now removed
                    $sql = "UPDATE type_drone_charactristics 
                            SET deletion = 1 
                            WHERE drone_type = ? AND charactristics = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("ss", $type_id, $charactristic);
                    $stmt->execute();
                }
            }

            $existing_usecases = [];

            $sql = "SELECT usecase, deletion 
                    FROM type_drone_usecase 
                    WHERE drone_type = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("s", $type_id);
            $stmt->execute();
            $res = $stmt->get_result();

            while ($row = $res->fetch_assoc()) {
                $existing_usecases[$row['usecase']] = $row['deletion'];
            }

            $new_usecases = $usecases; 
            
            foreach ($new_usecases as $usecase) { 
                if (!isset($existing_usecases[$usecase])) {
                    // Completely new → INSERT
                    $sql = "INSERT INTO type_drone_usecase 
                            (drone_type, usecase, deletion, added_by, added_time)
                            VALUES (?, ?, 0, ?, ?)";
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("ssss", $type_id, $usecase, $login_user_id, $currentdatetime);
                    $stmt->execute();

                } elseif ($existing_usecases[$usecase] == 1) {
                    // Was deleted → RESTORE
                    $sql = "UPDATE type_drone_usecase 
                            SET deletion = 0 
                            WHERE drone_type = ? AND usecase = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("ss", $type_id, $usecase);
                    $stmt->execute();
                }
            }

            foreach ($existing_usecases as $usecase => $del_status) { 
                if ($del_status == 0 && !in_array($usecase, $new_usecases)) {
                    // Previously active, now removed
                    $sql = "UPDATE type_drone_usecase 
                            SET deletion = 1 
                            WHERE drone_type = ? AND usecase = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("ss", $type_id, $usecase);
                    $stmt->execute();
                }
            }

            echo json_encode(['status' => 'success', 'code' => 11]);
        } else {
            echo json_encode(['status' => 'error', 'message' => $conn->error, 'code' => 00]);
        }
        
    }
    else if ($type == 'delete_dronetype') {
        $id = $_POST['id'];
        $sql = "UPDATE type_of_drones SET deleted_by = '$login_user_id', deleted_time = '$currentdatetime', deletion = 1 WHERE type_id = '$id'";
        if ($conn->query($sql) === TRUE) {
            $sql = "UPDATE type_drone_charactristics SET deleted_by = '$login_user_id', deleted_time = '$currentdatetime', deletion = 1 WHERE drone_type = '$id'";
            if ($conn->query($sql) === TRUE) {
                $sql = "UPDATE type_drone_usecase SET deleted_by = '$login_user_id', deleted_time = '$currentdatetime', deletion = 1 WHERE drone_type = '$id'";
                if ($conn->query($sql) === TRUE) {
                    echo "11";
                } else {
                    echo $conn->error;
                } 
            } else {
                echo $conn->error;
            } 
        } else {
            echo $conn->error;
        }
    } 
?>