<?php
include("dbconn.php");
$con = dbconn();
mysqli_set_charset($con, "utf8mb4");

header('Content-Type: application/json; charset=utf-8');

// Enable error reporting for debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Decode JSON input
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, true);

// Validate action
if (!isset($input['action'])) {
    echo json_encode(["success" => "false", "error" => "Action is required"]);
    exit;
}

$action = $input['action'];

// Common variable
$com_id = $input['com_id'] ?? null;
$item_id = $input['item_id'] ?? null;

$response = [];

switch ($action) {

    // Fetch All
    case "fetchAll":
        if (!$com_id) {
            echo json_encode(["success" => "false", "error" => "com_id is required"]);
            exit;
        }

        $stmt = $con->prepare("SELECT a.*, b.category_name 
    FROM item_details a
    JOIN item_category b ON a.category_id = b.category_id
    WHERE a.com_id = ?
    ORDER BY a.item_name");
        $stmt->bind_param("s", $com_id);
        $stmt->execute();
        $result = $stmt->get_result();

        $data = [];
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }

        echo json_encode($data);
        $stmt->close();
        break;

    // Fetch By ID
    case "fetchById":
        if (!$com_id || !$item_id) {
            echo json_encode(["success" => "false", "error" => "com_id and item_id are required"]);
            exit;
        }

        $stmt = $con->prepare("SELECT * FROM item_details WHERE com_id = ? AND item_id = ?");
        $stmt->bind_param("ss", $com_id, $item_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $data = $result->fetch_assoc();

        if ($data) {
            echo json_encode($data);
        } else {
            echo json_encode(["success" => "false", "error" => "Item not found"]);
        }
        $stmt->close();
        break;

    //  Insert
    case "insert":
    $fields = [
        "item_name", "category_id", "item_brand", "item_model",
        "item_size", "item_color", "item_unit", "item_cost",
        "item_trading_price", "item_barcode", "item_flag",
        "create_by", "imageData", "imageExt"
    ];

    foreach ($fields as $field) {
        if (!isset($input[$field])) {
            echo json_encode(["success" => "false", "error" => "$field is required"]);
            exit;
        }
    }

    // Assign variables
    $item_name = $input["item_name"];
    $category_id = $input["category_id"];
    $item_brand = $input["item_brand"];
    $item_model = $input["item_model"];
    $item_size = $input["item_size"];
    $item_color = $input["item_color"];
    $item_unit = $input["item_unit"];
    $item_cost = $input["item_cost"];
    $item_trading_price = $input["item_trading_price"];
    $item_barcode = $input["item_barcode"];
    $item_flag = $input["item_flag"];
    $create_by = $input["create_by"];
    $imageData = $input["imageData"];
    $imageExt = $input["image_name"]; // Extension from Flutter

    // Duplicate check
    $checkStmt = $con->prepare("SELECT item_id FROM item_details WHERE com_id = ? AND item_name = ?");
    $checkStmt->bind_param("ss", $com_id, $item_name);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();

    if ($checkResult->num_rows > 0) {
        echo json_encode(["duplicate" => true]);
        exit;
    }

    // Generate new item_id = com_id + next number (start from 1001)
    $prefix = $com_id;
    $stmtMax = $con->prepare("
        SELECT MAX(CAST(SUBSTRING(item_id, LENGTH(?) + 1) AS UNSIGNED)) AS max_num 
        FROM item_details 
        WHERE item_id LIKE CONCAT(?, '%')
    ");
    $stmtMax->bind_param("ss", $prefix, $prefix);
    $stmtMax->execute();
    $resultMax = $stmtMax->get_result();
    $row = $resultMax->fetch_assoc();
    $nextNumber = ($row['max_num'] ?? 1000) + 1;
    $item_id = $prefix . $nextNumber;
    $stmtMax->close();

    // Image handling
    if (empty($imageData)) {
        $image_name = "noImage.jpg";
        $path = "../image/item_image/" . $image_name;
        } else {
        $image_name = $item_id . "_" . $item_color . "." . $imageExt;
        $path = "../image/item_image/" . $image_name;
    }

    // Insert data
    $stmt = $con->prepare("
        INSERT INTO item_details (
            com_id, category_id, item_name, item_brand, item_model,
            item_size, item_color, item_unit, item_cost, item_trading_price,
            item_barcode, item_flag, image_name, item_id, create_by
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $stmt->bind_param(
        "ssssssssddsssss",
        $com_id,
        $category_id,
        $item_name,
        $item_brand,
        $item_model,
        $item_size,
        $item_color,
        $item_unit,
        $item_cost,
        $item_trading_price,
        $item_barcode,
        $item_flag,
        $image_name,
        $item_id,
        $create_by
    );

    if ($stmt->execute()) {
        if (!empty($imageData)) {
            file_put_contents($path, base64_decode($imageData));
        }
        $response["success"] = "true";
        $response["item_id"] = $item_id;
        $response["image_name"] = $image_name;
    } else {
        $response["success"] = "false";
        $response["error"] = $stmt->error;
    }

    echo json_encode($response);
    $stmt->close();
    $checkStmt->close();
    break;


    // ================================
    //  Update
    // ================================
   case "update":
    $fields = [
        "com_id", "item_id", "item_name", "item_brand", "item_model",
        "item_size", "item_color", "item_unit", "item_cost",
        "item_trading_price", "item_barcode", "item_flag",
        "image_name", "image_name_old", "imageData", "update_by"
    ];

    foreach ($fields as $field) {
        if (!isset($input[$field])) {
            echo json_encode(["success" => "false", "error" => "$field is required"]);
            exit;
        }
    }

    // Variables
    $com_id = $input["com_id"];
    $item_id = $input["item_id"];
    $item_name = $input["item_name"];
    $item_brand = $input["item_brand"];
    $item_model = $input["item_model"];
    $item_size = $input["item_size"];
    $item_color = $input["item_color"];
    $item_unit = $input["item_unit"];
    $item_cost = $input["item_cost"];
    $item_trading_price = $input["item_trading_price"];
    $item_barcode = $input["item_barcode"];
    $item_flag = $input["item_flag"];
    $image_name = $input["image_name"];
    $image_name_old = $input["image_name_old"];
    $imageData = $input["imageData"];
    $update_by = $input["update_by"];

    $path = "image/item_image/" . $image_name;
    $oldPath = "image/item_image/" . $image_name_old;

    // Base SQL (always update other fields)
    $stmt = $con->prepare("
        UPDATE item_details SET
            item_name = ?, item_brand = ?, item_model = ?, item_size = ?, item_color = ?, item_unit = ?,
            item_cost = ?, item_trading_price = ?, item_barcode = ?, item_flag = ?, image_name = ?, update_by = ?
        WHERE com_id = ? AND item_id = ?
    ");

    $stmt->bind_param(
        "ssssssddssssss",
        $item_name,
        $item_brand,
        $item_model,
        $item_size,
        $item_color,
        $item_unit,
        $item_cost,
        $item_trading_price,
        $item_barcode,
        $item_flag,
        $image_name,
        $update_by,
        $com_id,
        $item_id
    );

    if ($stmt->execute()) {
        // тЬЕ Image handling logic
        if (!empty($imageData)) {
             if ($image_name_old == "noImage.jpg") {
                // Old image was default тЖТ just save new image
                file_put_contents($path, base64_decode($imageData));
            } else {
                // Delete old image first if exists
                if (file_exists($oldPath)) {
                    unlink($oldPath);
                }
                // Then save new image
                file_put_contents($path, base64_decode($imageData));
            }
        }
        // else same image, do nothing

        echo json_encode(["success" => "true"]);
    } else {
        echo json_encode(["success" => "false", "error" => $stmt->error]);
    }

    $stmt->close();
    break;


    // ================================
    //  Delete
    // ================================
    case "delete":
        if (empty($input["com_id"]) || empty($input["item_id"])) {
            echo json_encode(["success" => "false", "error" => "com_id and item_id are required"]);
            exit;
        }

        $com_id = $input["com_id"];
        $item_id = $input["item_id"];
        $image_name = $input["image_name"] ?? "";

        $stmt = $con->prepare("DELETE FROM item_details WHERE com_id = ? AND item_id = ?");
        $stmt->bind_param("ss", $com_id, $item_id);

        if ($stmt->execute()) {
            // Delete image if exists
            if (!empty($image_name)) {
                $path = "image/item_image/" . $image_name;
                if (file_exists($path)) {
                    unlink($path);
                }
            }
            echo json_encode(["success" => "true"]);
        } else {
            echo json_encode(["success" => "false", "error" => $stmt->error]);
        }

        $stmt->close();
        break;

    default:
        echo json_encode(["success" => "false", "error" => "Invalid action"]);
        break;
}
?>
