<?php
session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php';
require_once '../includes/EtimsIntegration.php';

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

// Check permissions
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ACCOUNTANT'];
if (!isset($_SESSION['role_code']) || !in_array($_SESSION['role_code'], $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

$invoice_id = isset($_POST['invoice_id']) ? intval($_POST['invoice_id']) : 0;

if ($invoice_id == 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid invoice ID']);
    exit();
}

// Check eTIMS Status
$etims = new EtimsIntegration($conn);
if (!$etims->isEnabled() && !$etims->isMockMode()) {
    echo json_encode(['success' => false, 'message' => 'eTIMS integration is disabled system-wide.']);
    exit();
}

mysqli_begin_transaction($conn);

try {
    // 1. Get invoice details
    $invoice_query = "SELECT i.*, 
                     u.full_name as patient_name,
                     p.phone_number,
                     p.insurance_policy_number,
                     p.patient_id
                     FROM invoices i
                     LEFT JOIN patients p ON i.patient_id = p.patient_id
                     LEFT JOIN users u ON p.user_id = u.user_id
                     WHERE i.invoice_id = ?";

    $stmt = $conn->prepare($invoice_query);
    $stmt->bind_param("i", $invoice_id);
    $stmt->execute();
    $invoice_result = $stmt->get_result();

    if ($invoice_result->num_rows == 0) {
        throw new Exception("Invoice not found");
    }

    $invoice = $invoice_result->fetch_assoc();

    // Check if already submitted
    if (!empty($invoice['etims_invoice_number'])) {
        throw new Exception("Invoice already submitted to eTIMS");
    }

    // 2. Get invoice items
    $items_query = "SELECT ii.*, s.service_name, s.service_code
                   FROM invoice_items ii
                   LEFT JOIN services s ON ii.service_id = s.service_id
                   WHERE ii.invoice_id = ?";
    $stmt_items = $conn->prepare($items_query);
    $stmt_items->bind_param("i", $invoice_id);
    $stmt_items->execute();
    $items_result = $stmt_items->get_result();

    if ($items_result->num_rows == 0) {
        throw new Exception("Invoice has no items");
    }

    $invoice_items = [];
    while ($item = $items_result->fetch_assoc()) {
        $invoice_items[] = [
            'item_code' => $item['service_code'] ?? 'GEN-001',
            'item_name' => $item['item_name'] ?? $item['service_name'],
            'quantity' => $item['quantity'],
            'unit_price' => $item['unit_price'],
            'tax_type' => 'B', // Default to VAT 8% (modify logic if needed)
            'item_class_code' => '50101502' // Medical Service
        ];
    }

    // 3. Prepare data for eTIMS Integration
    $submit_data = [
        'invoice_number' => $invoice['invoice_id'],
        'trader_invoice_no' => 'INV-' . str_pad($invoice['invoice_id'], 6, '0', STR_PAD_LEFT),
        'customer_name' => $invoice['patient_name'] ?? 'Walk-in Patient',
        'customer_pin' => '', // Add column to patients table if needed
        'customer_mobile' => $invoice['phone_number'] ?? '',
        'amount_paid' => $invoice['total_amount'], // Assuming full payment for the receipt generation
        'items' => $invoice_items
    ];

    // 4. Submit to eTIMS
    $response = $etims->submitInvoice($submit_data);

    if ($response['success']) {
        // 5. Update Database with eTIMS details
        $etims_data = $response['data'];

        $update_sql = "UPDATE invoices SET 
                      etims_invoice_number = ?,
                      etims_cu_serial_number = ?, 
                      etims_receipt_signature = ?,
                      etims_submission_date = ?,
                      etims_qr_code = ?
                      WHERE invoice_id = ?";

        $stmt_update = $conn->prepare($update_sql);

        // Handle nulls safely
        $e_inv_no = $etims_data['invoiceNumber'] ?? null;
        $e_serial = $etims_data['cuSerial'] ?? null;
        $e_sig = $etims_data['receiptSignature'] ?? null;
        $e_date = $etims_data['receiptDate'] ?? date('Y-m-d H:i:s');
        $e_qr = $etims_data['qrCode'] ?? null;

        $stmt_update->bind_param(
            "sssssi",
            $e_inv_no,
            $e_serial,
            $e_sig,
            $e_date,
            $e_qr,
            $invoice_id
        );

        if (!$stmt_update->execute()) {
            throw new Exception("Failed to update invoice with eTIMS data: " . $conn->error);
        }

        mysqli_commit($conn);

        echo json_encode([
            'success' => true,
            'message' => 'Invoice submitted to eTIMS successfully',
            'data' => $etims_data
        ]);

    } else {
        throw new Exception("eTIMS Error: " . $response['message']);
    }

} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>