<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$db = (new Database())->connect();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

$id = (int)($_POST['id'] ?? 0);

if ($id <= 0) {
    die('Invalid item ID.');
}

$name = trim($_POST['name'] ?? '');
$price = (float)($_POST['price'] ?? 0);
$gst = (float)($_POST['gst'] ?? 0);
$categoryId = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
$stock = (float)($_POST['stock'] ?? 0);
$barcode = trim($_POST['barcode'] ?? '');
$unitId = !empty($_POST['unit_id']) ? (int)$_POST['unit_id'] : null;
$typeId = !empty($_POST['type_id']) ? (int)$_POST['type_id'] : null;

if ($name === '') {
    die('Item name is required.');
}

/*
    Get existing image
*/
$stmt = $db->prepare("SELECT image_path FROM items WHERE id = ?");
$stmt->execute([$id]);
$existingItem = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$existingItem) {
    die('Item not found.');
}

$imagePath = $existingItem['image_path'];

/*
    Image Upload
*/
if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {

    $uploadDir = '../../assets/uploads/items/';

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $fileName = time() . '_' . basename($_FILES['image']['name']);
    $targetFile = $uploadDir . $fileName;

    $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $extension = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

    if (in_array($extension, $allowedExtensions)) {

        if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFile)) {

            /*
                Delete old image
            */
            if (!empty($existingItem['image_path'])) {
                $oldFile = '../../' . $existingItem['image_path'];

                if (file_exists($oldFile)) {
                    unlink($oldFile);
                }
            }

            $imagePath = 'assets/uploads/items/' . $fileName;
        }
    }
}

/*
    Update item
*/
$stmt = $db->prepare("
    UPDATE items
    SET
        name = ?,
        price = ?,
        gst = ?,
        category_id = ?,
        image_path = ?,
        stock = ?,
        barcode = ?,
        unit_id = ?,
        type_id = ?
    WHERE id = ?
");

$stmt->execute([
    $name,
    $price,
    $gst,
    $categoryId,
    $imagePath,
    $stock,
    $barcode,
    $unitId,
    $typeId,
    $id
]);

header('Location: index.php');
exit;
?>