<?php
include 'db.php';
include 'auth.php';
require_right('Edit Items');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)$_POST['id'];
    $item_code = trim($_POST['item_code']);
    $sku_number = trim($_POST['sku_number']);
    $name = trim($_POST['name']);
    $category_id = (int)$_POST['category_id'];
    $sub_category_id = (int)$_POST['sub_category_id'];
    $retail_price = (float)$_POST['retail_price'];
    $cost_price = (float)$_POST['cost_price'];
    $reorder_quantity = (int)$_POST['reorder_quantity'];
    $reorder_level = (int)$_POST['reorder_level'];
    $tax_type = $_POST['tax_type'];
    $tax_rate_id = !empty($_POST['tax_rate_id']) ? (int)$_POST['tax_rate_id'] : NULL;
    $item_type = $_POST['item_type'];
    $bulk_qty = $item_type === 'bulk' ? (int)$_POST['bulk_qty'] : NULL;
    $bulk_price = $item_type === 'bulk' ? (float)$_POST['bulk_price'] : NULL;
    $pkg_qty = $item_type === 'bulk' ? (int)$_POST['pkg_qty'] : NULL;
    $uom_id = $item_type === 'bulk' ? (int)$_POST['uom_id'] : NULL;
    $item_role = $_POST['item_role'];

    // Basic validation
    if (!$item_code || !$sku_number || !$name || !$retail_price || $cost_price === '' || !$tax_type || !$item_type || !$item_role) {
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            echo json_encode(['success' => false, 'error' => 'Please fill all required fields.']);
            exit;
        }
        header('Location: item_list.php?edit_error=1');
        exit;
    }

    // Check for duplicate item code (excluding current item)
    $check = $conn->prepare("SELECT id FROM items WHERE item_code = ? AND id != ?");
    $check->bind_param("si", $item_code, $id);
    $check->execute();
    $check->store_result();
    if ($check->num_rows > 0) {
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            echo json_encode(['success' => false, 'error' => 'Item code already exists.']);
            exit;
        }
        header('Location: item_list.php?edit_error=3');
        exit;
    }
    $check->close();

    // Handle image upload (optional)
    $product_image = null;
    if (!empty($_FILES['product_image']['name'])) {
        $target_dir = "assets/img/products/";
        $filename = basename($_FILES["product_image"]["name"]);
        $target_file = $target_dir . time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $filename);
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        if (in_array($imageFileType, ['jpg', 'jpeg', 'png', 'gif'])) {
            if (move_uploaded_file($_FILES["product_image"]["tmp_name"], $target_file)) {
                $product_image = basename($target_file);
            }
        }
    }

    // Build update query
    $sql = "UPDATE items SET item_code=?, sku_number=?, name=?, category_id=?, sub_category_id=?, retail_price=?, cost_price=?, reorder_quantity=?, reorder_level=?, tax_type=?, tax_rate_id=?, item_type=?, bulk_qty=?, bulk_price=?, pkg_qty=?, uom_id=?, item_role=?";
    $params = [
        $item_code, $sku_number, $name, $category_id, $sub_category_id, $retail_price, $cost_price, $reorder_quantity, $reorder_level,
        $tax_type, $tax_rate_id, $item_type, $bulk_qty, $bulk_price, $pkg_qty, $uom_id, $item_role
    ];
    $types = "sssiddddisisidiss";
    if ($product_image) {
        $sql .= ", product_image=?";
        $params[] = $product_image;
        $types .= "s";
    }
    $sql .= " WHERE id=?";
    $params[] = $id;
    $types .= "i";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $stmt->close();

    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
        echo json_encode(['success' => true]);
        exit;
    }
    header('Location: item_list.php?edited=1');
    exit;
}
header('Location: item_list.php?edit_error=2');
exit; 