<?php
/**
 * Member Portal
 * Self-service portal for members
 * Kenyan Pension & Life Insurance Management System
 */

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

// Require login and member role
requireLogin();
if (!isMember()) {
    header('Location: access_denied.php');
    exit();
}

// Initialize services
$memberService = new MemberService($conn);
$member_id = $_SESSION['user_id']; // Assuming user_id maps to member_id

// Get member data
$member = $memberService->getMember($member_id);
if (!$member) {
    header('Location: logout.php');
    exit();
}

// Get member account details
$accountSql = "SELECT * FROM member_accounts WHERE member_id = ?";
$accountStmt = $conn->prepare($accountSql);
$accountStmt->bind_param("i", $member_id);
$accountStmt->execute();
$account = $accountStmt->get_result()->fetch_assoc();

// Get recent contributions
$contributionsSql = "SELECT * FROM contributions 
                     WHERE member_id = ? 
                     ORDER BY contribution_period DESC 
                     LIMIT 10";
$contributionsStmt = $conn->prepare($contributionsSql);
$contributionsStmt->bind_param("i", $member_id);
$contributionsStmt->execute();
$contributions = $contributionsStmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get beneficiaries
$beneficiaries = $memberService->getBeneficiaries($member_id);

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Member Portal')); ?>
    <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" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Welcome, <?php echo htmlspecialchars($member['first_name']); ?>!</h2>
                                <p>Member Self-Service Portal - Pension & Life Insurance</p>
                                <small style="opacity: 0.8;">Member Number: <?php echo htmlspecialchars($member['member_number']); ?></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>

                    <!-- Account Summary -->
                    <div class="metrics-row">
                        <div class="metric-card balances">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Accrued Benefits</h6>
                                </div>
                                <span class="metric-icon"><i class="ri-wallet-line"></i></span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format($account['accrued_benefits'] ?? 0, 2); ?></div>
                            <div class="metric-change">Total pension value</div>
                            <a href="member_statements.php" class="metric-link">
                                View statement <i class="ri-arrow-right-line"></i>
                            </a>
                        </div>

                        <div class="metric-card withdrawals">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Available Balance</h6>
                                </div>
                                <span class="metric-icon"><i class="ri-money-dollar-circle-line"></i></span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format($account['available_balance'] ?? 0, 2); ?></div>
                            <div class="metric-change">Available for withdrawal</div>
                            <a href="request_withdrawal.php" class="metric-link">
                                Request withdrawal <i class="ri-arrow-right-line"></i>
                            </a>
                        </div>

                        <div class="metric-card contributions">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Total Contributions</h6>
                                </div>
                                <span class="metric-icon"><i class="ri-file-add-line"></i></span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format(($account['total_employee_contributions'] ?? 0) + ($account['total_employer_contributions'] ?? 0), 2); ?></div>
                            <div class="metric-change">Employee + Employer</div>
                            <a href="member_contributions.php" class="metric-link">
                                View history <i class="ri-arrow-right-line"></i>
                            </a>
                        </div>

                        <div class="metric-card balances">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Investment Returns</h6>
                                </div>
                                <span class="metric-icon"><i class="ri-line-chart-line"></i></span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format($account['allocated_investment_returns'] ?? 0, 2); ?></div>
                            <div class="metric-change">Allocated returns</div>
                            <a href="member_statements.php" class="metric-link">
                                View details <i class="ri-arrow-right-line"></i>
                            </a>
                        </div>
                    </div>

                    <!-- Member Information -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Personal Information</h4>
                                </div>
                                <div class="page-card-body">
                                    <table class="table table-borderless">
                                        <tr>
                                            <td><strong>Member Number:</strong></td>
                                            <td><?php echo htmlspecialchars($member['member_number']); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Name:</strong></td>
                                            <td><?php echo htmlspecialchars($member['first_name'] . ' ' . $member['last_name']); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Date of Birth:</strong></td>
                                            <td><?php echo date('d M Y', strtotime($member['date_of_birth'])); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Scheme:</strong></td>
                                            <td><?php echo htmlspecialchars($member['scheme_name'] ?? 'N/A'); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Employment Status:</strong></td>
                                            <td>
                                                <span class="badge bg-<?php echo $member['employment_status'] === 'ACTIVE' ? 'success' : 'secondary'; ?>">
                                                    <?php echo htmlspecialchars($member['employment_status']); ?>
                                                </span>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Account Breakdown</h4>
                                </div>
                                <div class="page-card-body">
                                    <table class="table table-borderless">
                                        <tr>
                                            <td><strong>Employee Contributions:</strong></td>
                                            <td class="text-end">KES <?php echo number_format($account['total_employee_contributions'] ?? 0, 2); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Employer Contributions:</strong></td>
                                            <td class="text-end">KES <?php echo number_format($account['total_employer_contributions'] ?? 0, 2); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Investment Returns:</strong></td>
                                            <td class="text-end">KES <?php echo number_format($account['allocated_investment_returns'] ?? 0, 2); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Total Withdrawn:</strong></td>
                                            <td class="text-end">KES <?php echo number_format($account['total_withdrawn'] ?? 0, 2); ?></td>
                                        </tr>
                                        <tr class="border-top">
                                            <td><strong>Available Balance:</strong></td>
                                            <td class="text-end"><strong>KES <?php echo number_format($account['available_balance'] ?? 0, 2); ?></strong></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Contributions -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Recent Contributions</h3>
                        </div>
                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Period</th>
                                                    <th>Type</th>
                                                    <th>Amount</th>
                                                    <th>Status</th>
                                                    <th>Date</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($contributions)): ?>
                                                    <tr>
                                                        <td colspan="5" class="text-center">No contributions found</td>
                                                    </tr>
                                                <?php else: ?>
                                                    <?php foreach ($contributions as $contribution): ?>
                                                        <tr>
                                                            <td><?php echo date('M Y', strtotime($contribution['contribution_period'])); ?></td>
                                                            <td><?php echo htmlspecialchars($contribution['contribution_type']); ?></td>
                                                            <td>KES <?php echo number_format($contribution['contribution_amount'], 2); ?></td>
                                                            <td>
                                                                <span class="badge bg-<?php echo $contribution['status'] === 'PROCESSED' ? 'success' : 'warning'; ?>">
                                                                    <?php echo htmlspecialchars($contribution['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo date('d M Y', strtotime($contribution['created_at'])); ?></td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Beneficiaries -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Beneficiaries</h3>
                        </div>
                        <?php if (empty($beneficiaries)): ?>
                            <div class="page-card-body">
                                <p class="text-muted">No beneficiaries registered. <a href="add_beneficiary.php">Add beneficiary</a></p>
                            </div>
                        <?php else: ?>
                            <table class="data-table">
                                                <thead>
                                                    <tr>
                                                        <th>Name</th>
                                                        <th>Relationship</th>
                                                        <th>Allocation %</th>
                                                        <th>Date Added</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($beneficiaries as $beneficiary): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($beneficiary['first_name'] . ' ' . $beneficiary['last_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($beneficiary['relationship']); ?></td>
                                                            <td><?php echo number_format($beneficiary['allocation_percentage'], 2); ?>%</td>
                                                            <td><?php echo date('d M Y', strtotime($beneficiary['created_at'])); ?></td>
                                                        </tr>
                                                    <?php endforeach; ?>
                            </tbody>
                        </table>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        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();
    });
    </script>
</body>
</html>
