<?php
/**
 * Withdrawal Reports
 * Generate withdrawal reports
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('view_withdrawal_reports');

$scheme_id = $_GET['scheme_id'] ?? '';
$withdrawal_type = $_GET['withdrawal_type'] ?? '';
$date_from = $_GET['date_from'] ?? date('Y-m-01', strtotime('-12 months'));
$date_to = $_GET['date_to'] ?? date('Y-m-t');

$where = ["1=1"];
$params = [];
$types = '';

if ($scheme_id) {
    $where[] = "wr.scheme_id = ?";
    $params[] = $scheme_id;
    $types .= 'i';
}

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

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

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

$sql = "SELECT wr.*, m.member_number, m.first_name, m.last_name, ps.scheme_name
        FROM withdrawal_requests wr
        INNER JOIN members m ON wr.member_id = m.member_id
        LEFT JOIN pension_schemes ps ON wr.scheme_id = ps.scheme_id
        WHERE $whereClause
        ORDER BY wr.requested_date DESC";

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

// Calculate totals
$total_requested = array_sum(array_column($withdrawals, 'requested_amount'));
$total_processed = array_sum(array_filter(array_column($withdrawals, 'calculated_amount'), function($v) { return $v > 0; }));

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

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Withdrawal Reports')); ?>
    <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, #8b5cf6 0%, #7c3aed 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Withdrawal Reports</h2>
                                <p>Generate comprehensive withdrawal reports</p>
                            </div>
                        </div>
                    </div>

                    <div class="metrics-row">
                        <div class="metric-card withdrawals">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Requested</h6>
                                <span class="metric-icon"><i class="ri-money-dollar-circle-line"></i></span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format($total_requested, 0); ?></div>
                        </div>

                        <div class="metric-card balances">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Processed</h6>
                                <span class="metric-icon"><i class="ri-check-line"></i></span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format($total_processed, 0); ?></div>
                        </div>

                        <div class="metric-card contributions">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Requests</h6>
                                <span class="metric-icon"><i class="ri-file-list-line"></i></span>
                            </div>
                            <div class="metric-value"><?php echo count($withdrawals); ?></div>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-12">
                            <form method="GET" class="d-inline-flex gap-2">
                                <select name="scheme_id" class="form-select" style="width: auto;">
                                    <option value="">All Schemes</option>
                                    <?php foreach ($schemes as $scheme): ?>
                                        <option value="<?php echo $scheme['scheme_id']; ?>" <?php echo $scheme_id == $scheme['scheme_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($scheme['scheme_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <select name="withdrawal_type" class="form-select" style="width: auto;">
                                    <option value="">All Types</option>
                                    <option value="EARLY_EXIT" <?php echo $withdrawal_type === 'EARLY_EXIT' ? 'selected' : ''; ?>>Early Exit</option>
                                    <option value="RETIREMENT" <?php echo $withdrawal_type === 'RETIREMENT' ? 'selected' : ''; ?>>Retirement</option>
                                    <option value="DISABILITY" <?php echo $withdrawal_type === 'DISABILITY' ? 'selected' : ''; ?>>Disability</option>
                                    <option value="EMIGRATION" <?php echo $withdrawal_type === 'EMIGRATION' ? 'selected' : ''; ?>>Emigration</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>
                                <button type="button" onclick="window.print()" class="btn btn-success">
                                    <i class="ri-printer-line me-2"></i>Print
                                </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">Withdrawal Details</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Member</th>
                                                    <th>Scheme</th>
                                                    <th>Type</th>
                                                    <th>Requested</th>
                                                    <th>Processed</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($withdrawals)): ?>
                                                    <tr><td colspan="7" class="text-center">No withdrawals found</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($withdrawals as $withdrawal): ?>
                                                        <tr>
                                                            <td><?php echo date('d M Y', strtotime($withdrawal['requested_date'])); ?></td>
                                                            <td><?php echo htmlspecialchars($withdrawal['member_number'] . ' - ' . $withdrawal['first_name'] . ' ' . $withdrawal['last_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($withdrawal['scheme_name'] ?? 'N/A'); ?></td>
                                                            <td><span class="badge bg-info"><?php echo htmlspecialchars($withdrawal['withdrawal_type']); ?></span></td>
                                                            <td>KES <?php echo number_format($withdrawal['requested_amount'], 2); ?></td>
                                                            <td>KES <?php echo number_format($withdrawal['calculated_amount'] ?? 0, 2); ?></td>
                                                            <td><span class="status-badge status-<?php echo strtolower($withdrawal['status']); ?>"><?php echo htmlspecialchars($withdrawal['status']); ?></span></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>
