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

function column_exists(mysqli $mysqli, string $table, string $column): bool {
    $safeTable = $mysqli->real_escape_string($table);
    $safeColumn = $mysqli->real_escape_string($column);
    $res = $mysqli->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeColumn}'");
    return $res && $res->num_rows > 0;
}

$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']     ?? [];
$has_warranty_arr = $_POST['has_warranty'] ?? [];
$warranty_months_arr = $_POST['warranty_months'] ?? [];

$emp_ids = $_POST['emp_id'] ?? [];
$hours   = $_POST['hours'] ?? [];
$rates   = $_POST['rate'] ?? [];
$lnote   = $_POST['labor_note'] ?? [];

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');
$hasConsumptionItemWarranty = column_exists($mysqli, 'consumption_items', 'has_warranty') && column_exists($mysqli, 'consumption_items', 'warranty_months');

// 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();

if ($hasConsumptionItemWarranty) {
    $stmtItem = $mysqli->prepare('INSERT INTO consumption_items (order_id, item_id, quantity, unit, has_warranty, warranty_months) VALUES (?,?,?,?,?,?)');
} else {
    $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] ?? '');
    $hasWarranty = !empty($has_warranty_arr[$i]) ? 1 : 0;
    $warrantyMonths = $hasWarranty ? max(0, (int)($warranty_months_arr[$i] ?? 0)) : 0;
    if ($item_id > 0 && $qty > 0 && $unit !== '') {
        if ($hasConsumptionItemWarranty) {
            $stmtItem->bind_param('iidsii', $order_id, $item_id, $qty, $unit, $hasWarranty, $warrantyMonths);
        } else {
            $stmtItem->bind_param('iids', $order_id, $item_id, $qty, $unit);
        }
        $stmtItem->execute();
    }
}
$stmtItem->close();


// labor (radnici + sati)
if (!empty($emp_ids)) {
    $stmtL = $mysqli->prepare('INSERT INTO consumption_labor (order_id, employee_id, work_date, hours, hourly_rate, note) VALUES (?,?,?,?,?,?)');
    for ($i = 0; $i < count($emp_ids); $i++) {
        $eid = (int)$emp_ids[$i];
        $h   = (float)($hours[$i] ?? 0);
        $r   = (float)($rates[$i] ?? 0);
        $n   = trim($lnote[$i] ?? '');
        if ($eid > 0 && $h > 0) {
            $stmtL->bind_param('iisdds', $order_id, $eid, $usage_date, $h, $r, $n);
            $stmtL->execute();
        }
    }
    $stmtL->close();
}


// media upload (slike / video)
try {
    $uid = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : null;
    if (!empty($_FILES['media_files'])) {
        handle_order_media_uploads($mysqli, (int)$order_id, $_FILES['media_files'], $uid);
    }
} catch (Throwable $e) {
    // ne rušimo spremanje naloga zbog medija
}

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