<?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;
}

$itemId = (int)($_POST['item_id'] ?? 0);
$qty = (float)($_POST['qty'] ?? 0);
$rate = (float)($_POST['rate'] ?? 0);
$total = (float)($_POST['total'] ?? 0);
$type = trim($_POST['type'] ?? '');
$reference = trim($_POST['reference'] ?? '');
$remarks = trim($_POST['remarks'] ?? '');
$stockDate = trim($_POST['stock_date'] ?? '');

if ($itemId <= 0) {
    die('Invalid item selected.');
}

if ($qty <= 0) {
    die('Quantity must be greater than zero.');
}

if (!in_array($type, ['IN', 'OUT'])) {
    die('Invalid stock type.');
}

if (empty($stockDate)) {
    die('Stock date is required.');
}

/*
    Load item
*/
$stmt = $db->prepare("
    SELECT
        id,
        stock,
        unit_id
    FROM items
    WHERE id = ?
");

$stmt->execute([$itemId]);
$item = $stmt->fetch(PDO::FETCH_ASSOC);

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

$currentStock = (float)$item['stock'];
$unitId = $item['unit_id'];

$db->beginTransaction();

try {

    /*
        Stock calculation
    */
    if ($type === 'OUT') {

        if ($qty > $currentStock) {
            throw new Exception('Insufficient stock.');
        }

        $newStock = $currentStock - $qty;

    } else {

        $newStock = $currentStock + $qty;
    }

    /*
        Update item stock
    */
    $stmt = $db->prepare("
        UPDATE items
        SET stock = ?
        WHERE id = ?
    ");

    $stmt->execute([
        $newStock,
        $itemId
    ]);

    /*
        Insert stock entry
    */
    $stmt = $db->prepare("
        INSERT INTO stock_entries
        (
            item_id,
            qty,
            rate,
            total,
            type,
            reference,
            remarks,
            created_at,
            unit_id,
            stock_date
        )
        VALUES
        (?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?)
    ");

    $stmt->execute([
        $itemId,
        $qty,
        $rate,
        $total,
        $type,
        $reference,
        $remarks,
        $unitId,
        $stockDate
    ]);

    $db->commit();

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

} catch (Exception $e) {

    $db->rollBack();
    die($e->getMessage());
}
?>