<?php
session_start();
include '../layouts/dbconn.php';

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

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

$data        = json_decode(file_get_contents('php://input'), true);
$visit_id    = (int)($data['visit_id']   ?? 0);
$patient_id  = (int)($data['patient_id'] ?? 0);
$queue_id    = (int)($data['queue_id']   ?? 0);
$meds        = $data['medications']      ?? [];
$nurse_id    = (int)$_SESSION['user_id'];

if (!$visit_id || !$patient_id || empty($meds)) {
    echo json_encode(['success' => false, 'message' => 'Missing required data']);
    exit();
}

$stmt = $conn->prepare("
    INSERT INTO nurse_medication_requests
        (visit_id, patient_id, queue_id, inventory_id,
         quantity_requested, reason, requested_by, status, created_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, 'PENDING', NOW())
");

if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'DB prepare error: ' . $conn->error]);
    exit();
}

$saved  = 0;
$errors = [];

foreach ($meds as $med) {
    // JS sends item_id which maps to inventory_id in pharmacy_inventory
    $inventory_id = (int)($med['item_id']  ?? 0);
    $qty          = max(1, (int)($med['quantity'] ?? 1));
    $reason       = trim($med['reason'] ?? '');

    if (!$inventory_id) {
        $errors[] = 'Invalid inventory ID';
        continue;
    }

    // Verify stock is still sufficient before inserting
    $chk = $conn->prepare("
        SELECT inventory_id, item_name, current_stock
        FROM pharmacy_inventory
        WHERE inventory_id = ? AND is_active = 1
    ");
    $chk->bind_param("i", $inventory_id);
    $chk->execute();
    $row = $chk->get_result()->fetch_assoc();
    $chk->close();

    if (!$row) {
        $errors[] = "Item not found (ID: $inventory_id)";
        continue;
    }
    if ($row['current_stock'] < $qty) {
        $errors[] = $row['item_name'] . ': only ' . $row['current_stock'] . ' in stock';
        continue;
    }

    $q_id_val = $queue_id ?: null;
    $stmt->bind_param(
        "iiiisis",
        $visit_id, $patient_id, $q_id_val,
        $inventory_id, $qty, $reason, $nurse_id
    );

    if ($stmt->execute()) {
        $saved++;
    } else {
        $errors[] = 'Save failed: ' . $stmt->error;
    }
}

$stmt->close();

if ($saved > 0) {
    $msg = $saved . ' medication request' . ($saved > 1 ? 's' : '') . ' sent to pharmacy.';
    if ($errors) $msg .= ' Note: ' . implode('; ', $errors);
    echo json_encode(['success' => true, 'message' => $msg, 'saved' => $saved]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'No requests saved. ' . implode('; ', $errors)
    ]);
}