<?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']     ?? [];
$prices     = $_POST['unit_price'] ?? [];

if ($supplier_id <= 0) { die('Nedostaje dobavljač.'); }

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

$mysqli->begin_transaction();

try {
    // Header primke
    $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();

    // Stavke primke
    $stmtItem = $mysqli->prepare("INSERT INTO receipt_items (receipt_id, item_id, quantity, unit, unit_price) VALUES (?,?,?,?,?)");

    $count = count($item_ids);
    for ($i=0; $i<$count; $i++) {
        $item_id = (int)($item_ids[$i] ?? 0);
        $qty     = (float)($quantities[$i] ?? 0);
        $unit    = trim($units[$i] ?? '');
        $price   = (float)str_replace(',', '.', (string)($prices[$i] ?? 0));

        if ($item_id > 0 && $qty > 0 && $unit !== '') {
            $stmtItem->bind_param('iidsd', $receipt_id, $item_id, $qty, $unit, $price);
            $stmtItem->execute();
        }
    }
    $stmtItem->close();

    $mysqli->commit();
    header('Location: receipts.php?msg='.urlencode('Primka spremljena.'));
    exit;
} catch (Throwable $e) {
    $mysqli->rollback();
    die('Greška: '.$e->getMessage());
}
