<?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;
}

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

$item_ids   = $_POST['item_id'] ?? [];
$qtys       = $_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'] ?? [];


$delete_media_ids = $_POST['delete_media_ids'] ?? [];
if ($order_id <= 0) die('Nedostaje ID naloga.');

$dt = DateTime::createFromFormat('d.m.Y', $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 status projekta na trenutnom nalogu (ako je dovršen -> zabrani izmjene)
$stmt = $mysqli->prepare("
  SELECT p.project_status
  FROM consumption_orders o
  JOIN projects p ON p.id=o.project_id
  WHERE o.id=?
");
$stmt->bind_param('i', $order_id);
$stmt->execute();
$stmt->bind_result($pstatus);
$stmt->fetch();
$stmt->close();
if ($pstatus === 'closed') {
  header('Location: orders.php?msg=' . urlencode('Projekt je dovršen - izmjena nije dopuštena.'));
  exit;
}

$mysqli->begin_transaction();

try {
    // update header
    $stmt = $mysqli->prepare("UPDATE consumption_orders SET project_id=?, usage_date=?, note=? WHERE id=?");
    $stmt->bind_param('issi', $project_id, $usage_date, $note, $order_id);
    $stmt->execute();
    $stmt->close();

    // delete old items
    $mysqli->query("DELETE FROM consumption_items WHERE order_id=".(int)$order_id);
    $mysqli->query("DELETE FROM consumption_labor WHERE order_id=".(int)$order_id);


    // insert new
    if ($hasConsumptionItemWarranty) {
        $stmtI = $mysqli->prepare("INSERT INTO consumption_items (order_id, item_id, quantity, unit, has_warranty, warranty_months) VALUES (?,?,?,?,?,?)");
    } else {
        $stmtI = $mysqli->prepare("INSERT INTO consumption_items (order_id, item_id, quantity, unit) VALUES (?,?,?,?)");
    }
    for ($i=0; $i<count($item_ids); $i++) {
        $iid = (int)$item_ids[$i];
        $q   = (float)$qtys[$i];
        $u   = trim($units[$i] ?? '');
        $hasWarranty = !empty($has_warranty_arr[$i]) ? 1 : 0;
        $warrantyMonths = $hasWarranty ? max(0, (int)($warranty_months_arr[$i] ?? 0)) : 0;
        if ($iid>0 && $q>0 && $u!=='') {
            if ($hasConsumptionItemWarranty) {
                $stmtI->bind_param('iidsii', $order_id, $iid, $q, $u, $hasWarranty, $warrantyMonths);
            } else {
                $stmtI->bind_param('iids', $order_id, $iid, $q, $u);
            }
            $stmtI->execute();
        }
    }
    $stmtI->close();


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


    // obriši označene medije (i datoteke)
    if (!empty($delete_media_ids)) {
        delete_order_media($mysqli, (int)$order_id, (array)$delete_media_ids);
    }

    $mysqli->commit();

    // media upload (slike / video) - nakon commit-a
    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) {
        // ignoriraj greške medija
    }

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