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

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

// Require admin access
requireLogin();
if (!isAdmin()) {
    header('Location: access_denied.php');
    exit();
}

// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, r.role_name FROM users u INNER JOIN roles r ON u.role_id = r.role_id WHERE u.user_id = ? AND u.deleted_at IS NULL";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

$profile = json_decode($user_details['profile'] ?? '{}', true);
$full_name = isset($profile['first_name']) && isset($profile['last_name']) 
    ? $profile['first_name'] . ' ' . $profile['last_name'] 
    : ($user_details['username'] ?? 'Admin');

// Get dashboard stats
$total_schemes = $conn->query("SELECT COUNT(*) as count FROM pension_schemes WHERE is_active = 1")->fetch_assoc()['count'] ?? 0;
$total_members = $conn->query("SELECT COUNT(*) as count FROM members WHERE is_active = 1")->fetch_assoc()['count'] ?? 0;
$total_policies = $conn->query("SELECT COUNT(*) as count FROM life_policies WHERE policy_status = 'ACTIVE'")->fetch_assoc()['count'] ?? 0;
$pending_claims = $conn->query("SELECT COUNT(*) as count FROM life_claims WHERE claim_status = 'PENDING'")->fetch_assoc()['count'] ?? 0;

// Include dashboard header
$pageTitle = 'Admin Dashboard';
include 'layouts/topbar.php';
?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Admin Dashboard')); ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/apexcharts@latest/dist/apexcharts.css">
    <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">
                    <!-- Welcome Header -->
                    <div class="welcome-header">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>
                                    <?php 
                                    $hour = date('H');
                                    $greeting = $hour < 12 ? 'Good Morning' : ($hour < 17 ? 'Good Afternoon' : 'Good Evening');
                                    echo $greeting . ', ' . htmlspecialchars($full_name);
                                    ?>
                                </h2>
                                <p>Admin Dashboard - Pension & Life Insurance Management System</p>
                                <small style="opacity: 0.8;">Kenyan Retirement Benefits & Life Insurance Administration</small>
                            </div>
                            <div class="datetime-display d-none d-md-block">
                                <div class="current-time" id="currentTime"><?php echo date('h:i A'); ?></div>
                                <div class="current-date" id="currentDate"><?php echo date('l, M j, Y'); ?></div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="metrics-row">
                        <div class="metric-card schemes">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Total Schemes</h6>
                                </div>
                                <span class="metric-icon"><i class="ri-building-line"></i></span>
                            </div>
                            <div class="metric-value" id="total-schemes"><?php echo number_format($total_schemes); ?></div>
                            <div class="metric-change">Active pension schemes</div>
                            <a href="schemes.php" class="metric-link">
                                Manage schemes <i class="ri-arrow-right-line"></i>
                            </a>
                        </div>

                        <div class="metric-card members">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Total Members</h6>
                                </div>
                                <span class="metric-icon"><i class="ri-user-line"></i></span>
                            </div>
                            <div class="metric-value" id="total-members"><?php echo number_format($total_members); ?></div>
                            <div class="metric-change">Active pension members</div>
                            <a href="members.php" class="metric-link">
                                View all members <i class="ri-arrow-right-line"></i>
                            </a>
                        </div>

                        <div class="metric-card policies">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Active Policies</h6>
                                </div>
                                <span class="metric-icon"><i class="ri-file-shield-line"></i></span>
                            </div>
                            <div class="metric-value" id="total-policies"><?php echo number_format($total_policies); ?></div>
                            <div class="metric-change">Life insurance policies</div>
                            <a href="policies.php" class="metric-link">
                                View policies <i class="ri-arrow-right-line"></i>
                            </a>
                        </div>

                        <div class="metric-card claims">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Pending Claims</h6>
                                </div>
                                <span class="metric-icon"><i class="ri-file-list-3-line"></i></span>
                            </div>
                            <div class="metric-value" id="pending-claims"><?php echo number_format($pending_claims); ?></div>
                            <div class="metric-change">Requires attention</div>
                            <a href="claims.php?status=PENDING" class="metric-link">
                                Process claims <i class="ri-arrow-right-line"></i>
                            </a>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="row">
                        <div class="col-12">
                            <h5 class="mb-3" style="color: #2563eb; font-weight: 600;">Quick Actions</h5>
                        </div>
                    </div>
                    <div class="quick-actions">
                        <a href="members.php?action=create" class="quick-action">
                            <span class="quick-action-icon"><i class="ri-user-add-line"></i></span>
                            <div class="quick-action-title">Add Member</div>
                            <p class="quick-action-desc">Register new member</p>
                        </a>
                        <a href="contributions.php?action=create" class="quick-action">
                            <span class="quick-action-icon"><i class="ri-file-add-line"></i></span>
                            <div class="quick-action-title">Post Contribution</div>
                            <p class="quick-action-desc">Record contribution</p>
                        </a>
                        <a href="policies.php?action=create" class="quick-action">
                            <span class="quick-action-icon"><i class="ri-file-shield-line"></i></span>
                            <div class="quick-action-title">New Policy</div>
                            <p class="quick-action-desc">Create life policy</p>
                        </a>
                        <a href="process_withdrawal.php" class="quick-action">
                            <span class="quick-action-icon"><i class="ri-money-dollar-circle-line"></i></span>
                            <div class="quick-action-title">Process Withdrawal</div>
                            <p class="quick-action-desc">Handle withdrawal</p>
                        </a>
                        <a href="process_claim.php" class="quick-action">
                            <span class="quick-action-icon"><i class="ri-file-list-3-line"></i></span>
                            <div class="quick-action-title">Process Claim</div>
                            <p class="quick-action-desc">Life insurance claim</p>
                        </a>
                        <a href="scheme_reports.php" class="quick-action">
                            <span class="quick-action-icon"><i class="ri-file-chart-line"></i></span>
                            <div class="quick-action-title">Reports</div>
                            <p class="quick-action-desc">View analytics</p>
                        </a>
                    </div>

                    <!-- Recent Activity -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Recent Activity</h3>
                        </div>
                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Event</th>
                                                    <th>User</th>
                                                    <th>Details</th>
                                                </tr>
                                            </thead>
                            <tbody id="recent-activity">
                                <tr>
                                    <td colspan="4" class="text-center">Loading...</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts@latest/dist/apexcharts.min.js"></script>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Update time and date
        function updateDateTime() {
            const now = new Date();
            const timeElement = document.getElementById('currentTime');
            const dateElement = document.getElementById('currentDate');
            
            if (timeElement) {
                timeElement.textContent = now.toLocaleTimeString('en-US', {
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: true
                });
            }
            
            if (dateElement) {
                dateElement.textContent = now.toLocaleDateString('en-US', {
                    weekday: 'long',
                    month: 'short',
                    day: 'numeric',
                    year: 'numeric'
                });
            }
        }
        
        setInterval(updateDateTime, 60000);
        updateDateTime();
        
        // Load recent activity
        if (typeof $ !== 'undefined') {
            $.ajax({
                url: 'ajax/get_recent_activity.php',
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.data.length > 0) {
                        let html = '';
                        response.data.forEach(function(activity) {
                            html += `
                                <tr>
                                    <td>${activity.created_at}</td>
                                    <td><span class="status-badge status-${activity.badge_color || 'pending'}">${activity.event_type}</span></td>
                                    <td>${activity.performed_by}</td>
                                    <td>${activity.event_description}</td>
                                </tr>
                            `;
                        });
                        $('#recent-activity').html(html);
                    } else {
                        $('#recent-activity').html('<tr><td colspan="4" class="text-center">No recent activity</td></tr>');
                    }
                },
                error: function() {
                    $('#recent-activity').html('<tr><td colspan="4" class="text-center">Failed to load activity</td></tr>');
                }
            });
        }
    });
    </script>
</body>
</html>
