<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/menu_config.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
}

// Handle payment operations
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $response = ['success' => false, 'message' => ''];
    
    try {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'record_payment':
                    $order_id = $_POST['order_id'];
                    $payment_method_id = $_POST['payment_method_id'];
                    $amount = $_POST['amount'];
                    $transaction_reference = trim($_POST['transaction_reference']);
                    $notes = trim($_POST['notes']);
                    
                    $conn->begin_transaction();
                    
                    try {
                        // Get order and customer details
                        $order_sql = "SELECT o.*, c.customer_id FROM orders o 
                                     JOIN customers c ON o.customer_id = c.customer_id 
                                     WHERE o.order_id = ?";
                        $order_stmt = $conn->prepare($order_sql);
                        $order_stmt->bind_param("i", $order_id);
                        $order_stmt->execute();
                        $order = $order_stmt->get_result()->fetch_assoc();
                        
                        if (!$order) {
                            $response['message'] = 'Order not found';
                            break;
                        }
                        
                        $remaining_balance = $order['total_amount'] - $order['paid_amount'];
                        
                        if ($amount > $remaining_balance) {
                            $response['message'] = 'Payment amount exceeds remaining balance';
                            break;
                        }
                        
                        // Insert payment record
                        $payment_sql = "INSERT INTO payments (order_id, customer_id, payment_method_id, amount, transaction_reference, notes, processed_by) 
                                       VALUES (?, ?, ?, ?, ?, ?, ?)";
                        $payment_stmt = $conn->prepare($payment_sql);
                        $payment_stmt->bind_param("iiiissi", $order_id, $order['customer_id'], $payment_method_id, $amount, $transaction_reference, $notes, $user_id);
                        $payment_stmt->execute();
                        
                        // Update order payment status
                        $new_paid_amount = $order['paid_amount'] + $amount;
                        $new_balance = $order['total_amount'] - $new_paid_amount;
                        
                        $payment_status = 'PENDING';
                        if ($new_balance <= 0) {
                            $payment_status = 'PAID';
                        } elseif ($new_paid_amount > 0) {
                            $payment_status = 'PARTIAL';
                        }
                        
                        $update_order_sql = "UPDATE orders SET 
                                            paid_amount = ?, 
                                            balance_amount = ?, 
                                            payment_status = ? 
                                            WHERE order_id = ?";
                        $update_stmt = $conn->prepare($update_order_sql);
                        $update_stmt->bind_param("ddsi", $new_paid_amount, $new_balance, $payment_status, $order_id);
                        $update_stmt->execute();
                        
                        $conn->commit();
                        $response['success'] = true;
                        $response['message'] = 'Payment recorded successfully';
                        
                    } catch (Exception $e) {
                        $conn->rollback();
                        throw $e;
                    }
                    break;
                    
                case 'refund_payment':
                    $payment_id = $_POST['payment_id'];
                    $refund_reason = trim($_POST['refund_reason']);
                    
                    $conn->begin_transaction();
                    
                    try {
                        // Get payment details
                        $payment_sql = "SELECT * FROM payments WHERE payment_id = ? AND status = 'COMPLETED'";
                        $payment_stmt = $conn->prepare($payment_sql);
                        $payment_stmt->bind_param("i", $payment_id);
                        $payment_stmt->execute();
                        $payment = $payment_stmt->get_result()->fetch_assoc();
                        
                        if (!$payment) {
                            $response['message'] = 'Payment not found or already refunded';
                            break;
                        }
                        
                        // Update payment status
                        $refund_sql = "UPDATE payments SET 
                                      status = 'REFUNDED', 
                                      notes = CONCAT(COALESCE(notes, ''), ?, ?) 
                                      WHERE payment_id = ?";
                        $refund_stmt = $conn->prepare($refund_sql);
                        $refund_note = "\n\nRefunded on " . date('Y-m-d H:i:s') . ": ";
                        $refund_stmt->bind_param("ssi", $refund_note, $refund_reason, $payment_id);
                        $refund_stmt->execute();
                        
                        // Update order payment status
                        $order_sql = "SELECT * FROM orders WHERE order_id = ?";
                        $order_stmt = $conn->prepare($order_sql);
                        $order_stmt->bind_param("i", $payment['order_id']);
                        $order_stmt->execute();
                        $order = $order_stmt->get_result()->fetch_assoc();
                        
                        $new_paid_amount = $order['paid_amount'] - $payment['amount'];
                        $new_balance = $order['total_amount'] - $new_paid_amount;
                        
                        $payment_status = 'PENDING';
                        if ($new_balance <= 0) {
                            $payment_status = 'PAID';
                        } elseif ($new_paid_amount > 0) {
                            $payment_status = 'PARTIAL';
                        }
                        
                        $update_order_sql = "UPDATE orders SET 
                                            paid_amount = ?, 
                                            balance_amount = ?, 
                                            payment_status = ? 
                                            WHERE order_id = ?";
                        $update_stmt = $conn->prepare($update_order_sql);
                        $update_stmt->bind_param("ddsi", $new_paid_amount, $new_balance, $payment_status, $payment['order_id']);
                        $update_stmt->execute();
                        
                        $conn->commit();
                        $response['success'] = true;
                        $response['message'] = 'Payment refunded successfully';
                        
                    } catch (Exception $e) {
                        $conn->rollback();
                        throw $e;
                    }
                    break;
            }
        }
    } catch (Exception $e) {
        $response['message'] = 'Error: ' . $e->getMessage();
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit();
}

// Get payment statistics
$sql_total_payments = "SELECT COUNT(*) as total_payments FROM payments";
$total_payments = $conn->query($sql_total_payments)->fetch_assoc()['total_payments'];

$sql_completed_payments = "SELECT COUNT(*) as completed_payments FROM payments WHERE status = 'COMPLETED'";
$completed_payments = $conn->query($sql_completed_payments)->fetch_assoc()['completed_payments'];

$sql_total_amount = "SELECT COALESCE(SUM(amount), 0) as total_amount FROM payments WHERE status = 'COMPLETED'";
$total_amount = $conn->query($sql_total_amount)->fetch_assoc()['total_amount'];

$sql_today_payments = "SELECT 
    COUNT(*) as today_count,
    COALESCE(SUM(amount), 0) as today_amount 
FROM payments 
WHERE DATE(payment_date) = CURDATE() AND status = 'COMPLETED'";
$today_payments = $conn->query($sql_today_payments)->fetch_assoc();

// Get payments with related information
$sql_payments = "SELECT 
    p.*,
    o.order_number,
    o.total_amount as order_total,
    c.first_name,
    c.last_name,
    c.phone,
    pm.method_name,
    pm.method_type,
    u.full_name as processed_by_name,
    r.receipt_number
FROM payments p
JOIN orders o ON p.order_id = o.order_id
JOIN customers c ON p.customer_id = c.customer_id
JOIN payment_methods pm ON p.payment_method_id = pm.method_id
LEFT JOIN users u ON p.processed_by = u.user_id
LEFT JOIN receipts r ON p.order_id = r.order_id AND r.is_void = 0
ORDER BY p.payment_date DESC
LIMIT 100";
$result_payments = $conn->query($sql_payments);

// Get payment methods for dropdown
$sql_payment_methods = "SELECT * FROM payment_methods WHERE is_active = 1 ORDER BY sort_order, method_name";
$result_payment_methods = $conn->query($sql_payment_methods);

// Get orders with outstanding balances for quick payment
$sql_outstanding_orders = "SELECT 
    o.order_id,
    o.order_number,
    o.total_amount,
    o.paid_amount,
    o.balance_amount,
    c.first_name,
    c.last_name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.balance_amount > 0 AND o.status != 'CANCELLED'
ORDER BY o.order_date DESC
LIMIT 20";
$result_outstanding = $conn->query($sql_outstanding_orders);

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Payment Management - Laundry System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-header {
            background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: all 0.2s ease;
        }
        
        .stat-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .stat-title {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: 0.5rem;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-change {
            font-size: 0.875rem;
            font-weight: 500;
        }
        
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-completed { background: #dcfce7; color: #166534; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-failed { background: #fee2e2; color: #991b1b; }
        .status-refunded { background: #f3e8ff; color: #7c3aed; }
        
        .method-cash { background: #f0fdf4; color: #166534; }
        .method-card { background: #dbeafe; color: #1d4ed8; }
        .method-mobile { background: #fef3c7; color: #92400e; }
        .method-bank { background: #f3e8ff; color: #7c3aed; }
        .method-credit { background: #fee2e2; color: #991b1b; }
        
        .btn-primary {
            background: #3b82f6;
            border-color: #3b82f6;
        }
        
        .btn-primary:hover {
            background: #2563eb;
            border-color: #2563eb;
        }
        
        .action-buttons {
            display: flex;
            gap: 0.5rem;
        }
        
        .action-btn {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            border: none;
            font-size: 0.75rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .search-filter-bar {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        }
        
        .filter-group {
            display: flex;
            gap: 1rem;
            align-items: end;
            flex-wrap: wrap;
        }
        
        .payment-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #3b82f6;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        @media (max-width: 768px) {
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .filter-group {
                flex-direction: column;
                align-items: stretch;
            }
            
            .action-buttons {
                flex-direction: column;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h2 class="mb-2">Payment Management</h2>
                                <p class="mb-0">Track payments, process transactions, and manage customer billing</p>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#recordPaymentModal">
                                    <i class="bi bi-plus-circle me-2"></i>Record Payment
                                </button>
                                <button type="button" class="btn btn-outline-light" onclick="exportPayments()">
                                    <i class="bi bi-download me-2"></i>Export
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-title">Total Payments</div>
                            <div class="stat-value"><?php echo number_format($total_payments); ?></div>
                            <div class="stat-change" style="color: #3b82f6;">All time payments</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Completed Payments</div>
                            <div class="stat-value" style="color: #059669;"><?php echo number_format($completed_payments); ?></div>
                            <div class="stat-change" style="color: #64748b;">Successful transactions</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Total Amount</div>
                            <div class="stat-value" style="color: #059669;">KES <?php echo number_format($total_amount); ?></div>
                            <div class="stat-change" style="color: #64748b;">Collected payments</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Today's Payments</div>
                            <div class="stat-value"><?php echo number_format($today_payments['today_count']); ?></div>
                            <div class="stat-change" style="color: #059669;">KES <?php echo number_format($today_payments['today_amount']); ?></div>
                        </div>
                    </div>

                    <!-- Search and Filter -->
                    <div class="search-filter-bar">
                        <div class="filter-group">
                            <div>
                                <label class="form-label">Search Payments</label>
                                <input type="text" class="form-control" id="searchInput" placeholder="Search by payment number, customer, order...">
                            </div>
                            <div>
                                <label class="form-label">Status</label>
                                <select class="form-select" id="statusFilter">
                                    <option value="">All Status</option>
                                    <option value="COMPLETED">Completed</option>
                                    <option value="PENDING">Pending</option>
                                    <option value="FAILED">Failed</option>
                                    <option value="REFUNDED">Refunded</option>
                                </select>
                            </div>
                            <div>
                                <label class="form-label">Payment Method</label>
                                <select class="form-select" id="methodFilter">
                                    <option value="">All Methods</option>
                                    <?php
                                    $result_payment_methods->data_seek(0);
                                    while($row = $result_payment_methods->fetch_assoc()): ?>
                                        <option value="<?php echo $row['method_name']; ?>"><?php echo $row['method_name']; ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div>
                                <label class="form-label">Date Range</label>
                                <input type="date" class="form-control" id="dateFilter" max="<?php echo date('Y-m-d'); ?>">
                            </div>
                            <div>
                                <label class="form-label">&nbsp;</label>
                                <button type="button" class="btn btn-primary d-block" onclick="filterTable()">
                                    <i class="bi bi-search"></i> Filter
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Payments Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">All Payments</h3>
                            <div>
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="refreshTable()">
                                    <i class="bi bi-arrow-clockwise me-1"></i>Refresh
                                </button>
                            </div>
                        </div>
                        <div class="table-responsive">
                            <table class="data-table" id="paymentsTable">
                                <thead>
                                    <tr>
                                        <th>Payment #</th>
                                        <th>Customer</th>
                                        <th>Order #</th>
                                        <th>Amount</th>
                                        <th>Payment Method</th>
                                        <th>Date</th>
                                        <th>Status</th>
                                        <th>Receipt</th>
                                        <th>Processed By</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while($row = $result_payments->fetch_assoc()): ?>
                                    <tr>
                                        <td>
                                            <span style="color: #3b82f6; font-weight: 600;">
                                                <?php echo $row['payment_number']; ?>
                                            </span>
                                            <?php if($row['transaction_reference']): ?>
                                                <br><small style="color: #64748b;">Ref: <?php echo $row['transaction_reference']; ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="payment-avatar me-3">
                                                    <?php echo strtoupper(substr($row['first_name'], 0, 1) . substr($row['last_name'], 0, 1)); ?>
                                                </div>
                                                <div>
                                                    <div style="font-weight: 600;"><?php echo $row['first_name'] . ' ' . $row['last_name']; ?></div>
                                                    <small style="color: #64748b;"><?php echo $row['phone']; ?></small>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <a href="view_order.php?id=<?php echo $row['order_id']; ?>" style="color: #3b82f6; text-decoration: none; font-weight: 600;">
                                                <?php echo $row['order_number']; ?>
                                            </a>
                                            <br><small style="color: #64748b;">Total: KES <?php echo number_format($row['order_total']); ?></small>
                                        </td>
                                        <td style="font-weight: 600; color: #059669;">
                                            KES <?php echo number_format($row['amount'], 2); ?>
                                        </td>
                                        <td>
                                            <?php 
                                            $method_class = match(strtolower($row['method_type'])) {
                                                'cash' => 'method-cash',
                                                'card' => 'method-card',
                                                'mobile' => 'method-mobile',
                                                'bank_transfer' => 'method-bank',
                                                'credit' => 'method-credit',
                                                default => 'method-cash'
                                            };
                                            ?>
                                            <span class="status-badge <?php echo $method_class; ?>">
                                                <?php echo $row['method_name']; ?>
                                            </span>
                                        </td>
                                        <td style="color: #64748b;">
                                            <?php echo date('M j, Y g:i A', strtotime($row['payment_date'])); ?>
                                        </td>
                                        <td>
                                            <?php 
                                            $status_class = match(strtolower($row['status'])) {
                                                'completed' => 'status-completed',
                                                'pending' => 'status-pending',
                                                'failed' => 'status-failed',
                                                'refunded' => 'status-refunded',
                                                default => 'status-pending'
                                            };
                                            ?>
                                            <span class="status-badge <?php echo $status_class; ?>">
                                                <?php echo ucfirst($row['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if($row['receipt_number']): ?>
                                                <a href="view_receipt.php?number=<?php echo $row['receipt_number']; ?>" style="color: #3b82f6; text-decoration: none;">
                                                    <?php echo $row['receipt_number']; ?>
                                                </a>
                                            <?php else: ?>
                                                <span style="color: #64748b;">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td style="color: #64748b;">
                                            <?php echo $row['processed_by_name']; ?>
                                        </td>
                                        <td>
                                            <div class="action-buttons">
                                                <button class="action-btn btn btn-sm btn-primary" onclick="viewPayment(<?php echo $row['payment_id']; ?>)" title="View Details">
                                                    <i class="bi bi-eye"></i>
                                                </button>
                                                <?php if($row['status'] === 'COMPLETED'): ?>
                                                    <button class="action-btn btn btn-sm btn-warning" onclick="refundPayment(<?php echo $row['payment_id']; ?>)" title="Refund">
                                                        <i class="bi bi-arrow-return-left"></i>
                                                    </button>
                                                <?php endif; ?>
                                                <button class="action-btn btn btn-sm btn-success" onclick="printReceipt(<?php echo $row['order_id']; ?>)" title="Print Receipt">
                                                    <i class="bi bi-printer"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Outstanding Orders (Quick Payment) -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Outstanding Orders (Quick Payment)</h3>
                        </div>
                        <div class="table-responsive">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Order #</th>
                                        <th>Customer</th>
                                        <th>Total Amount</th>
                                        <th>Paid Amount</th>
                                        <th>Balance</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $result_outstanding->data_seek(0);
                                    if($result_outstanding->num_rows > 0): ?>
                                        <?php while($row = $result_outstanding->fetch_assoc()): ?>
                                        <tr>
                                            <td>
                                                <span style="color: #3b82f6; font-weight: 600;">
                                                    <?php echo $row['order_number']; ?>
                                                </span>
                                            </td>
                                            <td style="font-weight: 600;">
                                                <?php echo $row['first_name'] . ' ' . $row['last_name']; ?>
                                            </td>
                                            <td style="font-weight: 600;">
                                                KES <?php echo number_format($row['total_amount']); ?>
                                            </td>
                                            <td style="color: #059669;">
                                                KES <?php echo number_format($row['paid_amount']); ?>
                                            </td>
                                            <td style="font-weight: 600; color: #dc2626;">
                                                KES <?php echo number_format($row['balance_amount']); ?>
                                            </td>
                                            <td>
                                                <button class="btn btn-sm btn-primary" onclick="quickPayment(<?php echo $row['order_id']; ?>, '<?php echo addslashes($row['order_number']); ?>', <?php echo $row['balance_amount']; ?>)">
                                                    <i class="bi bi-credit-card me-1"></i>Pay Now
                                                </button>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="6" class="text-center" style="color: #64748b; padding: 2rem;">
                                                No outstanding orders found
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Record Payment Modal -->
    <div class="modal fade" id="recordPaymentModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Record Payment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="recordPaymentForm">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Order <span class="text-danger">*</span></label>
                            <select class="form-select" name="order_id" id="orderSelect" required>
                                <option value="">Select order...</option>
                                <?php
                                $result_outstanding->data_seek(0);
                                while($row = $result_outstanding->fetch_assoc()): ?>
                                    <option value="<?php echo $row['order_id']; ?>" data-balance="<?php echo $row['balance_amount']; ?>">
                                        <?php echo $row['order_number']; ?> - <?php echo $row['first_name'] . ' ' . $row['last_name']; ?> 
                                        (Balance: KES <?php echo number_format($row['balance_amount']); ?>)
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Payment Method <span class="text-danger">*</span></label>
                                    <select class="form-select" name="payment_method_id" required>
                                        <option value="">Select method...</option>
                                        <?php
                                        $result_payment_methods->data_seek(0);
                                        while($row = $result_payment_methods->fetch_assoc()): ?>
                                            <option value="<?php echo $row['method_id']; ?>" data-requires-ref="<?php echo $row['requires_reference']; ?>">
                                                <?php echo $row['method_name']; ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Amount <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" name="amount" step="0.01" min="0.01" required>
                                    <small class="text-muted">Maximum: <span id="maxAmount">KES 0.00</span></small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3" id="transactionRefDiv" style="display: none;">
                            <label class="form-label">Transaction Reference</label>
                            <input type="text" class="form-control" name="transaction_reference" placeholder="Enter transaction reference...">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" rows="3" placeholder="Optional payment notes..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Record Payment</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Refund Payment Modal -->
    <div class="modal fade" id="refundModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Refund Payment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="refundForm">
                    <input type="hidden" name="payment_id" id="refund_payment_id">
                    <div class="modal-body">
                        <div class="alert alert-warning">
                            <i class="bi bi-exclamation-triangle me-2"></i>
                            This action will refund the payment and update the order balance. This cannot be undone.
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Refund Reason <span class="text-danger">*</span></label>
                            <textarea class="form-control" name="refund_reason" rows="3" required placeholder="Please provide a reason for the refund..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger">Process Refund</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Alert Container -->
    <div id="alertContainer" style="position: fixed; top: 20px; right: 20px; z-index: 9999;"></div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
    // Form submission handlers
    document.getElementById('recordPaymentForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('action', 'record_payment');
        
        fetch('', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('success', data.message);
                bootstrap.Modal.getInstance(document.getElementById('recordPaymentModal')).hide();
                setTimeout(() => window.location.reload(), 1000);
            } else {
                showAlert('error', data.message);
            }
        })
        .catch(error => {
            showAlert('error', 'An error occurred while recording payment');
        });
    });

    document.getElementById('refundForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('action', 'refund_payment');
        
        fetch('', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('success', data.message);
                bootstrap.Modal.getInstance(document.getElementById('refundModal')).hide();
                setTimeout(() => window.location.reload(), 1000);
            } else {
                showAlert('error', data.message);
            }
        })
        .catch(error => {
            showAlert('error', 'An error occurred while processing refund');
        });
    });

    // Order selection handler
    document.getElementById('orderSelect').addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        const maxAmount = selectedOption.dataset.balance || 0;
        
        document.getElementById('maxAmount').textContent = `KES ${parseFloat(maxAmount).toLocaleString('en-US', {minimumFractionDigits: 2})}`;
        document.querySelector('input[name="amount"]').max = maxAmount;
        document.querySelector('input[name="amount"]').value = maxAmount;
    });

    // Payment method selection handler
    document.querySelector('select[name="payment_method_id"]').addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        const requiresRef = selectedOption.dataset.requiresRef === '1';
        
        const refDiv = document.getElementById('transactionRefDiv');
        const refInput = document.querySelector('input[name="transaction_reference"]');
        
        if (requiresRef) {
            refDiv.style.display = 'block';
            refInput.required = true;
        } else {
            refDiv.style.display = 'none';
            refInput.required = false;
            refInput.value = '';
        }
    });

    // Action functions
    function quickPayment(orderId, orderNumber, balance) {
        // Pre-fill the record payment form
        document.getElementById('orderSelect').value = orderId;
        document.getElementById('maxAmount').textContent = `KES ${balance.toLocaleString('en-US', {minimumFractionDigits: 2})}`;
        document.querySelector('input[name="amount"]').max = balance;
        document.querySelector('input[name="amount"]').value = balance;
        
        const modal = new bootstrap.Modal(document.getElementById('recordPaymentModal'));
        modal.show();
    }

    function viewPayment(paymentId) {
        window.location.href = `view_payment.php?id=${paymentId}`;
    }

    function refundPayment(paymentId) {
        document.getElementById('refund_payment_id').value = paymentId;
        const modal = new bootstrap.Modal(document.getElementById('refundModal'));
        modal.show();
    }

    function printReceipt(orderId) {
        window.open(`print_receipt.php?order_id=${orderId}`, '_blank');
    }

    // Utility functions
    function showAlert(type, message) {
        const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
        const alertHtml = `
            <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        document.getElementById('alertContainer').innerHTML = alertHtml;
        
        setTimeout(() => {
            const alert = document.querySelector('#alertContainer .alert');
            if (alert) {
                bootstrap.Alert.getInstance(alert).close();
            }
        }, 5000);
    }

    function filterTable() {
        const searchTerm = document.getElementById('searchInput').value.toLowerCase();
        const statusFilter = document.getElementById('statusFilter').value;
        const methodFilter = document.getElementById('methodFilter').value;
        const dateFilter = document.getElementById('dateFilter').value;
        const table = document.getElementById('paymentsTable');
        const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');

        for (let i = 0; i < rows.length; i++) {
            let show = true;
            const row = rows[i];
            const cells = row.getElementsByTagName('td');
            
            // Search filter
            if (searchTerm) {
                const paymentNumber = cells[0].textContent.toLowerCase();
                const customer = cells[1].textContent.toLowerCase();
                const orderNumber = cells[2].textContent.toLowerCase();
                
                if (!paymentNumber.includes(searchTerm) && 
                    !customer.includes(searchTerm) && 
                    !orderNumber.includes(searchTerm)) {
                    show = false;
                }
            }
            
            // Status filter
            if (statusFilter && show) {
                const status = cells[6].textContent.trim().toUpperCase();
                if (status !== statusFilter) {
                    show = false;
                }
            }
            
            // Method filter
            if (methodFilter && show) {
                const method = cells[4].textContent.trim();
                if (!method.includes(methodFilter)) {
                    show = false;
                }
            }
            
            // Date filter
            if (dateFilter && show) {
                const paymentDate = cells[5].textContent.trim();
                const filterDate = new Date(dateFilter).toLocaleDateString();
                const cellDate = new Date(paymentDate).toLocaleDateString();
                if (cellDate !== filterDate) {
                    show = false;
                }
            }
            
            row.style.display = show ? '' : 'none';
        }
    }

    function refreshTable() {
        window.location.reload();
    }

    function exportPayments() {
        const filters = {
            search: document.getElementById('searchInput').value,
            status: document.getElementById('statusFilter').value,
            method: document.getElementById('methodFilter').value,
            date: document.getElementById('dateFilter').value
        };
        
        const params = new URLSearchParams(filters).toString();
        window.open(`export_payments.php?${params}`, '_blank');
    }

    // Real-time search
    document.getElementById('searchInput').addEventListener('input', filterTable);
    document.getElementById('statusFilter').addEventListener('change', filterTable);
    document.getElementById('methodFilter').addEventListener('change', filterTable);
    document.getElementById('dateFilter').addEventListener('change', filterTable);

    // Reset modal forms when hidden
    document.getElementById('recordPaymentModal').addEventListener('hidden.bs.modal', function() {
        document.getElementById('recordPaymentForm').reset();
        document.getElementById('transactionRefDiv').style.display = 'none';
        document.getElementById('maxAmount').textContent = 'KES 0.00';
    });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>