<?php
// api/patient/payments.php
require_once __DIR__ . '/../middleware.php';
require_once __DIR__ . '/../../layouts/dbconn.php';

global $API_USER;
if (!isset($API_USER)) {
    jsonError('Unauthorized', 401);
}

// Get Patient ID
$user_id = $API_USER['sub'];
$stmt = $conn->prepare("SELECT patient_id FROM patients WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    jsonError('Patient profile not found', 404);
}

$patient = $res->fetch_assoc();
$patient_id = $patient['patient_id'];

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // List Payment History
    $sql = "SELECT p.payment_id, p.payment_date, p.amount, p.payment_method, p.payment_reference, p.status, i.invoice_number 
            FROM payments p
            JOIN invoices i ON p.invoice_id = i.invoice_id
            WHERE i.patient_id = ?
            ORDER BY p.payment_date DESC LIMIT 50";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $payments = [];
    $base_download_url = "http://" . $_SERVER['HTTP_HOST'] . "/patient_download_records.php";

    while ($row = $result->fetch_assoc()) {
        $row['receipt_url'] = $base_download_url . "?type=receipt&id=" . $row['payment_id'];
        $payments[] = $row;
    }

    jsonResponse($payments);

} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Initiate Payment
    $input = json_decode(file_get_contents('php://input'), true);

    if (empty($input['invoice_id']) || empty($input['amount']) || empty($input['method'])) {
        jsonError('Missing required fields: invoice_id, amount, method', 400);
    }

    $invoice_id = $input['invoice_id'];
    $amount = floatval($input['amount']);
    $method = $input['method']; // MPESA, CARD
    $phone = $input['phone'] ?? null; // For MPESA

    // Verify invoice ownership
    $check = $conn->prepare("SELECT balance FROM invoices WHERE invoice_id = ? AND patient_id = ?");
    $check->bind_param("ii", $invoice_id, $patient_id);
    $check->execute();
    $inv_res = $check->get_result();

    if ($inv_res->num_rows === 0) {
        jsonError('Invoice not found or access denied', 404);
    }

    $invoice = $inv_res->fetch_assoc();
    if ($amount > $invoice['balance']) {
        jsonError('Amount exceeds invoice balance', 400);
    }

    // In a real app, this is where we trigger STK Push or Stripe Intent
    // For this prototype, we simulate a "Pending" or successful initiation

    $response_msg = "Payment initiated successfully.";
    if ($method === 'MPESA') {
        if (!$phone)
            jsonError('Phone number required for M-Pesa', 400);
        $response_msg = "M-Pesa STK Push sent to $phone. Please complete the transaction on your phone.";
    }

    // We do NOT insert into payments table yet; existing system listens for callbacks.
    // However, to make this useful for the mobile app "Test", let's return a success status.

    jsonResponse([
        'message' => $response_msg,
        'status' => 'INITIATED',
        'gateway_reference' => 'REQ_' . strtoupper(uniqid())
    ]);

} else {
    jsonError('Method not allowed', 405);
}
?>