<?php
require_once "config.php";
require_once "auth.php";
requireLogin();

header('Content-Type: application/json');

if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if (!isset($_POST['id']) || !isset($_POST['status'])) {
    echo json_encode(['success' => false, 'message' => 'Missing parameters']);
    exit();
}

$id = (int)$_POST['id'];
$status = $_POST['status'];

// Validacija statusa
$valid_statuses = ['Na čekanju', 'Nerasporedjeno', 'Predstoji', 'Završeno', 'Arhivirano', 'Odbijeno'];
if (!in_array($status, $valid_statuses)) {
    echo json_encode(['success' => false, 'message' => 'Invalid status']);
    exit();
}

try {
    $stmt = $conn->prepare("UPDATE voznje SET status = ? WHERE id = ?");
    if (!$stmt) {
        throw new Exception("Database prepare error: " . $conn->error);
    }

    $stmt->bind_param("si", $status, $id);
    if (!$stmt->execute()) {
        throw new Exception("Database execute error: " . $stmt->error);
    }

    if ($stmt->affected_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'No ride found with that ID']);
        exit();
    }

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
} 