<?php
/**
 * Contributions Management
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('view_contributions');

$pensionService = new PensionService($conn);
$action = $_GET['action'] ?? 'list';
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'create') {
    $result = $pensionService->postContribution($_POST);
    if ($result['success']) {
        $message = $result['message'];
        $messageType = 'success';
        $action = 'list';
    } else {
        $message = $result['message'];
        $messageType = 'danger';
    }
}

// Get filters
$filters = [
    'scheme_id' => $_GET['scheme_id'] ?? '',
    'member_id' => $_GET['member_id'] ?? '',
    'status' => $_GET['status'] ?? '',
    'search' => $_GET['search'] ?? ''
];

$page = $_GET['page'] ?? 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Build query
$where = ["1=1"];
$params = [];
$types = '';

if (!empty($filters['scheme_id'])) {
    $where[] = "m.scheme_id = ?";
    $params[] = $filters['scheme_id'];
    $types .= 'i';
}

if (!empty($filters['member_id'])) {
    $where[] = "c.member_id = ?";
    $params[] = $filters['member_id'];
    $types .= 'i';
}

if (!empty($filters['status'])) {
    $where[] = "c.status = ?";
    $params[] = $filters['status'];
    $types .= 's';
}

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

// Get contributions
$sql = "SELECT c.*, m.member_number, m.first_name, m.last_name, ps.scheme_name
        FROM contributions c
        INNER JOIN members m ON c.member_id = m.member_id
        LEFT JOIN pension_schemes ps ON m.scheme_id = ps.scheme_id
        WHERE $whereClause
        ORDER BY c.contribution_period DESC, c.created_at DESC
        LIMIT ? OFFSET ?";

$params[] = $perPage;
$params[] = $offset;
$types .= 'ii';

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

// Get schemes for filter
$schemes = $conn->query("SELECT scheme_id, scheme_name FROM pension_schemes WHERE is_active = 1")->fetch_all(MYSQLI_ASSOC);

$pageTitle = 'Contributions';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Contributions Management')); ?>
    <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">
                    <!-- Page Header -->
                    <div class="welcome-header" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Contributions Management</h2>
                                <p>Post, view, and manage pension contributions</p>
                            </div>
                        </div>
                    </div>

                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="contributions.php?action=create" class="btn btn-primary">
                                <i class="ri-file-add-line me-2"></i>Post Contribution
                            </a>
                            <a href="bulk_upload_contributions.php" class="btn btn-success">
                                <i class="ri-upload-line me-2"></i>Bulk Upload
                            </a>
                        </div>
                    </div>

                    <?php if ($action === 'create'): ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Post Contribution</h4>
                                    </div>
                                    <div class="page-card-body">
                                        <form method="POST">
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Member <span class="text-danger">*</span></label>
                                                    <select name="member_id" id="member_id" class="form-select" required>
                                                        <option value="">Select Member</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Account ID</label>
                                                    <input type="text" name="account_id" id="account_id" class="form-control" readonly>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Contribution Type <span class="text-danger">*</span></label>
                                                    <select name="contribution_type" class="form-select" required>
                                                        <option value="EMPLOYEE">Employee</option>
                                                        <option value="EMPLOYER">Employer</option>
                                                        <option value="VOLUNTARY">Voluntary</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Contribution Period <span class="text-danger">*</span></label>
                                                    <input type="date" name="contribution_period" class="form-control" required>
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Amount (KES) <span class="text-danger">*</span></label>
                                                    <input type="number" name="contribution_amount" class="form-control" step="0.01" required>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Reference Number</label>
                                                    <input type="text" name="reference_number" class="form-control">
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Payment Method</label>
                                                    <select name="payment_method" class="form-select">
                                                        <option value="">Select Method</option>
                                                        <option value="MPESA">M-Pesa</option>
                                                        <option value="BANK_TRANSFER">Bank Transfer</option>
                                                        <option value="CHEQUE">Cheque</option>
                                                        <option value="CASH">Cash</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <button type="submit" class="btn btn-primary">Post Contribution</button>
                                            <a href="contributions.php" class="btn btn-secondary">Cancel</a>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Contributions List</h4>
                                    </div>
                                    <div class="page-card-body">
                                        <form method="GET" class="mb-3">
                                            <div class="row">
                                                <div class="col-md-3 mb-2">
                                                    <select name="scheme_id" class="form-select">
                                                        <option value="">All Schemes</option>
                                                        <?php foreach ($schemes as $scheme): ?>
                                                            <option value="<?php echo $scheme['scheme_id']; ?>" <?php echo $filters['scheme_id'] == $scheme['scheme_id'] ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($scheme['scheme_name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-2 mb-2">
                                                    <select name="status" class="form-select">
                                                        <option value="">All Status</option>
                                                        <option value="PENDING" <?php echo $filters['status'] === 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                                        <option value="PROCESSED" <?php echo $filters['status'] === 'PROCESSED' ? 'selected' : ''; ?>>Processed</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-2 mb-2">
                                                    <button type="submit" class="btn btn-primary w-100">Filter</button>
                                                </div>
                                            </div>
                                        </form>
                                        
                                        <div class="table-responsive">
                                            <table class="data-table">
                                                <thead>
                                                    <tr>
                                                        <th>Period</th>
                                                        <th>Member</th>
                                                        <th>Type</th>
                                                        <th>Amount (KES)</th>
                                                        <th>Status</th>
                                                        <th>Date</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php if (empty($contributions)): ?>
                                                        <tr><td colspan="7" class="text-center">No contributions found</td></tr>
                                                    <?php else: ?>
                                                        <?php foreach ($contributions as $contrib): ?>
                                                            <tr>
                                                                <td><?php echo date('M Y', strtotime($contrib['contribution_period'])); ?></td>
                                                                <td><?php echo htmlspecialchars($contrib['member_number'] . ' - ' . $contrib['first_name'] . ' ' . $contrib['last_name']); ?></td>
                                                                <td><?php echo htmlspecialchars($contrib['contribution_type']); ?></td>
                                                                <td>KES <?php echo number_format($contrib['contribution_amount'], 2); ?></td>
                                                                <td>
                                                                    <span class="badge bg-<?php echo $contrib['status'] === 'PROCESSED' ? 'success' : 'warning'; ?>">
                                                                        <?php echo htmlspecialchars($contrib['status']); ?>
                                                                    </span>
                                                                </td>
                                                                <td><?php echo date('d M Y', strtotime($contrib['created_at'])); ?></td>
                                                                <td>
                                                                    <a href="contribution_details.php?id=<?php echo $contrib['contribution_id']; ?>" class="btn btn-sm btn-info" title="View Details">
                                                                        <i class="ri-eye-line"></i>
                                                                    </a>
                                                                    <?php if ($contrib['status'] === 'PROCESSED'): ?>
                                                                        <button onclick="generateETIMSInvoice(<?php echo $contrib['contribution_id']; ?>, 'CONTRIBUTION')" class="btn btn-sm btn-warning" title="Generate eTIMS Invoice">
                                                                            <i class="ri-file-invoice-line"></i>
                                                                        </button>
                                                                    <?php endif; ?>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
    function generateETIMSInvoice(sourceId, sourceType) {
        if (!confirm('Generate eTIMS invoice for this ' + sourceType.toLowerCase() + '?')) {
            return;
        }
        
        $.ajax({
            url: 'ajax/generate_etims_invoice.php',
            method: 'POST',
            data: {
                source_id: sourceId,
                source_type: sourceType
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    alert('eTIMS invoice generated successfully!\nInvoice Number: ' + (response.invoice_number || 'N/A'));
                    location.reload();
                } else {
                    alert('Error: ' + (response.message || 'Failed to generate invoice'));
                }
            },
            error: function() {
                alert('Error generating invoice. Please try again.');
            }
        });
    }
    </script>
</body>
</html>
