<?php
/**
 * Agent Commissions
 * View agent commission earnings
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
if (!isAgent()) {
    header('Location: access_denied.php');
    exit();
}

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

// Note: This assumes a commissions table exists. If not, this would need to be created.
// For now, we'll calculate from policies and premiums
$policies = $conn->query("SELECT lp.*, 
                         SUM(pr.premium_amount) as total_premiums_collected
                         FROM life_policies lp
                         LEFT JOIN premiums pr ON lp.policy_id = pr.policy_id 
                         AND pr.payment_status = 'PAID'
                         AND DATE(pr.payment_date) BETWEEN '$date_from' AND '$date_to'
                         WHERE lp.agent_id = $agent_id
                         GROUP BY lp.policy_id")->fetch_all(MYSQLI_ASSOC);

// Calculate commission (assuming 10% of first year premium, 5% renewal)
$total_commission = 0;
$commissions = [];

foreach ($policies as $policy) {
    $first_year_commission = $policy['premium_amount'] * 0.10; // 10% first year
    $renewal_commission = ($policy['total_premiums_collected'] - $policy['premium_amount']) * 0.05; // 5% renewal
    
    $policy_commission = $first_year_commission + $renewal_commission;
    $total_commission += $policy_commission;
    
    $commissions[] = [
        'policy_number' => $policy['policy_number'],
        'premium_amount' => $policy['premium_amount'],
        'total_premiums' => $policy['total_premiums_collected'] ?? $policy['premium_amount'],
        'first_year_commission' => $first_year_commission,
        'renewal_commission' => $renewal_commission,
        'total_commission' => $policy_commission
    ];
}

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My Commissions')); ?>
    <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, #f59e0b 0%, #d97706 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>My Commissions</h2>
                                <p>View your commission earnings</p>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-12">
                            <form method="GET" class="d-inline-flex gap-2">
                                <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="metrics-row">
                        <div class="metric-card contributions">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Commission</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_commission, 0); ?></div>
                            <div class="metric-change">Period total</div>
                        </div>

                        <div class="metric-card balances">
                            <div class="metric-header">
                                <h6 class="metric-title">Policies</h6>
                                <span class="metric-icon"><i class="ri-file-shield-line"></i></span>
                            </div>
                            <div class="metric-value"><?php echo count($commissions); ?></div>
                            <div class="metric-change">With commissions</div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Commission Details</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Policy Number</th>
                                                    <th>Premium Amount</th>
                                                    <th>Total Premiums Collected</th>
                                                    <th>First Year Commission (10%)</th>
                                                    <th>Renewal Commission (5%)</th>
                                                    <th>Total Commission</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($commissions)): ?>
                                                    <tr><td colspan="6" class="text-center">No commissions found</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($commissions as $comm): ?>
                                                        <tr>
                                                            <td><strong><?php echo htmlspecialchars($comm['policy_number']); ?></strong></td>
                                                            <td>KES <?php echo number_format($comm['premium_amount'], 2); ?></td>
                                                            <td>KES <?php echo number_format($comm['total_premiums'], 2); ?></td>
                                                            <td>KES <?php echo number_format($comm['first_year_commission'], 2); ?></td>
                                                            <td>KES <?php echo number_format($comm['renewal_commission'], 2); ?></td>
                                                            <td><strong>KES <?php echo number_format($comm['total_commission'], 2); ?></strong></td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                    <tr class="table-primary">
                                                        <td colspan="5"><strong>Total</strong></td>
                                                        <td><strong>KES <?php echo number_format($total_commission, 2); ?></strong></td>
                                                    </tr>
                                                <?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>
