<?php
session_start();

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

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

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

$stockDate = trim($_POST['stock_date'] ?? '');
$reference = trim($_POST['reference'] ?? '');
$remarks = trim($_POST['remarks'] ?? '');

$itemIds = $_POST['item_id'] ?? [];
$unitIds = $_POST['unit_id'] ?? [];
$qtys = $_POST['qty'] ?? [];
$rates = $_POST['rate'] ?? [];
$totals = $_POST['total'] ?? [];

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

if (empty($itemIds)) {
    die('No stock rows found.');
}

$db->beginTransaction();

try {

    for ($i = 0; $i < count($itemIds); $i++) {

        $itemId = (int)$itemIds[$i];
        $unitId = !empty($unitIds[$i]) ? (int)$unitIds[$i] : null;
        $qty = (float)$qtys[$i];
        $rate = (float)$rates[$i];
        $total = (float)$totals[$i];

        if ($itemId <= 0) {
            continue;
        }

        if ($qty <= 0) {
            throw new Exception('Invalid quantity in one of the rows.');
        }

        /*
            Get current stock
        */
        $stmt = $db->prepare("
            SELECT stock
            FROM items
            WHERE id = ?
        ");

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

        if (!$item) {
            throw new Exception('Item not found.');
        }

        $currentStock = (float)$item['stock'];
        $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,
            'IN',
            $reference,
            $remarks,
            $unitId,
            $stockDate
        ]);
    }

    $db->commit();

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

} catch (Exception $e) {

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