<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../../dripend/includes/db.php';

// =========================================================================================
// 1. AUTO-DEPLOY DYNAMIC CONFIGURATION TABLES & COLUMNS
// =========================================================================================
$conn->query("CREATE TABLE IF NOT EXISTS `setup_payment_methods` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `method_name` varchar(50) NOT NULL,
    `icon_class` varchar(50) NOT NULL,
    `is_online_api` tinyint(1) DEFAULT 0,
    `is_active` tinyint(1) DEFAULT 1,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

$chkMethods = $conn->query("SELECT COUNT(*) as c FROM setup_payment_methods")->fetch_assoc();
if ($chkMethods['c'] == 0) {
    $conn->query("INSERT INTO setup_payment_methods (method_name, icon_class, is_online_api) VALUES 
        ('Cash', 'fa-money-bill-wave', 0),
        ('Offline MoMo', 'fa-mobile-screen-button', 0),
        ('POS / Card', 'fa-credit-card', 0),
        ('Online API Gateway', 'fa-globe', 1)
    ");
}

// Ensure global settings columns exist, including the dynamic denominations
$conn->query("ALTER TABLE system_workflow_rules ADD COLUMN IF NOT EXISTS currency_symbol varchar(10) DEFAULT 'GHS'");
$conn->query("ALTER TABLE system_workflow_rules ADD COLUMN IF NOT EXISTS allow_partial_payments tinyint(1) DEFAULT 1");
$conn->query("ALTER TABLE system_workflow_rules ADD COLUMN IF NOT EXISTS default_payment_api varchar(50) DEFAULT 'Paystack'");
$conn->query("ALTER TABLE system_workflow_rules ADD COLUMN IF NOT EXISTS quick_payment_denominations varchar(100) DEFAULT '50,100,200,500'");

// =========================================================================================
// 2. FETCH SYSTEM CONFIGURATIONS
// =========================================================================================
$sysQ = $conn->query("SELECT currency_symbol, allow_partial_payments, default_payment_api, quick_payment_denominations FROM system_workflow_rules LIMIT 1");
$sys = $sysQ ? $sysQ->fetch_assoc() : [];
$currency = $sys['currency_symbol'] ?? 'GHS';
$allow_partial = (int)($sys['allow_partial_payments'] ?? 1);
$default_api = $sys['default_payment_api'] ?? 'Standard Gateway';
$quick_denoms_string = $sys['quick_payment_denominations'] ?? '50,100,200';
$quick_denominations = array_filter(array_map('trim', explode(',', $quick_denoms_string)));

$methodsQ = $conn->query("SELECT * FROM setup_payment_methods WHERE is_active = 1 ORDER BY id ASC");
$payment_methods = [];
if ($methodsQ) {
    while ($m = $methodsQ->fetch_assoc()) {
        $payment_methods[] = $m;
    }
}

// =========================================================================================
// 3. FETCH INVOICE & PATIENT DATA
// =========================================================================================
$invoice_no = isset($_GET['invoice_id']) ? $conn->real_escape_string($_GET['invoice_id']) : '';

if (empty($invoice_no)) {
    die("<div style='padding:40px; text-align:center; font-family:sans-serif;'><h2>Invalid Invoice Reference.</h2><a href='billingDashboard.php'>Return to Dashboard</a></div>");
}

$stmt = $conn->prepare("
    SELECT i.*, p.first_name, p.last_name, p.mobile 
    FROM patient_invoices i 
    LEFT JOIN patient p ON i.patient_no = p.patient_no 
    WHERE i.invoice_no = ? LIMIT 1
");
if (!$stmt) die("Database Prepare Error: " . $conn->error);

$stmt->bind_param("s", $invoice_no);
$stmt->execute();
$invoice = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$invoice) die("<div style='padding:40px; text-align:center;'><h2>Invoice Not Found.</h2></div>");

$patient_no = $invoice['patient_no'];
$balance_due = (float)$invoice['balance_due'];
$total_amount = (float)$invoice['total_amount'];
$amount_paid = $total_amount - $balance_due;

// Resolve an active visit_id for the Patient Header to locate them
$visit_id = 0;
if ($patient_no !== 'WALK-IN') {
    $vQ = $conn->query("SELECT id FROM visit_master WHERE patient_no = '$patient_no' ORDER BY id DESC LIMIT 1");
    if ($vQ && $v = $vQ->fetch_assoc()) {
        $visit_id = (int)$v['id'];
    }
}

// Fetch Payment History
$payments = [];
$qPay = $conn->query("SELECT * FROM patient_payments WHERE invoice_no = '$invoice_no' ORDER BY created_at DESC");
if ($qPay) while($p = $qPay->fetch_assoc()) $payments[] = $p;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic POS Terminal | eRHAMS Accounts</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { background-color: #f1f5f9; margin: 0; font-family: 'Inter', sans-serif; }
        .main-content-wrapper { margin-left: 260px; padding: 2.5rem; width: calc(100% - 260px); min-height: 100vh; }
        @media (max-width: 992px) { .main-content-wrapper { margin-left: 0; width: 100%; padding: 1.5rem; } }
        
        .desk-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;}
        .content-card { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 4px 15px rgba(0,0,0,0.02); overflow: hidden; }
        
        .invoice-banner { background: #1e293b; color: #fff; padding: 25px; border-radius: 16px 16px 0 0; }
        .amount-display { font-size: 48px; font-weight: 800; letter-spacing: -1.5px; color: #0f172a; line-height: 1; margin: 15px 0; }
        
        .payment-method-box { border: 2px solid #e2e8f0; border-radius: 12px; padding: 15px; cursor: pointer; transition: 0.2s; text-align: center; font-weight: 700; color: #64748b; height: 100%; display: flex; flex-direction: column; justify-content: center;}
        .payment-method-box:hover { border-color: #bae6fd; background: #f0f9ff; color: #0284c7; }
        .payment-method-box.active { border-color: #0284c7; background: #e0f2fe; color: #0284c7; }
        .payment-method-box.online-active { border-color: #10b981; background: #ecfdf5; color: #10b981; }
        .payment-method-box i { font-size: 24px; display: block; margin-bottom: 8px; }
        
        .quick-amt-btn { border: 1px solid #cbd5e1; background: #fff; border-radius: 8px; padding: 10px; font-weight: 700; color: #334155; transition: 0.2s; cursor: pointer; width: 100%; }
        .quick-amt-btn:hover { background: #f8fafc; border-color: #94a3b8; }
        
        .mode-selector { border: 2px solid #e2e8f0; border-radius: 10px; padding: 12px; cursor: pointer; font-weight: 700; color: #64748b; text-align: center; transition: 0.2s;}
        .mode-selector.active { border-color: #0284c7; background: #0284c7; color: #fff; }
        
        .numpad-input { font-size: 36px !important; font-weight: 800 !important; text-align: center; height: 80px; border-radius: 16px !important; border: 2px solid #cbd5e1 !important; color: #0f172a !important; background: #fff !important; transition: 0.2s;}
        .numpad-input:focus { border-color: #0284c7 !important; box-shadow: 0 0 0 4px rgba(2, 132, 199, 0.15) !important; }
        .numpad-input:read-only { background: #f8fafc !important; color: #64748b !important; border-color: #e2e8f0 !important; }
    </style>
</head>
<body>

<?php include '../../dripend/statpages/sidebar.php'; ?>

<div class="main-content-wrapper">
    <div class="desk-header">
        <div>
            <h4 class="fw-bold text-dark m-0"><a href="billingDashboard.php" class="text-secondary text-decoration-none me-2"><i class="fa-solid fa-arrow-left"></i></a> Dynamic POS Terminal</h4>
        </div>
        <div class="badge bg-<?php echo $balance_due <= 0 ? 'success' : 'danger'; ?> fs-6 px-4 py-2 rounded-pill shadow-sm">
            <?php echo $balance_due <= 0 ? '<i class="fa-solid fa-check-double me-1"></i> FULLY PAID' : '<i class="fa-solid fa-triangle-exclamation me-1"></i> PAYMENT REQUIRED'; ?>
        </div>
    </div>

    <!-- DYNAMIC PATIENT CONTEXT HEADER -->
    <?php if ($visit_id > 0): ?>
        <div class="mb-4">
            <?php include('../../dripend/statpages/patientProfileHeader.php'); ?>
        </div>
    <?php elseif ($patient_no === 'WALK-IN'): ?>
        <div class="alert alert-info border-info fw-bold shadow-sm mb-4"><i class="fa-solid fa-person-walking me-2"></i> Unregistered Walk-In Client</div>
    <?php endif; ?>

    <div class="row g-4">
        <!-- INVOICE DETAILS PANEL -->
        <div class="col-lg-5">
            <div class="content-card mb-4">
                <div class="invoice-banner d-flex justify-content-between align-items-center">
                    <div>
                        <span class="text-white-50 small fw-bold text-uppercase d-block mb-1">Invoice Reference</span>
                        <h4 class="m-0 fw-bold text-white"><?php echo htmlspecialchars($invoice_no); ?></h4>
                    </div>
                    <i class="fa-solid fa-file-invoice-dollar fa-3x text-white opacity-25"></i>
                </div>
                <div class="p-4">
                    <div class="d-flex justify-content-between mb-4 pb-4 border-bottom">
                        <div>
                            <span class="d-block small text-muted fw-bold text-uppercase mb-1">Target Account</span>
                            <span class="badge bg-light text-secondary border fw-bold px-3 py-2"><i class="fa-solid fa-building me-1"></i> <?php echo htmlspecialchars($invoice['department_origin'] ?? 'General'); ?></span>
                        </div>
                    </div>
                    
                    <div class="d-flex justify-content-between mb-2">
                        <span class="fw-bold text-muted">Total Billed Amount</span>
                        <span class="fw-bold text-dark"><?php echo $currency; ?> <?php echo number_format($total_amount, 2); ?></span>
                    </div>
                    <div class="d-flex justify-content-between mb-3 pb-3 border-bottom">
                        <span class="fw-bold text-success">Total Amount Paid</span>
                        <span class="fw-bold text-success">- <?php echo $currency; ?> <?php echo number_format($amount_paid, 2); ?></span>
                    </div>
                    
                    <div class="text-center bg-light p-4 rounded-4 border">
                        <span class="d-block fw-bold text-danger text-uppercase mb-1" style="letter-spacing:1px;">Outstanding Balance</span>
                        <div class="amount-display text-danger"><?php echo $currency; ?> <span id="lbl_balance_due"><?php echo number_format($balance_due, 2); ?></span></div>
                    </div>
                </div>
            </div>

            <!-- PAYMENT HISTORY -->
            <?php if (!empty($payments)): ?>
            <div class="content-card p-4">
                <h6 class="fw-bold text-dark text-uppercase mb-3"><i class="fa-solid fa-clock-rotate-left me-2 text-muted"></i> Transaction Ledger</h6>
                <?php foreach($payments as $pay): ?>
                    <div class="d-flex justify-content-between align-items-center mb-2 pb-2 border-bottom">
                        <div>
                            <span class="fw-bold text-dark d-block"><?php echo $currency; ?> <?php echo number_format($pay['amount_paid'], 2); ?></span>
                            <span class="small text-muted"><?php echo date('M d, Y h:i A', strtotime($pay['created_at'])); ?> &bull; <?php echo htmlspecialchars($pay['payment_method']); ?></span>
                        </div>
                        <span class="badge bg-success bg-opacity-10 text-success border border-success"><i class="fa-solid fa-check me-1"></i> Success</span>
                    </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>

        <!-- DYNAMIC PAYMENT TERMINAL -->
        <div class="col-lg-7">
            <div class="content-card p-4 h-100 position-relative">
                <?php if ($balance_due <= 0): ?>
                    <div class="position-absolute w-100 h-100 top-0 start-0 bg-white bg-opacity-75 d-flex flex-column align-items-center justify-content-center" style="z-index: 10; backdrop-filter: blur(2px);">
                        <i class="fa-solid fa-circle-check text-success fa-5x mb-3 shadow-sm rounded-circle bg-white"></i>
                        <h3 class="fw-bold text-dark">Invoice Settled</h3>
                        <p class="text-muted fw-bold">No further payment is required.</p>
                        <div class="d-flex flex-wrap justify-content-center gap-3 mt-3">
                            <a href="print_payment.php?invoice_id=<?php echo urlencode($invoice_no); ?>" target="_blank" class="btn btn-dark fw-bold px-4 shadow-sm"><i class="fa-solid fa-print me-2"></i> Print Official Receipt</a>
                            
                            <!-- DYNAMIC NAVIGATION BUTTON ADDED HERE -->
                            <?php if ($patient_no !== 'WALK-IN'): ?>
                                <a href="patientBilling.php?patient_id=<?php echo urlencode($patient_no); ?>" class="btn btn-primary fw-bold px-4 shadow-sm"><i class="fa-solid fa-user-injured me-2"></i> Go to Patient Billing Desk</a>
                            <?php else: ?>
                                <a href="billingDashboard.php" class="btn btn-primary fw-bold px-4 shadow-sm"><i class="fa-solid fa-house me-2"></i> Return to POS Dashboard</a>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>

                <h5 class="fw-bold text-dark mb-4"><i class="fa-solid fa-cash-register me-2 text-primary"></i> Process New Payment</h5>
                
                <form id="frmProcessPayment" onsubmit="return false;">
                    <input type="hidden" name="invoice_no" value="<?php echo htmlspecialchars($invoice_no); ?>">
                    <input type="hidden" name="patient_no" value="<?php echo htmlspecialchars($invoice['patient_no']); ?>">
                    <input type="hidden" name="payment_method" id="selected_method" value="">
                    <input type="hidden" name="is_online_api" id="is_online_api" value="0">
                    <input type="hidden" id="sys_currency" value="<?php echo htmlspecialchars($currency); ?>">
                    
                    <!-- DYNAMIC METHODS FROM DATABASE -->
                    <label class="small fw-bold text-muted text-uppercase mb-2">Select Database Configured Method</label>
                    <div class="row g-3 mb-4">
                        <?php foreach($payment_methods as $idx => $m): ?>
                            <div class="col-md-4 col-6">
                                <div class="payment-method-box <?php echo $idx === 0 ? 'active' : ''; ?>" 
                                     data-method="<?php echo htmlspecialchars($m['method_name']); ?>" 
                                     data-online="<?php echo $m['is_online_api']; ?>">
                                    <i class="fa-solid <?php echo htmlspecialchars($m['icon_class']); ?>"></i>
                                    <?php echo htmlspecialchars($m['method_name']); ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- DYNAMIC PARTIAL PAYMENT TOGGLE FROM DATABASE -->
                    <div class="row g-3 mb-4">
                        <div class="col-6">
                            <div class="mode-selector active" id="mode_full" onclick="setMode('full')"><i class="fa-solid fa-check-double me-2"></i> Full Settlement</div>
                        </div>
                        <div class="col-6">
                            <?php if($allow_partial === 1): ?>
                                <div class="mode-selector" id="mode_partial" onclick="setMode('partial')"><i class="fa-solid fa-pie-chart me-2"></i> Partial Payment</div>
                            <?php else: ?>
                                <div class="mode-selector text-muted" style="cursor:not-allowed; opacity:0.6;" title="Disabled in Database Rules"><i class="fa-solid fa-lock me-2"></i> Partial (Disabled)</div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div id="reference_container" style="display:none;" class="mb-4">
                        <label class="small fw-bold text-dark mb-1">Transaction Reference / Receipt No. <span class="text-danger">*</span></label>
                        <input type="text" name="transaction_ref" id="transaction_ref" class="form-control form-control-lg border-secondary fw-bold" placeholder="e.g. MOMO-123456789">
                    </div>

                    <label class="small fw-bold text-muted text-uppercase mb-2">Amount to Pay (<?php echo $currency; ?>)</label>
                    <input type="number" step="0.01" name="amount_paid" id="amount_input" class="form-control numpad-input mb-3" max="<?php echo $balance_due; ?>" value="<?php echo $balance_due; ?>" readonly required>
                    
                    <!-- DYNAMIC QUICK AMOUNT BUTTONS FROM DATABASE -->
                    <div class="row g-2 mb-4 d-flex justify-content-center">
                        <div class="col"><button type="button" class="quick-amt-btn" onclick="setAmt(<?php echo $balance_due; ?>)">Full</button></div>
                        <?php foreach($quick_denominations as $val): if(is_numeric($val)): ?>
                            <div class="col"><button type="button" class="quick-amt-btn" onclick="setAmt(<?php echo htmlspecialchars($val); ?>)"><?php echo htmlspecialchars($val); ?></button></div>
                        <?php endif; endforeach; ?>
                    </div>

                    <div class="bg-light p-3 rounded border mb-4 d-flex justify-content-between align-items-center" id="change_container">
                        <span class="fw-bold text-muted">Change to return:</span>
                        <h4 class="m-0 fw-bold text-dark" id="change_display"><?php echo $currency; ?> 0.00</h4>
                    </div>

                    <button type="submit" id="btnSubmitPayment" class="btn btn-primary w-100 py-3 shadow-sm fw-bold fs-5">
                        <i class="fa-solid fa-lock me-2"></i> Confirm Payment
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<!-- Inject PHP configuration variables into the global window object -->
<script>
    window.PAYMENT_CONFIG = {
        balanceDue: <?php echo $balance_due; ?>,
        defaultApiName: "<?php echo htmlspecialchars($default_api); ?>"
    };
</script>

<!-- Load the decoupled external JavaScript file -->
<script src="/rimax/application/assets/js/processPatientPayment.js?v=<?php echo time(); ?>"></script>

</body>
</html>