<?php
require_once '../includes/auth.php';
require_once '../includes/db.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$action = $data['action'] ?? '';

switch ($action) {
    case 'save':
        $item = $data['item'];
        $id = $item['id'] ?? '';
        $sku = $item['sku'] ?? '';
        $company_id = $_SESSION['company_id'];
        $branch_id = $item['branch_id'] ?? null;
        $supplierId = !empty($item['supplier_id']) ? $item['supplier_id'] : null;
        
        // Validate SKU format: SKU- followed by 8 digits
        if (!preg_match('/^SKU-\d{8}$/', $sku)) {
            echo json_encode(['success' => false, 'message' => 'Invalid SKU format. Must be SKU-XXXXXXXX (8 digits)']);
            exit;
        }

        // Check for uniqueness
        $existing = fetch("SELECT id FROM inventory_items WHERE sku = ? AND id != ?", [$sku, $id]);
        if ($existing) {
            echo json_encode(['success' => false, 'message' => 'This SKU is already in use by another item']);
            exit;
        }
        
        if ($id) {
            $addition = floatval($item['stock_addition'] ?? 0);
            $unitPrice = floatval($item['buying_unit_price'] ?? 0);
            $sql = "UPDATE inventory_items SET sku=?, name=?, category=?, stock=stock + ?, unit=?, buying_unit_price=?, min_level=?, supplier_id=?, status=?, branch_id=? WHERE id=? AND company_id=?";
            query($sql, [$item['sku'], $item['name'], $item['category'], $addition, $item['unit'], $unitPrice, $item['min_level'], $supplierId, $item['status'], $branch_id, $id, $company_id]);
            echo json_encode(['success' => true, 'message' => 'Inventory item updated and stock topped up']);
        } else {
            $initialStock = floatval($item['stock_addition'] ?? 0);
            $unitPrice = floatval($item['buying_unit_price'] ?? 0);
            $sql = "INSERT INTO inventory_items (company_id, branch_id, sku, name, category, stock, unit, buying_unit_price, min_level, supplier_id, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            query($sql, [$company_id, $branch_id, $item['sku'], $item['name'], $item['category'], $initialStock, $item['unit'], $unitPrice, $item['min_level'], $supplierId, $item['status']]);
            echo json_encode(['success' => true, 'message' => 'New inventory item added with initial stock']);
        }
        break;

    case 'delete':
        $id = $data['id'];
        $company_id = $_SESSION['company_id'];
        query("DELETE FROM inventory_items WHERE id = ? AND company_id = ?", [$id, $company_id]);
        echo json_encode(['success' => true, 'message' => 'Item deleted from inventory']);
        break;

    case 'withdraw':
        $id = $data['id'];
        $amount = floatval($data['amount']);
        $reason = $data['reason'] ?? '';
        $company_id = $_SESSION['company_id'];
        
        if ($amount <= 0) {
            echo json_encode(['success' => false, 'message' => 'Withdraw amount must be greater than zero']);
            exit;
        }

        if (empty(trim($reason))) {
            echo json_encode(['success' => false, 'message' => 'Comments are mandatory for withdrawals']);
            exit;
        }
        
        $item = fetch("SELECT name, stock, unit FROM inventory_items WHERE id = ? AND company_id = ?", [$id, $company_id]);
        if (!$item) {
            echo json_encode(['success' => false, 'message' => 'Item not found']);
            exit;
        }
        
        if ($item['stock'] < $amount) {
            echo json_encode(['success' => false, 'message' => 'Insufficient stock. Available: ' . $item['stock'] . ' ' . $item['unit']]);
            exit;
        }
        
        query("UPDATE inventory_items SET stock = stock - ? WHERE id = ? AND company_id = ?", [$amount, $id, $company_id]);
        
        // Log to audit with item name and SKU
        require_once '../includes/functions.php'; // Ensure logAudit is available
        logAudit('INVENTORY_WITHDRAW', "Withdrew $amount {$item['unit']} from '{$item['name']}'. Reason: $reason");
        
        echo json_encode(['success' => true, 'message' => 'Stock withdrawn successfully']);
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}
