<?php
if (!isset($memberContextLoaded)) {
    $memberContextLoaded = true;

    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    require_once __DIR__ . '/config.php';

    $memberId = $_SESSION['member_id'] ?? null;

    if (!$memberId) {
        header("Location: index.php");
        exit;
    }

    try {
        $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([$memberId])) {
            throw new Exception("Failed to fetch member data: " . implode(" ", $stmt->errorInfo()));
        }

        $member = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$member) {
            echo "<script>alert('Member not found.'); window.location.href='index.php';</script>";
            exit;
        }

        // Merge with default values
        $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',
            'kyc_verified' => 0,
            'kyc_verified_at' => '',
            'passport_photo' => '',
            'created_at' => '',
            'updated_at' => '',
            'created_by' => 'System'
        ], $member ?? []);

        // Construct full member name
        $member['member_name'] = trim($member['first_name'] . ' ' . $member['middle_name'] . ' ' . $member['last_name']);

        // Check KYC verification only on dashboard page
        if (basename($_SERVER['SCRIPT_NAME']) === 'dashboard.php' && !$member['kyc_verified']) {
            header("Location: verify_kyc.php");
            exit;
        }

        // Fallback photo
        if (empty($member['passport_photo']) || !file_exists($member['passport_photo'])) {
            $member['passport_photo'] = '../uploads/default.png';
        }

        // Make $member globally accessible
        $GLOBALS['member'] = $member;

    } catch (Exception $e) {
        // You can log this error instead of echoing it
        echo "<script>alert('Error loading member details. Please try again later.'); window.location.href='index.php';</script>";
        exit;
    }
}
