<?php
/**
 * Agent Reports
 * Generate agent performance reports
 * 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');

// Get agent statistics
$total_policies = $conn->query("SELECT COUNT(*) as count FROM life_policies WHERE agent_id = $agent_id")->fetch_assoc()['count'];
$active_policies = $conn->query("SELECT COUNT(*) as count FROM life_policies WHERE agent_id = $agent_id AND policy_status = 'ACTIVE'")->fetch_assoc()['count'];
$total_sum_assured = $conn->query("SELECT COALESCE(SUM(sum_assured), 0) as total FROM life_policies WHERE agent_id = $agent_id")->fetch_assoc()['total'];
$total_clients = $conn->query("SELECT COUNT(DISTINCT member_id) as count FROM life_policies WHERE agent_id = $agent_id")->fetch_assoc()['count'];

// Get policies created in period
$policies_period = $conn->query("SELECT COUNT(*) as count FROM life_policies 
                                WHERE agent_id = $agent_id 
                                AND DATE(created_at) BETWEEN '$date_from' AND '$date_to'")->fetch_assoc()['count'];

// Get policies by status
$policies_by_status = $conn->query("SELECT policy_status, COUNT(*) as count 
                                   FROM life_policies 
                                   WHERE agent_id = $agent_id 
                                   GROUP BY policy_status")->fetch_all(MYSQLI_ASSOC);

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Agent 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, #ec4899 0%, #db2777 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Agent Performance Reports</h2>
                                <p>View your sales and performance statistics</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">Generate Report</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="metrics-row">
                        <div class="metric-card policies">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Policies</h6>
                                <span class="metric-icon"><i class="ri-file-shield-line"></i></span>
                            </div>
                            <div class="metric-value"><?php echo $total_policies; ?></div>
                            <div class="metric-change">All time</div>
                        </div>

                        <div class="metric-card balances">
                            <div class="metric-header">
                                <h6 class="metric-title">Active Policies</h6>
                                <span class="metric-icon"><i class="ri-check-line"></i></span>
                            </div>
                            <div class="metric-value"><?php echo $active_policies; ?></div>
                            <div class="metric-change">Currently active</div>
                        </div>

                        <div class="metric-card withdrawals">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Clients</h6>
                                <span class="metric-icon"><i class="ri-user-line"></i></span>
                            </div>
                            <div class="metric-value"><?php echo $total_clients; ?></div>
                            <div class="metric-change">Unique clients</div>
                        </div>

                        <div class="metric-card contributions">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Sum Assured</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_sum_assured, 0); ?></div>
                            <div class="metric-change">All policies</div>
                        </div>

                        <div class="metric-card claims">
                            <div class="metric-header">
                                <h6 class="metric-title">Policies This Period</h6>
                                <span class="metric-icon"><i class="ri-calendar-line"></i></span>
                            </div>
                            <div class="metric-value"><?php echo $policies_period; ?></div>
                            <div class="metric-change">New policies</div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Policies by Status</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Status</th>
                                                    <th>Count</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($policies_by_status)): ?>
                                                    <tr><td colspan="2" class="text-center">No data available</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($policies_by_status as $status): ?>
                                                        <tr>
                                                            <td><span class="status-badge status-<?php echo strtolower($status['policy_status']); ?>"><?php echo htmlspecialchars($status['policy_status']); ?></span></td>
                                                            <td><strong><?php echo $status['count']; ?></strong></td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Performance Summary</h4>
                                </div>
                                <div class="page-card-body">
                                    <table class="table table-borderless">
                                        <tr>
                                            <td><strong>Report Period:</strong></td>
                                            <td><?php echo date('d M Y', strtotime($date_from)); ?> to <?php echo date('d M Y', strtotime($date_to)); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>New Policies:</strong></td>
                                            <td><?php echo $policies_period; ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Active Rate:</strong></td>
                                            <td><?php echo $total_policies > 0 ? number_format(($active_policies / $total_policies) * 100, 1) : 0; ?>%</td>
                                        </tr>
                                        <tr>
                                            <td><strong>Average Sum Assured:</strong></td>
                                            <td>KES <?php echo $total_policies > 0 ? number_format($total_sum_assured / $total_policies, 0) : 0; ?></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
