<?php
session_start();
include 'db.php';
include 'auth.php';
require_right('Add Item');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $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;
    $product_image = null;
    $item_role = $_POST['item_role'];


    // Basic validation
    if (!$item_code || !$sku_number || !$name || !$retail_price || !$cost_price || !$tax_type || !$item_type || !$item_role) {

        header("Location: item_list.php?error=1");
        exit;
    }

    // Check for duplicate item code
    $check = $conn->prepare("SELECT id FROM items WHERE item_code = ?");
    $check->bind_param("s", $item_code);
    $check->execute();
    $check->store_result();
    if ($check->num_rows > 0) {
        header("Location: item_list.php?error=2");
        exit;
    }

    // Handle image upload (optional)
    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));

        // Validate file type
        if (in_array($imageFileType, ['jpg', 'jpeg', 'png', 'gif'])) {
            if (move_uploaded_file($_FILES["product_image"]["tmp_name"], $target_file)) {
                $product_image = basename($target_file);
            }
        }
    }

    // Insert
    $stmt = $conn->prepare("INSERT INTO items 
    (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, product_image, item_role) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

    $stmt->bind_param("sssiddddisisidiiss", 
    $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, $product_image, $item_role);

    $stmt->execute();

    header("Location: item_list.php?added=1");
    exit;
}

header("Location: item_list.php");
exit;
