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

$pharmacy_roles = ['CHIEF_PHARMACIST', 'PHARMACIST', 'PHARMACY_TECH', 'LOCUM_PHARMACIST'];
if (!in_array($_SESSION['role_code'] ?? '', $pharmacy_roles)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

$data       = json_decode(file_get_contents('php://input'), true);
$request_id = (int)($data['request_id'] ?? 0);
$user_id    = (int)$_SESSION['user_id'];

if (!$request_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid request ID']);
    exit();
}

/* Verify the request exists and is still PENDING */
$chk = $conn->prepare("SELECT request_id, inventory_id, quantity_requested, status FROM nurse_medication_requests WHERE request_id = ?");
$chk->bind_param("i", $request_id);
$chk->execute();
$req = $chk->get_result()->fetch_assoc();
$chk->close();

if (!$req) {
    echo json_encode(['success' => false, 'message' => 'Request not found']);
    exit();
}
if ($req['status'] !== 'PENDING') {
    echo json_encode(['success' => false, 'message' => 'Request is already ' . $req['status']]);
    exit();
}

/* Mark as DISPENSED */
$stmt = $conn->prepare("
    UPDATE nurse_medication_requests
    SET status       = 'DISPENSED',
        dispensed_by = ?,
        dispensed_at = NOW()
    WHERE request_id = ? AND status = 'PENDING'
");
$stmt->bind_param("ii", $user_id, $request_id);
$stmt->execute();
$affected = $stmt->affected_rows;
$stmt->close();

if ($affected === 0) {
    echo json_encode(['success' => false, 'message' => 'Could not update — may already be dispensed']);
    exit();
}

/*
 * Deduct from pharmacy_inventory stock.
 * The after_dispensing_item_insert trigger handles stock deduction
 * when going through pharmacy_dispensing_items, but since this is a
 * direct nurse triage request (not a formal dispensing record), we
 * deduct manually here.
 */
$inv = $conn->prepare("
    UPDATE pharmacy_inventory
    SET current_stock = GREATEST(current_stock - ?, 0)
    WHERE inventory_id = ?
");
$inv->bind_param("ii", $req['quantity_requested'], $req['inventory_id']);
$inv->execute();
$inv->close();

echo json_encode([
    'success' => true,
    'message' => 'Medication marked as dispensed and stock updated.'
]);