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

$rid         = (int)($_POST['receipt_id'] ?? 0);
$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'] ?? [];
$qtys     = $_POST['quantity'] ?? [];
$units    = $_POST['unit'] ?? [];
$prices   = $_POST['unit_price'] ?? [];

if ($rid <= 0 || $supplier_id <= 0) die('Nedostaju podaci.');

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

$mysqli->begin_transaction();

try {
    // Update header
    $stmt = $mysqli->prepare("UPDATE receipts SET supplier_id=?, receipt_date=?, doc_no=?, note=? WHERE id=?");
    $stmt->bind_param('isssi', $supplier_id, $receipt_date, $doc_no, $note, $rid);
    $stmt->execute();
    $stmt->close();

    // Replace items
    $mysqli->query("DELETE FROM receipt_items WHERE receipt_id=".(int)$rid);

    $stmtI = $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++) {
        $iid = (int)($item_ids[$i] ?? 0);
        $q   = (float)($qtys[$i] ?? 0);
        $u   = trim($units[$i] ?? '');
        $p   = (float)str_replace(',', '.', (string)($prices[$i] ?? 0));

        if ($iid > 0 && $q > 0 && $u !== '') {
            $stmtI->bind_param('iidsd', $rid, $iid, $q, $u, $p);
            $stmtI->execute();
        }
    }
    $stmtI->close();

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