<?php
require_once 'config.php';
require_login();
require_permission('receipts');

$supplier_id = (int)($_POST['supplier_id'] ?? 0);
$date_input  = trim($_POST['receipt_date'] ?? '');
$doc_no      = trim($_POST['doc_no'] ?? '');
$note        = trim($_POST['note'] ?? '');

$item_ids   = $_POST['item_id']  ?? [];
$quantities = $_POST['quantity'] ?? [];
$units      = $_POST['unit']     ?? [];

if ($supplier_id <= 0 || $date_input === '' || empty($item_ids)) {
    die('Nedostaju podaci.');
}

$dt = DateTime::createFromFormat('d.m.Y', $date_input);
if (!$dt) {
    die('Neispravan datum.');
}
$receipt_date = $dt->format('Y-m-d');

$stmt = $mysqli->prepare('INSERT INTO receipts (supplier_id, receipt_date, doc_no, note) VALUES (?,?,?,?)');
$stmt->bind_param('isss', $supplier_id, $receipt_date, $doc_no, $note);
$stmt->execute();
$receipt_id = $stmt->insert_id;
$stmt->close();

$stmtItem = $mysqli->prepare('INSERT INTO receipt_items (receipt_id, item_id, quantity, unit) VALUES (?,?,?,?)');
for ($i = 0; $i < count($item_ids); $i++) {
    $item_id = (int)$item_ids[$i];
    $qty     = (float)$quantities[$i];
    $unit    = trim($units[$i]);
    if ($item_id > 0 && $qty > 0 && $unit !== '') {
        $stmtItem->bind_param('iids', $receipt_id, $item_id, $qty, $unit);
        $stmtItem->execute();
    }
}
$stmtItem->close();

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