<?php
require_once __DIR__ . '/includes/header.php';

$today = date('Y-m-d');
$stats = ['pending_count' => 0, 'pending_total' => 0, 'paid_count' => 0, 'paid_total' => 0];

if ($restaurantId) {
    $stmt = $db->query(
        "SELECT COUNT(*) AS cnt, COALESCE(SUM(grand_total), 0) AS total
         FROM orders WHERE restaurant_id = ? AND payment_status = 'pending'
         AND order_status NOT IN ('cancelled', 'rejected') AND is_demo = 0",
        [$restaurantId]
    );
    $r = $stmt->fetch();
    $stats['pending_count'] = (int) ($r['cnt'] ?? 0);
    $stats['pending_total'] = (float) ($r['total'] ?? 0);

    $stmt2 = $db->query(
        "SELECT COUNT(*) AS cnt, COALESCE(SUM(p.amount), 0) AS total
         FROM payments p
         INNER JOIN orders o ON p.order_id = o.id
         WHERE p.restaurant_id = ? AND p.status = 'paid'
         AND DATE(p.created_at) = ?",
        [$restaurantId, $today]
    );
    $r2 = $stmt2->fetch();
    $stats['paid_count'] = (int) ($r2['cnt'] ?? 0);
    $stats['paid_total'] = (float) ($r2['total'] ?? 0);
}
?>

<!-- Stats Cards -->
<div class="dash-cards">
    <div class="dash-card card-warning">
        <div class="card-icon"><i class="fas fa-hourglass-half"></i></div>
        <div class="card-value" id="stat-pending-count"><?php echo $stats['pending_count']; ?></div>
        <div class="card-label">Pending Payments</div>
    </div>
    <div class="dash-card card-info">
        <div class="card-icon"><i class="fas fa-money-bill-wave"></i></div>
        <div class="card-value" id="stat-pending-total"><?php echo formatCurrency($stats['pending_total']); ?></div>
        <div class="card-label">Pending Amount</div>
    </div>
    <div class="dash-card card-success">
        <div class="card-icon"><i class="fas fa-check-double"></i></div>
        <div class="card-value" id="stat-paid-count"><?php echo $stats['paid_count']; ?></div>
        <div class="card-label">Paid Today</div>
    </div>
    <div class="dash-card card-primary">
        <div class="card-icon"><i class="fas fa-coins"></i></div>
        <div class="card-value" id="stat-paid-total"><?php echo formatCurrency($stats['paid_total']); ?></div>
        <div class="card-label">Collected Today</div>
    </div>
</div>

<!-- Order Search -->
<div class="card mb-4">
    <div class="card-header">
        <h6 class="card-title mb-0"><i class="fas fa-search me-2"></i>Order Lookup</h6>
    </div>
    <div class="card-body">
        <div class="order-search-box position-relative">
            <i class="fas fa-search"></i>
            <input type="text" class="form-control" id="search-input" placeholder="Search by order number or table number..." oninput="searchOrders()">
        </div>
    </div>
</div>

<div class="row">
    <!-- Pending Payments -->
    <div class="col-lg-6" id="pending-section">
        <div class="card">
            <div class="card-header">
                <h6 class="card-title mb-0"><i class="fas fa-hourglass-half me-2 text-warning"></i>Pending Payments</h6>
                <button class="btn btn-sm btn-outline" onclick="loadPendingOrders()"><i class="fas fa-sync-alt"></i></button>
            </div>
            <div class="card-body" id="pending-orders-list" style="max-height:500px;overflow-y:auto;">
                <div class="text-center text-muted p-3">Loading...</div>
            </div>
        </div>
    </div>

    <!-- Payment Processing -->
    <div class="col-lg-6">
        <div class="card" id="payment-section">
            <div class="card-header">
                <h6 class="card-title mb-0"><i class="fas fa-cash-register me-2 text-success"></i>Process Payment</h6>
            </div>
            <div class="card-body" id="payment-content">
                <div class="text-center text-muted p-4">
                    <i class="fas fa-hand-pointer" style="font-size:2rem;"></i>
                    <p class="mt-2">Select an order to process payment</p>
                </div>
            </div>
        </div>

        <!-- Completed Today -->
        <div class="card mt-4" id="completed-section">
            <div class="card-header">
                <h6 class="card-title mb-0"><i class="fas fa-check-double me-2 text-success"></i>Completed Today</h6>
                <button class="btn btn-sm btn-outline" onclick="loadCompletedOrders()"><i class="fas fa-sync-alt"></i></button>
            </div>
            <div class="card-body" id="completed-orders-list" style="max-height:300px;overflow-y:auto;">
                <div class="text-center text-muted p-3">Loading...</div>
            </div>
        </div>
    </div>
</div>

<script>
var selectedOrder = null;

document.addEventListener('DOMContentLoaded', function() {
    loadPendingOrders();
    loadCompletedOrders();
});

function searchOrders() {
    var query = document.getElementById('search-input').value.trim();
    if (query.length < 2) {
        loadPendingOrders();
        return;
    }
    ajaxGet(BASE_URL + '/ajax/cashier_orders.php?search=' + encodeURIComponent(query), function(data) {
        if (data.success && data.orders) {
            renderPendingOrders(data.orders);
        }
    });
}

function loadPendingOrders() {
    ajaxGet(BASE_URL + '/ajax/cashier_orders.php', function(data) {
        if (data.success && data.orders) {
            renderPendingOrders(data.orders);
            var pendingCount = 0;
            var pendingTotal = 0;
            data.orders.forEach(function(o) {
                pendingCount++;
                pendingTotal += parseFloat(o.balance || o.grand_total);
            });
            document.getElementById('stat-pending-count').textContent = pendingCount;
            document.getElementById('stat-pending-total').textContent = formatCurrency(pendingTotal);
        }
    });
}

function renderPendingOrders(orders) {
    var container = document.getElementById('pending-orders-list');
    if (!orders.length) {
        container.innerHTML = '<div class="text-center text-muted p-3"><i class="fas fa-check-circle" style="font-size:2rem;color:#27ae60;"></i><p class="mt-2">All clear! No pending payments.</p></div>';
        return;
    }
    var html = '';
    orders.forEach(function(order) {
        var isSelected = selectedOrder && selectedOrder.id === order.id;
        var balance = order.balance || order.grand_total;
        html += '<div class="pending-order-card' + (isSelected ? ' selected' : '') + '" onclick="selectOrder(' + order.id + ')">';
        html += '<div class="d-flex justify-content-between align-items-start">';
        html += '<div>';
        html += '<div class="fw-bold">#' + escapeHtml(order.order_number) + '</div>';
        html += '<div class="text-muted" style="font-size:0.8rem;">';
        html += capitalize(order.order_type.replace('_', ' '));
        if (order.table_number) html += ' | Table ' + escapeHtml(order.table_number);
        html += '</div>';
        html += '</div>';
        html += '<div class="text-end">';
        html += '<div class="fw-bold text-danger">' + formatCurrency(balance) + '</div>';
        html += '<span class="badge badge-' + (order.payment_status === 'paid' ? 'success' : 'warning') + '">' + capitalize(order.payment_status) + '</span>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
    });
    container.innerHTML = html;
}

function selectOrder(orderId) {
    ajaxPost(BASE_URL + '/ajax/cashier_action.php',
        'action=get_order_details&order_id=' + orderId + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN),
        function(data) {
            if (data.success && data.order) {
                selectedOrder = data.order;
                renderPaymentSection(data.order);
                loadPendingOrders();
            } else {
                showToast(data.message || 'Failed to load order', 'error');
            }
        }
    );
}

function renderPaymentSection(order) {
    var container = document.getElementById('payment-content');
    var balance = order.balance || order.grand_total;

    var html = '';
    html += '<div class="mb-3">';
    html += '<div class="d-flex justify-content-between align-items-center mb-2">';
    html += '<h5 class="mb-0">#' + escapeHtml(order.order_number) + '</h5>';
    html += '<span class="badge badge-' + getStatusBadge(order.order_status) + '">' + capitalize(order.order_status) + '</span>';
    html += '</div>';
    html += '<div class="text-muted" style="font-size:0.85rem;">';
    html += capitalize(order.order_type.replace('_', ' '));
    if (order.table_number) html += ' | Table ' + escapeHtml(order.table_number);
    if (order.customer_name) html += ' | ' + escapeHtml(order.customer_name);
    html += ' | ' + order.created_at;
    html += '</div></div>';

    html += '<div class="bill-summary mb-3">';
    if (order.items && order.items.length) {
        order.items.forEach(function(item) {
            html += '<div class="bill-row">';
            html += '<span>' + item.quantity + 'x ' + escapeHtml(item.item_name);
            if (item.variation_name) html += ' (' + escapeHtml(item.variation_name) + ')';
            html += '</span>';
            html += '<span>' + formatCurrency(item.item_total) + '</span>';
            html += '</div>';
        });
    }
    html += '<div class="bill-row"><span>Subtotal</span><span>' + formatCurrency(order.subtotal) + '</span></div>';
    if (parseFloat(order.discount) > 0) html += '<div class="bill-row" style="color:#27ae60;"><span>Discount</span><span>-' + formatCurrency(order.discount) + '</span></div>';
    if (parseFloat(order.tax) > 0) html += '<div class="bill-row"><span>Tax</span><span>' + formatCurrency(order.tax) + '</span></div>';
    if (parseFloat(order.service_charge) > 0) html += '<div class="bill-row"><span>Service Charge</span><span>' + formatCurrency(order.service_charge) + '</span></div>';
    if (parseFloat(order.delivery_charge) > 0) html += '<div class="bill-row"><span>Delivery</span><span>' + formatCurrency(order.delivery_charge) + '</span></div>';
    if (parseFloat(order.total_paid) > 0) html += '<div class="bill-row" style="color:#27ae60;"><span>Already Paid</span><span>-' + formatCurrency(order.total_paid) + '</span></div>';
    html += '<div class="bill-row bill-total"><span>Balance Due</span><span>' + formatCurrency(balance) + '</span></div>';
    html += '</div>';

    html += '<div class="form-group mb-3"><label class="form-label fw-bold">Payment Method</label>';
    html += '<div class="d-flex gap-2 flex-wrap">';
    html += '<div class="payment-method-btn active" data-method="cash" onclick="selectPaymentMethod(this)"><i class="fas fa-money-bill-wave"></i>Cash</div>';
    html += '<div class="payment-method-btn" data-method="card" onclick="selectPaymentMethod(this)"><i class="fas fa-credit-card"></i>Card</div>';
    html += '<div class="payment-method-btn" data-method="bank_transfer" onclick="selectPaymentMethod(this)"><i class="fas fa-university"></i>Bank</div>';
    html += '<div class="payment-method-btn" data-method="manual" onclick="selectPaymentMethod(this)"><i class="fas fa-hand-holding-usd"></i>Manual</div>';
    html += '</div></div>';

    html += '<div class="form-group mb-3"><label class="form-label fw-bold">Amount Received</label>';
    html += '<input type="number" class="form-control form-control-lg" id="payment-amount" value="' + parseFloat(balance).toFixed(2) + '" step="0.01" min="0" oninput="calculateChange()"></div>';

    html += '<div class="form-group mb-3"><label class="form-label fw-bold">Transaction Ref (optional)</label>';
    html += '<input type="text" class="form-control" id="payment-ref" placeholder="Reference number..."></div>';

    html += '<div id="change-display" class="alert alert-info mb-3" style="display:none;"></div>';

    html += '<div class="d-flex gap-2">';
    html += '<button class="btn btn-success btn-lg flex-fill" onclick="processPayment(' + order.id + ', ' + balance + ')">';
    html += '<i class="fas fa-check-circle"></i> Process Payment</button>';
    html += '<button class="btn btn-outline btn-lg" onclick="printReceipt(' + order.id + ')">';
    html += '<i class="fas fa-print"></i> Receipt</button>';
    html += '</div>';

    container.innerHTML = html;
}

function selectPaymentMethod(el) {
    document.querySelectorAll('.payment-method-btn').forEach(function(b) { b.classList.remove('active'); });
    el.classList.add('active');
}

function calculateChange() {
    if (!selectedOrder) return;
    var balance = parseFloat(selectedOrder.balance || selectedOrder.grand_total);
    var amount = parseFloat(document.getElementById('payment-amount').value) || 0;
    var change = amount - balance;
    var display = document.getElementById('change-display');

    if (amount > 0 && change >= 0) {
        display.style.display = '';
        display.className = 'alert alert-success mb-3';
        display.innerHTML = '<i class="fas fa-money-bill-wave me-2"></i>Change: <strong>' + formatCurrency(change) + '</strong>';
    } else if (amount > 0 && change < 0) {
        display.style.display = '';
        display.className = 'alert alert-warning mb-3';
        display.innerHTML = '<i class="fas fa-exclamation-triangle me-2"></i>Remaining: <strong>' + formatCurrency(Math.abs(change)) + '</strong>';
    } else {
        display.style.display = 'none';
    }
}

function processPayment(orderId, balance) {
    var amount = parseFloat(document.getElementById('payment-amount').value) || 0;
    if (amount <= 0) {
        showToast('Enter a valid amount', 'error');
        return;
    }
    if (amount > balance + 0.01) {
        showToast('Amount exceeds balance', 'error');
        return;
    }

    var methodEl = document.querySelector('.payment-method-btn.active');
    var method = methodEl ? methodEl.getAttribute('data-method') : 'cash';
    var ref = document.getElementById('payment-ref').value;

    var btn = document.querySelector('#payment-content .btn-success');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Processing...';

    var params = 'action=process_payment&order_id=' + orderId +
        '&amount=' + amount +
        '&payment_method=' + method +
        '&transaction_ref=' + encodeURIComponent(ref) +
        '&csrf_token=' + encodeURIComponent(CSRF_TOKEN);

    ajaxPost(BASE_URL + '/ajax/cashier_action.php', params, function(data) {
        if (data.success) {
            showToast('Payment processed! ' + formatCurrency(amount), 'success');
            selectedOrder = null;
            document.getElementById('payment-content').innerHTML = '<div class="text-center text-muted p-4"><i class="fas fa-check-circle" style="font-size:2rem;color:#27ae60;"></i><p class="mt-2">Payment successful!</p></div>';
            loadPendingOrders();
            loadCompletedOrders();
            refreshStats();
        } else {
            showToast(data.message || 'Payment failed', 'error');
        }
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-check-circle"></i> Process Payment';
    });
}

function printReceipt(orderId) {
    var params = 'order_id=' + orderId + '&type=invoice&csrf_token=' + encodeURIComponent(CSRF_TOKEN);
    ajaxPost(BASE_URL + '/ajax/print_order.php', params, function(data) {
        if (data.success && data.html) {
            var win = window.open('', '_blank', 'width=400,height=600');
            if (win) {
                win.document.write(data.html);
                win.document.close();
                win.focus();
                setTimeout(function() { win.print(); }, 500);
            }
        } else {
            showToast('Failed to generate receipt', 'error');
        }
    });
}

function loadCompletedOrders() {
    ajaxGet(BASE_URL + '/ajax/cashier_orders.php?status=paid', function(data) {
        if (data.success && data.orders) {
            var completed = data.orders.filter(function(o) { return o.payment_status === 'paid'; });
            renderCompletedOrders(completed);
        }
    });
}

function renderCompletedOrders(orders) {
    var container = document.getElementById('completed-orders-list');
    if (!orders.length) {
        container.innerHTML = '<div class="text-center text-muted p-3">No completed payments today</div>';
        return;
    }
    var html = '<table class="data-table table-striped" style="width:100%;">';
    html += '<thead><tr><th>Order</th><th>Table</th><th>Amount</th><th>Time</th><th></th></tr></thead><tbody>';
    var totalCollected = 0;
    orders.forEach(function(o) {
        if (o.payment_status === 'paid') {
            totalCollected += parseFloat(o.grand_total);
        }
        html += '<tr>';
        html += '<td class="fw-bold">#' + escapeHtml(o.order_number) + '</td>';
        html += '<td>' + escapeHtml(o.table_number || '-') + '</td>';
        html += '<td class="fw-bold">' + formatCurrency(o.grand_total) + '</td>';
        html += '<td class="text-muted">' + (o.created_at ? o.created_at.substring(11, 16) : '-') + '</td>';
        html += '<td><button class="btn btn-sm btn-outline" onclick="printReceipt(' + o.id + ')"><i class="fas fa-print"></i></button></td>';
        html += '</tr>';
    });
    html += '</tbody></table>';
    html += '<div class="mt-2 p-2 text-center fw-bold" style="background:#eafaf1;border-radius:8px;">Total Collected: ' + formatCurrency(totalCollected) + '</div>';
    container.innerHTML = html;
}

function refreshStats() {
    loadPendingOrders();
}

function getStatusBadge(status) {
    var map = {
        new: 'danger', confirmed: 'warning', preparing: 'danger',
        ready: 'success', served: 'info', completed: 'success',
        cancelled: 'secondary', rejected: 'secondary',
        pending: 'warning', paid: 'success', partial: 'warning',
        failed: 'danger', refunded: 'info'
    };
    return map[status] || 'secondary';
}

function capitalize(str) {
    if (!str) return '';
    return str.charAt(0).toUpperCase() + str.slice(1);
}
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
