<?php
/**
 * M-Pesa Payments
 * View and manage M-Pesa payment transactions
 * Kenyan Pension & Life Insurance Management System
 */

require_once 'layouts/main.php';
require_once 'includes/auth.php';

requireLogin();
requirePermission('view_mpesa_payments');

$status = $_GET['status'] ?? '';
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-t');

$where = ["p.payment_method = 'MPESA'"];
$params = [];
$types = '';

if ($status) {
    $where[] = "p.status = ?";
    $params[] = $status;
    $types .= 's';
}

$where[] = "DATE(p.created_at) BETWEEN ? AND ?";
$params[] = $date_from;
$params[] = $date_to;
$types .= 'ss';

$whereClause = implode(' AND ', $where);

$sql = "SELECT p.*, 
       CASE 
           WHEN p.payout_type = 'WITHDRAWAL' THEN CONCAT(m1.member_number, ' - ', m1.first_name, ' ', m1.last_name)
           WHEN p.payout_type = 'CLAIM' THEN CONCAT(m2.member_number, ' - ', m2.first_name, ' ', m2.last_name)
           WHEN p.payout_type = 'SURRENDER' THEN CONCAT(m3.member_number, ' - ', m3.first_name, ' ', m3.last_name)
           ELSE 'N/A'
       END as member_name
       FROM payouts p
       LEFT JOIN withdrawal_requests wr ON p.reference_id = wr.request_id AND p.payout_type = 'WITHDRAWAL'
       LEFT JOIN members m1 ON wr.member_id = m1.member_id
       LEFT JOIN life_claims lc ON p.reference_id = lc.claim_id AND p.payout_type = 'CLAIM'
       LEFT JOIN members m2 ON lc.member_id = m2.member_id
       LEFT JOIN surrender_requests sr ON p.reference_id = sr.surrender_id AND p.payout_type = 'SURRENDER'
       LEFT JOIN members m3 ON sr.member_id = m3.member_id
       WHERE $whereClause
       ORDER BY p.created_at DESC";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$payments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$pageTitle = 'M-Pesa Payments';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'M-Pesa Payments')); ?>
    <link rel="stylesheet" href="assets/css/pension-dashboard.css">
    <?php include 'layouts/head-css.php'; ?>
</head>

<body data-sidebar="dark">
    <div id="layout-wrapper">
        <?php include 'layouts/sidebar.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="welcome-header" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>M-Pesa Payments</h2>
                                <p>View and manage M-Pesa payment transactions</p>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-12">
                            <form method="GET" class="d-inline-flex gap-2">
                                <select name="status" class="form-select" style="width: auto;">
                                    <option value="">All Status</option>
                                    <option value="PENDING" <?php echo $status === 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="PROCESSED" <?php echo $status === 'PROCESSED' ? 'selected' : ''; ?>>Processed</option>
                                    <option value="FAILED" <?php echo $status === 'FAILED' ? 'selected' : ''; ?>>Failed</option>
                                </select>
                                <input type="date" name="date_from" class="form-control" style="width: auto;" value="<?php echo $date_from; ?>">
                                <input type="date" name="date_to" class="form-control" style="width: auto;" value="<?php echo $date_to; ?>">
                                <button type="submit" class="btn btn-primary">Filter</button>
                            </form>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">M-Pesa Transactions</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Member</th>
                                                    <th>Type</th>
                                                    <th>Amount</th>
                                                    <th>Transaction Reference</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($payments)): ?>
                                                    <tr><td colspan="7" class="text-center">No M-Pesa payments found</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($payments as $payment): ?>
                                                        <tr>
                                                            <td><?php echo date('d M Y, h:i A', strtotime($payment['created_at'])); ?></td>
                                                            <td><?php echo htmlspecialchars($payment['member_name'] ?? 'N/A'); ?></td>
                                                            <td><span class="badge bg-info"><?php echo htmlspecialchars($payment['payout_type']); ?></span></td>
                                                            <td><strong>KES <?php echo number_format($payment['payout_amount'], 2); ?></strong></td>
                                                            <td><?php echo htmlspecialchars($payment['transaction_reference'] ?? 'N/A'); ?></td>
                                                            <td><span class="status-badge status-<?php echo strtolower($payment['status']); ?>"><?php echo htmlspecialchars($payment['status']); ?></span></td>
                                                            <td>
                                                                <a href="process_payout.php?id=<?php echo $payment['payout_id']; ?>" class="btn btn-sm btn-primary">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
