<?php
session_start();
ob_start();

// Debug mode - set to false for production
define('DEBUG', false);

if (!isset($_SESSION['member_id'])) {
    header("Location: login.php");
    exit;
}

require_once './includes/config.php';
require_once './auth/middleware.php';
outputSessionTimeoutWarning();

// Function to safely display member information
function displayInfo($label, $value, $default = 'Not specified', $format = null) {
    if ($value === null || $value === '') {
        $displayValue = $default;
    } else {
        $displayValue = htmlspecialchars($value);
        if ($format === 'date' && !empty($value)) {
            $displayValue = date('M j, Y', strtotime($value));
        } elseif ($format === 'datetime' && !empty($value)) {
            $displayValue = date('M j, Y H:i', strtotime($value));
        }
    }
    
}

try {
    // Fetch member details
    $stmt = $pdo->prepare("
        SELECT 
            id, member_number, first_name, middle_name, last_name,
            date_of_birth, gender, citizenship, id_number, kra_pin,
            email_address, phone_number, address, city,
            personal_number, position_id, employer_id, branch_id,
            registration_date, admission_date, status,
            kyc_verified, kyc_verified_at, passport_photo,
            created_at, updated_at, created_by
        FROM members 
        WHERE id = ?
    ");
    
    if (!$stmt->execute([$_SESSION['member_id']])) {
        throw new Exception("Failed to fetch member data: " . implode(" ", $stmt->errorInfo()));
    }
    
    $member = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$member) {
        throw new Exception("No member found with ID: " . $_SESSION['member_id']);
    }
$member = array_merge([
    'id' => '',
    'member_number' => '',
    'first_name' => '',
    'middle_name' => '',
    'last_name' => '',
    'date_of_birth' => '',
    'gender' => '',
    'citizenship' => '',
    'id_number' => '',
    'kra_pin' => '',
    'email_address' => '',
    'phone_number' => '',
    'address' => '',
    'city' => '',
    'personal_number' => '',
    'position_id' => '',
    'employer_id' => '',
    'branch_id' => '',
    'registration_date' => '',
    'admission_date' => '',
    'status' => 'inactive', // Default to inactive
    'kyc_verified' => 0, // Default to not verified
    'kyc_verified_at' => '',
    'passport_photo' => '',
    'created_at' => '',
    'updated_at' => '',
    'created_by' => 'System'
], $member ?? []); // Merge with actual member data if it exists
    // Verify KYC status
    if (!$member['kyc_verified']) {
        header("Location: verify_kyc.php");
        exit;
    }

    // Fetch member accounts
    $accountsStmt = $pdo->prepare("
        SELECT ma.*, at.account_name, at.description
        FROM member_accounts ma
        JOIN account_types at ON ma.account_type_id = at.id
        WHERE ma.member_id = ?
        ORDER BY ma.account_type_id, ma.sub_account_code
    ");
    
    $accountsStmt->execute([$_SESSION['member_id']]);
    $accounts = $accountsStmt->fetchAll(PDO::FETCH_ASSOC);

    // Organize accounts by type
    $organizedAccounts = [];
    foreach ($accounts as $account) {
        if (!isset($organizedAccounts[$account['account_type_id']])) {
            $organizedAccounts[$account['account_type_id']] = [
                'name' => $account['account_name'],
                'description' => $account['description'],
                'sub_accounts' => []
            ];
        }
        $organizedAccounts[$account['account_type_id']]['sub_accounts'][$account['sub_account_code']] = $account;
    }
    
    // Fetch recent transactions (last 5)
    $transactionsStmt = $pdo->prepare("
        SELECT * FROM transactions
        WHERE member_id = ?
        ORDER BY transaction_date DESC
        LIMIT 5
    ");
    $transactionsStmt->execute([$_SESSION['member_id']]);
    $recentTransactions = $transactionsStmt->fetchAll(PDO::FETCH_ASSOC);
    
    
    // Fetch company name
    if (!isset($_SESSION['company_name'])) {
        $companyStmt = $pdo->query("SELECT company_name FROM company_settings LIMIT 1");
        $_SESSION['company_name'] = $companyStmt->fetchColumn();
    }

} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
} catch (Exception $e) {
    die("Error: " . $e->getMessage());
}

$companyName = htmlspecialchars($_SESSION['company_name'] ?? 'Member Portal');
$title = 'Member Dashboard';
$subTitle = 'Welcome back, ' . htmlspecialchars($member['first_name']);
?>




<h2>My Accounts & Balances</h2>

<?php if (!empty($organizedAccounts)): ?>
    <?php foreach ($organizedAccounts as $typeId => $typeData): ?>
        <div class="account-type-card">
            <h3><?php echo htmlspecialchars($typeData['name']); ?></h3>
            <p><?php echo htmlspecialchars($typeData['description']); ?></p>
            <table class="account-table">
                <thead>
                    <tr>
                        <th>Sub Account</th>
                        <th>Account Number</th>
                        <th>Balance</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($typeData['sub_accounts'] as $subCode => $account): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($subCode); ?></td>
                            <td><?php echo htmlspecialchars($account['account_number']); ?></td>
                            <td>KES <?php echo number_format($account['current_balance'], 2); ?></td>
                            <td><?php echo htmlspecialchars(ucfirst($account['status'])); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endforeach; ?>
<?php else: ?>
    <p>You currently have no accounts.</p>
<?php endif; ?>
