<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
ini_set('display_errors', 0);
error_reporting(E_ALL);
ob_start();

require_once dirname(__DIR__) . '/db.php';
header('Content-Type: application/json');

$staff_id = (int)($_SESSION['staff_id'] ?? 1);
$action = $_POST['action'] ?? $_GET['action'] ?? '';

try {
    // 1. PATIENT SEARCH FOR OTC
    if ($action === 'search_patient') {
        $term = $conn->real_escape_string($_GET['term'] ?? '');
        $q = $conn->query("SELECT patient_no, first_name, last_name, mobile FROM patient WHERE first_name LIKE '%$term%' OR last_name LIKE '%$term%' OR patient_no LIKE '%$term%' LIMIT 10");
        $data = [];
        if($q) {
            while($r = $q->fetch_assoc()){
                $data[] = [
                    'id' => $r['patient_no'],
                    'text' => $r['first_name'] . ' ' . $r['last_name'] . ' (' . $r['patient_no'] . ')',
                    'fname' => $r['first_name'],
                    'lname' => $r['last_name'],
                    'mobile' => $r['mobile']
                ];
            }
        }
        ob_end_clean(); echo json_encode(['results' => $data]); exit;
    }

    // 2. FETCH AVAILABLE PRODUCTS
    if ($action === 'get_products') {
        $q = $conn->query("SELECT id, service_name, cash_price_adult FROM service_catalog WHERE service_type='Drug' AND is_active=1 ORDER BY service_name ASC");
        $data = [];
        while($r = $q->fetch_assoc()) $data[] = ['id'=>$r['id'], 'name'=>$r['service_name'], 'price'=>$r['cash_price_adult']];
        if(ob_get_length()) ob_end_clean(); echo json_encode(['status'=>'success', 'data'=>$data]); exit;
    }

    // 3. PROCESS THE OTC DISPENSE
    if ($action === 'process_otc_dispense') {
        $loc_id = (int)$_POST['location_id'];
        $patient_no = $conn->real_escape_string($_POST['patient_no'] ?? 'WALK-IN');
        $pat_name = $conn->real_escape_string($_POST['patient_name'] ?? 'Walk-In');
        $mobile = $conn->real_escape_string($_POST['mobile'] ?? '');
        
        $svcs = $_POST['service_id'] ?? [];
        $qtys = $_POST['qty'] ?? [];
        $prices = $_POST['unit_price'] ?? [];
        
        if (empty($svcs)) throw new Exception("No products selected.");

        $conn->begin_transaction();
        
        $inv_no = 'OTC-' . strtoupper(substr(md5(uniqid()), 0, 8));
        $total_bill = 0;

        $stmtStkCheck = $conn->prepare("SELECT quantity FROM inventory_stock WHERE service_id = ? AND location_id = ? FOR UPDATE");
        $stmtStkUpdate = $conn->prepare("UPDATE inventory_stock SET quantity = quantity - ? WHERE service_id = ? AND location_id = ?");
        $stmtTxLog = $conn->prepare("INSERT INTO inventory_transactions (service_id, location_id, transaction_type, quantity_changed, reference_id, performed_by) VALUES (?, ?, 'Dispense', ?, 0, ?)");

        foreach ($svcs as $i => $svc_id) {
            $svc_id = (int)$svc_id;
            $qty = (int)($qtys[$i] ?? 0);
            $price = (float)($prices[$i] ?? 0);
            
            if ($qty <= 0) continue;
            
            $stmtStkCheck->bind_param("ii", $svc_id, $loc_id); $stmtStkCheck->execute();
            $stk = $stmtStkCheck->get_result()->fetch_assoc();
            if (!$stk || $stk['quantity'] < $qty) {
                $name = $conn->query("SELECT service_name FROM service_catalog WHERE id=$svc_id")->fetch_assoc()['service_name'];
                throw new Exception("Insufficient stock for: " . $name);
            }

            $stmtStkUpdate->bind_param("iii", $qty, $svc_id, $loc_id); $stmtStkUpdate->execute();
            $neg = -$qty;
            $stmtTxLog->bind_param("iiii", $svc_id, $loc_id, $neg, $staff_id); $stmtTxLog->execute();

            $total_bill += ($qty * $price);
        }

        // Attach invoice to specific patient if searched, otherwise mark as walk-in
        $invoice_patient_identity = ($patient_no === 'WALK-IN') ? "WALK-IN ($pat_name)" : $patient_no;
        $conn->query("INSERT INTO patient_invoices (invoice_no, patient_no, department_origin, total_amount, balance_due, status, created_at) VALUES ('$inv_no', '$invoice_patient_identity', 'OTC Pharmacy', $total_bill, $total_bill, 'Unpaid', NOW())");

        $conn->commit();
        if(ob_get_length()) ob_end_clean(); echo json_encode(['status'=>'success', 'invoice_no'=>$inv_no]); exit;
    }
} catch (Throwable $e) {
    if (isset($conn)) $conn->rollback();
    if(ob_get_length()) ob_end_clean(); echo json_encode(['status'=>'error', 'message'=>$e->getMessage()]); exit;
}
?>