<?php
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'Gagal memvalidasi ID Pesanan.'];

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/session.php';
require_once __DIR__ . '/../../lib/Auth.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!Auth::isLoggedIn()) {
    http_response_code(401);
    $response['message'] = 'Sesi berakhir. Silakan login kembali.';
    echo json_encode($response);
    exit;
}

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    error_log("PDO object not available in validate_user_order.php");
    $response['message'] = 'Koneksi database gagal.';
    echo json_encode($response);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    $response['message'] = 'Metode request tidak valid.';
    echo json_encode($response);
    exit;
}

try {
    $userId = $_SESSION['user_id'];
    $orderId = filter_input(INPUT_GET, 'order_id', FILTER_VALIDATE_INT);

    if (!$orderId) {
        http_response_code(400);
        $response['message'] = 'Format ID Pesanan tidak valid. Harap masukkan angka.';
        echo json_encode($response);
        exit;
    }

    $sql = "SELECT id FROM orders WHERE id = :order_id AND user_id = :user_id LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':order_id', $orderId, PDO::PARAM_INT);
    $stmt->bindParam(':user_id', $userId, PDO::PARAM_INT);
    $stmt->execute();

    if ($stmt->fetch()) {
        $response['success'] = true;
        $response['message'] = 'ID Pesanan valid.';
    } else {
        $response['success'] = false;
        $response['message'] = 'ID Pesanan tidak ditemukan atau bukan milik Anda. Mohon periksa kembali.';
    }

} catch (\PDOException $e) {
    error_log("Validate User Order DB Error: " . $e->getMessage());
    http_response_code(500);
    $response['message'] = "Terjadi kesalahan database saat validasi.";
} catch (\Throwable $e) {
    error_log("Validate User Order General Error: " . $e->getMessage());
    http_response_code(500);
    $response['message'] = "Terjadi kesalahan internal server.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
}

echo json_encode($response);
exit;
