<?php
// request_details.kts.php
include 'shikanisha.kts.php'; // Your database connection file

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

// Initialize response array
$response = [
    'success' => false,
    'message' => 'Request ID parameter is required',
    'request' => null,
    'items' => []
];

try {
    // Validate request ID
    if (!isset($_GET['request_id']) || !is_numeric($_GET['request_id'])) {
        throw new Exception('Invalid request ID');
    }

    $request_id = (int)$_GET['request_id'];
    
    // 1. Get the request header information
    $header_sql = "SELECT request_id, date AS request_date, request_by AS user_name, status 
                   FROM requests 
                   WHERE request_id = ?";
    $header_stmt = $conn->prepare($header_sql);
    
    if ($header_stmt === false) {
        throw new Exception("Header prepare failed: " . $conn->error);
    }

    $header_stmt->bind_param("i", $request_id);
    if (!$header_stmt->execute()) {
        throw new Exception("Header execute failed: " . $header_stmt->error);
    }

    $header_result = $header_stmt->get_result();
    if ($header_result->num_rows === 0) {
        throw new Exception("No request found with ID: $request_id");
    }

    $response['request'] = $header_result->fetch_assoc();
    $header_stmt->close();

    // 2. Get the request items
    $items_sql = "SELECT product_name, quantity, category 
                  FROM request_items 
                  WHERE request_id = ?";
    $items_stmt = $conn->prepare($items_sql);
    
    if ($items_stmt === false) {
        throw new Exception("Items prepare failed: " . $conn->error);
    }

    $items_stmt->bind_param("i", $request_id);
    if (!$items_stmt->execute()) {
        throw new Exception("Items execute failed: " . $items_stmt->error);
    }

    $items_result = $items_stmt->get_result();
    while ($row = $items_result->fetch_assoc()) {
        $response['items'][] = $row;
    }

    $response['success'] = true;
    $response['message'] = '';
    $items_stmt->close();

} catch (Exception $e) {
    $response['message'] = $e->getMessage();
    error_log("Request Details Error: " . $e->getMessage());
} finally {
    // Ensure proper JSON encoding
    echo json_encode($response, JSON_PRETTY_PRINT);
    if (isset($conn)) $conn->close();
    exit;
}
?>