<?php
/**
 * صفحة الدفع أونلاين - تحويل للفاتورة
 * index.php?page=pay&invoice_id=X أو ?code=رقم_الفاتورة
 */
use App\Core\Tenant;
use App\Core\PaymentGateway;

$action = $_GET['action'] ?? 'index';
$invoiceId = (int)($_GET['invoice_id'] ?? 0);
$invoiceCode = trim($_GET['code'] ?? '');
$tenantId = (int)Tenant::id();

if ($action === 'success' && $invoiceId > 0) {
    ?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head><meta charset="UTF-8"><title>تم الطلب</title><link rel="stylesheet" href="styles.css"></head>
<body class="login-page">
<div class="login-container" style="max-width:480px;">
    <h1 style="color:var(--status-completed);">✓ تم إرسال طلب الدفع</h1>
    <p>سيتم التحقق من استلام الدفعة وتحديث الفاتورة خلال فترة قصيرة.</p>
    <p><a href="index.php?page=print_invoice&invoice_id=<?php echo (int)$invoiceId; ?>" class="btn-primary">عرض الفاتورة</a></p>
</div>
</body>
</html>
    <?php
    return;
}

if ($invoiceCode !== '' && $invoiceId <= 0) {
    try {
        $stmt = $db->prepare('SELECT id FROM invoices WHERE invoice_number = ? LIMIT 1');
        $stmt->execute([$invoiceCode]);
        $r = $stmt->fetch();
        if ($r) $invoiceId = (int)$r['id'];
    } catch (Throwable $e) {}
}

$invoice = null;
if ($invoiceId > 0) {
    try {
        $tenantAnd = '';
        try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $tenantAnd = ' AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
        $stmt = $db->prepare(
            'SELECT i.id, i.invoice_number, i.order_id, i.net_amount, i.paid_amount, i.currency,
                    o.order_number, p.full_name AS patient_name
             FROM invoices i
             JOIN lab_orders o ON o.id = i.order_id
             JOIN patients p ON p.id = o.patient_id
             WHERE i.id = ?' . $tenantAnd
        );
        $stmt->execute([$invoiceId]);
        $invoice = $stmt->fetch();
    } catch (Throwable $e) {}
}

if (!$invoice) {
    echo '<!DOCTYPE html><html lang="ar" dir="rtl"><head><meta charset="UTF-8"><title>فاتورة غير موجودة</title></head><body style="font-family:Arial;padding:40px;text-align:center;"><h1>الفاتورة غير موجودة</h1><p><a href="index.php">العودة</a></p></body></html>';
    return;
}

$remaining = max(0, (float)$invoice['net_amount'] - (float)$invoice['paid_amount']);
$pg = new PaymentGateway($db, $tenantId);

if ($remaining <= 0) {
    echo '<!DOCTYPE html><html lang="ar" dir="rtl"><head><meta charset="UTF-8"><title>الفاتورة مدفوعة</title></head><body style="font-family:Arial;padding:40px;text-align:center;"><h1>الفاتورة مدفوعة بالكامل</h1><p><a href="index.php?page=print_invoice&invoice_id=' . (int)$invoice['id'] . '">عرض الفاتورة</a></p></body></html>';
    return;
}

$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
$scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? ''));
if ($scriptDir === '/') $scriptDir = '';
$successUrl = $baseUrl . $scriptDir . '/index.php?page=pay&action=success&invoice_id=' . $invoiceId;
$cancelUrl = $baseUrl . $scriptDir . '/index.php?page=print_invoice&invoice_id=' . $invoiceId;

$result = $pg->createPayment($invoice, $successUrl, $cancelUrl);

if (!empty($result['error'])) {
    ?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head><meta charset="UTF-8"><title>خطأ في الدفع</title><link rel="stylesheet" href="styles.css"></head>
<body class="login-page">
<div class="login-container" style="max-width:480px;">
    <h1>تعذّر إتمام الدفع</h1>
    <p class="alert alert-danger"><?php echo htmlspecialchars($result['error'], ENT_QUOTES, 'UTF-8'); ?></p>
    <p>رقم الفاتورة: <strong><?php echo htmlspecialchars($invoice['invoice_number'], ENT_QUOTES, 'UTF-8'); ?></strong></p>
    <p>المبلغ المتبقي: <strong><?php echo number_format($remaining, 2); ?> <?php echo ($invoice['currency'] ?? '') === 'IQD' ? 'د.ع' : '$'; ?></strong></p>
    <p><a href="index.php?page=print_invoice&invoice_id=<?php echo (int)$invoice['id']; ?>" class="btn-primary">عرض الفاتورة</a></p>
    <?php if ($pg->getPaymentNumber()): ?>
    <p style="margin-top:16px;color:var(--text-muted);">للدفع يدوياً: <?php echo htmlspecialchars($pg->getPaymentNumber(), ENT_QUOTES, 'UTF-8'); ?></p>
    <?php endif; ?>
</div>
</body>
</html>
    <?php
    return;
}

header('Location: ' . $result['url']);
exit;
