<?php
// Load CORS configuration FIRST
require_once './includes/cors.php';
configureCors();

require_once __DIR__ . '/includes/config_loader.php';
require_once __DIR__ . '/includes/config.php';

// Set response headers
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// Add security headers
header('X-Frame-Options: DENY');
header('X-Content-Type-Options: nosniff');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Max-Age: 86400');
    header('Content-Length: 0');
    http_response_code(200);
    exit();
}
// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

// Authentication - user must be logged in to view member data
if (!isset($_SESSION['member_id'])) {
    http_response_code(401);
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

header('Content-Type: application/json');

// Validate member_id parameter
if (!isset($_GET['member_id'])) {
    echo json_encode(['success' => false, 'error' => 'member_id parameter is required']);
    exit;
}

$memberId = filter_var($_GET['member_id'], FILTER_VALIDATE_INT);
if ($memberId === false || $memberId <= 0) {
    echo json_encode(['success' => false, 'error' => 'Invalid member_id. Must be a positive integer']);
    exit;
}

/**
 * Get base URL for the application
 */
function getBaseUrl() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
    $pathInfo = dirname($scriptName);
    
    return $protocol . '://' . $host . rtrim($pathInfo, '/');
}

/**
 * Generate full image URL for member documents
 */
function getFullImageUrl($filePath, $baseUrl) {
    if (empty($filePath)) {
        return null;
    }
    
    // Convert relative path to absolute URL
    $filePath = str_replace(['../', './'], '', $filePath);
    
    // If path is already a URL, return it
    if (filter_var($filePath, FILTER_VALIDATE_URL)) {
        return $filePath;
    }
    
    // Generate full URL
    return rtrim($baseUrl, '/') . '/' . ltrim($filePath, '/');
}

/**
 * Fetch individual member details by ID
 */
function fetchMemberDetails($pdo, $memberId) {
    try {
        $sql = "
            SELECT 
                m.id,
                m.personal_number,
                m.member_number,
                m.employer_id,
                e.employer_name,
                m.branch_id,
                b.branch_name,
                m.position_id,
                p.position_name,
                m.first_name,
                m.middle_name,
                m.last_name,
                m.citizenship,
                m.id_number,
                m.date_of_birth,
                m.gender,
                m.phone_number,
                m.email_address,
                m.address,
                m.city,
                m.kra_pin,
                m.status,
                m.communication_preference,
                m.passport_photo,
                m.id_document,
                m.kra_pin_document,
                m.signature,
                m.registration_date,
                m.admission_date,
                m.kyc_verified,
                m.kyc_verified_at,
                m.created_by,
                m.created_at,
                m.updated_at,
                m.kyc_attempts,
                m.kyc_locked,
                CONCAT(m.first_name, ' ', COALESCE(m.middle_name, ''), ' ', m.last_name) as full_name
            FROM members m
            LEFT JOIN employers e ON m.employer_id = e.id
            LEFT JOIN branches b ON m.branch_id = b.id
            LEFT JOIN positions p ON m.position_id = p.id
            WHERE m.id = ? AND m.deleted_at IS NULL
            LIMIT 1
        ";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$memberId]);
        $member = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$member) {
            throw new Exception('Member not found');
        }
        
        return $member;
        
    } catch (Exception $e) {
        error_log("Fetch member details failed: " . $e->getMessage());
        throw $e;
    }
}

/**
 * Process member data - add URLs, format dates, calculate age, etc.
 */
function processMemberData($memberData) {
    // Generate full URLs for uploaded files
    $baseUrl = getBaseUrl();
    
    // Process file paths to full URLs
    $fileFields = ['passport_photo', 'id_document', 'kra_pin_document', 'signature'];
    foreach ($fileFields as $field) {
        if (!empty($memberData[$field])) {
            $memberData[$field . '_url'] = getFullImageUrl($memberData[$field], $baseUrl);
            $memberData[$field . '_path'] = $memberData[$field]; // Keep original path
        } else {
            $memberData[$field . '_url'] = null;
            $memberData[$field . '_path'] = null;
        }
    }
    
    // Format dates for better readability
    $dateFields = ['date_of_birth', 'registration_date', 'admission_date', 'created_at', 'updated_at', 'kyc_verified_at'];
    foreach ($dateFields as $field) {
        if (!empty($memberData[$field])) {
            $memberData[$field . '_formatted'] = date('F j, Y', strtotime($memberData[$field]));
            $memberData[$field . '_timestamp'] = strtotime($memberData[$field]);
        }
    }
    
    // Add age calculation
    if (!empty($memberData['date_of_birth'])) {
        $dob = new DateTime($memberData['date_of_birth']);
        $now = new DateTime();
        $memberData['age'] = $dob->diff($now)->y;
    }
    
    // Get membership duration
    if (!empty($memberData['registration_date'])) {
        $regDate = new DateTime($memberData['registration_date']);
        $now = new DateTime();
        $duration = $regDate->diff($now);
        $memberData['membership_duration'] = [
            'years' => $duration->y,
            'months' => $duration->m,
            'days' => $duration->d,
            'total_days' => $duration->days
        ];
    }
    
    // Add KYC status
    $memberData['kyc_status'] = $memberData['kyc_verified'] ? 'Verified' : 'Not Verified';
    if ($memberData['kyc_locked']) {
        $memberData['kyc_status'] = 'Locked';
    }
    
    // Add status badge/class for UI
    $statusClasses = [
        'active' => 'success',
        'inactive' => 'secondary',
        'suspended' => 'warning',
        'pending' => 'info'
    ];
    $memberData['status_class'] = $statusClasses[$memberData['status']] ?? 'secondary';
    
    return $memberData;
}

/**
 * Check if user has permission to view this member
 */
function hasPermissionToViewMember($userRole, $userBranchId, $memberData, $loggedInUserId) {
    // Admins can view all members
    if ($userRole === 'admin') {
        return true;
    }
    
    // Check if user is viewing their own member record
    // This requires session has member_id set when user logs in
    if (isset($_SESSION['member_id']) && $_SESSION['member_id'] == $memberData['id']) {
        return true;
    }
    
    // Branch managers can view members in their branch
    if ($userRole === 'branch_manager' && $userBranchId == $memberData['branch_id']) {
        return true;
    }
    
    // Agents can view members in their branch
    if ($userRole === 'agent' && $userBranchId == $memberData['branch_id']) {
        return true;
    }
    
    return false;
}

/**
 * Mask sensitive data based on user role
 */
function maskSensitiveMemberData($memberData, $userRole) {
    $maskedData = $memberData;
    
    switch ($userRole) {
        case 'admin':
            // Admins see everything
            break;
            
        case 'branch_manager':
            // Branch managers see most data but mask sensitive fields
            if (!empty($maskedData['id_number'])) {
                $maskedData['id_number'] = substr($maskedData['id_number'], 0, 3) . '****' . substr($maskedData['id_number'], -3);
            }
            if (!empty($maskedData['kra_pin'])) {
                $maskedData['kra_pin'] = '***-***-***';
            }
            break;
            
        case 'agent':
        default:
            // Agents and others see limited data
            if (!empty($maskedData['id_number'])) {
                $maskedData['id_number'] = '***-***-****';
            }
            $maskedData['kra_pin'] = null;
            $maskedData['kyc_attempts'] = null;
            $maskedData['kyc_locked'] = null;
            break;
    }
    
    return $maskedData;
}

try {
    // Get user info from session
    $loggedInUserId = $_SESSION['member_id'];
    $userRole = $_SESSION['role'] ?? null;
    $userBranchId = $_SESSION['branch_id'] ?? null;
    
    // Fetch raw member data
    $memberData = fetchMemberDetails($pdo, $memberId);
    
    // Process member data (add URLs, format dates, etc.)
    $memberData = processMemberData($memberData);
    
    // Mask sensitive data based on user role
    if ($userRole !== 'admin') {
        $memberData = maskSensitiveMemberData($memberData, $userRole);
    }
    
    // Prepare final response
    echo json_encode([
        'success' => true, 
        'data' => [
            'member' => $memberData,
            'permissions' => [
                'can_edit' => ($userRole === 'admin' || $userRole === 'branch_manager'),
                'can_delete' => ($userRole === 'admin'),
                'can_view_sensitive' => ($userRole === 'admin')
            ]
        ]
    ], JSON_NUMERIC_CHECK);
    
} catch (Exception $e) {
    error_log("Member API Error: " . $e->getMessage());
    
    // Determine appropriate status code
    $statusCode = 500;
    if (strpos($e->getMessage(), 'not found') !== false) {
        $statusCode = 404;
    } elseif (strpos($e->getMessage(), 'permission') !== false) {
        $statusCode = 403;
    }
    
    http_response_code($statusCode);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}