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

$project_id = (int)($_POST['project_id'] ?? 0);
$usage_date_input = trim($_POST['usage_date'] ?? '');
$note = trim($_POST['note'] ?? '');

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

if ($project_id <= 0 || !$usage_date_input || empty($item_ids)) {
    die('Nedostaju podaci.');
}
$dt = DateTime::createFromFormat('d.m.Y', $usage_date_input);
if (!$dt) {
    die('Neispravan datum.');
}
$usage_date = $dt->format('Y-m-d');

// provjeri projekt i status
$stmtP = $mysqli->prepare('SELECT project_status FROM projects WHERE id = ?');
$stmtP->bind_param('i', $project_id);
$stmtP->execute();
$stmtP->bind_result($status);
if (!$stmtP->fetch()) {
    $stmtP->close();
    die('Projekt ne postoji.');
}
$stmtP->close();
if ($status === 'closed') {
    die('Projekt je dovršen – nije moguće unositi novi utrošak.');
}

$stmt = $mysqli->prepare('INSERT INTO consumption_orders (project_id, usage_date, note) VALUES (?,?,?)');
$stmt->bind_param('iss', $project_id, $usage_date, $note);
$stmt->execute();
$order_id = $stmt->insert_id;
$stmt->close();

$stmtItem = $mysqli->prepare('INSERT INTO consumption_items (order_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', $order_id, $item_id, $qty, $unit);
        $stmtItem->execute();
    }
}
$stmtItem->close();

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