<?php
/**
 * Members API Endpoints
 * v1/members
 */

global $method, $input, $queryParams, $apiResponse, $user, $conn, $segments;

require_once __DIR__ . '/../../classes/MemberService.php';

$memberService = new MemberService($conn);

switch ($method) {
    case 'GET':
        // Get member(s)
        if (empty($segments[2])) {
            // List members with pagination
            $page = $queryParams['page'] ?? 1;
            $per_page = min($queryParams['per_page'] ?? 20, 100);
            $offset = ($page - 1) * $per_page;
            
            // Get member_id if user is a member
            $member_id = null;
            if ($user['role_name'] === 'MEMBER') {
                $memberSql = "SELECT member_id FROM members WHERE user_id = ?";
                $memberStmt = $conn->prepare($memberSql);
                $memberStmt->bind_param("i", $user['user_id']);
                $memberStmt->execute();
                $memberResult = $memberStmt->get_result();
                $member = $memberResult->fetch_assoc();
                $member_id = $member['member_id'] ?? null;
                
                if (!$member_id) {
                    $apiResponse->error('Member not found', 404);
                }
            }
            
            // Build query
            $where = ["m.is_active = 1"];
            $params = [];
            $types = '';
            
            if ($member_id) {
                $where[] = "m.member_id = ?";
                $params[] = $member_id;
                $types .= 'i';
            }
            
            if (isset($queryParams['scheme_id'])) {
                $where[] = "m.scheme_id = ?";
                $params[] = $queryParams['scheme_id'];
                $types .= 'i';
            }
            
            if (isset($queryParams['search'])) {
                $where[] = "(m.member_number LIKE ? OR m.first_name LIKE ? OR m.last_name LIKE ?)";
                $search = "%{$queryParams['search']}%";
                $params[] = $search;
                $params[] = $search;
                $params[] = $search;
                $types .= 'sss';
            }
            
            $whereClause = implode(' AND ', $where);
            
            // Get total count
            $countSql = "SELECT COUNT(*) as total FROM members m WHERE $whereClause";
            $countStmt = $conn->prepare($countSql);
            if (!empty($params)) {
                $countStmt->bind_param($types, ...$params);
            }
            $countStmt->execute();
            $total = $countStmt->get_result()->fetch_assoc()['total'];
            
            // Get members
            $sql = "SELECT m.member_id, m.member_number, m.first_name, m.middle_name, m.last_name,
                           m.date_of_birth, m.gender, m.email, m.phone_number, m.employment_status,
                           m.scheme_id, ps.scheme_name, ma.accrued_benefits, ma.available_balance
                    FROM members m
                    LEFT JOIN pension_schemes ps ON m.scheme_id = ps.scheme_id
                    LEFT JOIN member_accounts ma ON m.member_id = ma.member_id
                    WHERE $whereClause
                    ORDER BY m.member_number
                    LIMIT ? OFFSET ?";
            
            $params[] = $per_page;
            $params[] = $offset;
            $types .= 'ii';
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $members = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            
            $apiResponse->paginated($members, $page, $per_page, $total, 'Members retrieved successfully');
            
        } else {
            // Get single member
            $member_id = $segments[2];
            
            // Check access
            if ($user['role_name'] === 'MEMBER') {
                $memberSql = "SELECT member_id FROM members WHERE user_id = ? AND member_id = ?";
                $memberStmt = $conn->prepare($memberSql);
                $memberStmt->bind_param("ii", $user['user_id'], $member_id);
                $memberStmt->execute();
                if ($memberStmt->get_result()->num_rows === 0) {
                    $apiResponse->error('Access denied', 403);
                }
            }
            
            $member = $memberService->getMember($member_id);
            
            if ($member) {
                $apiResponse->success($member, 'Member retrieved successfully');
            } else {
                $apiResponse->error('Member not found', 404);
            }
        }
        break;
        
    case 'GET':
        // Get member account balance
        if (isset($segments[2]) && $segments[2] === 'balance') {
            $member_id = $segments[3] ?? null;
            
            if (!$member_id && $user['role_name'] === 'MEMBER') {
                $memberSql = "SELECT member_id FROM members WHERE user_id = ?";
                $memberStmt = $conn->prepare($memberSql);
                $memberStmt->bind_param("i", $user['user_id']);
                $memberStmt->execute();
                $memberResult = $memberStmt->get_result();
                $member = $memberResult->fetch_assoc();
                $member_id = $member['member_id'] ?? null;
            }
            
            if (!$member_id) {
                $apiResponse->error('Member ID required', 400);
            }
            
            $sql = "SELECT ma.*, ps.scheme_name 
                    FROM member_accounts ma
                    LEFT JOIN members m ON ma.member_id = m.member_id
                    LEFT JOIN pension_schemes ps ON m.scheme_id = ps.scheme_id
                    WHERE ma.member_id = ?";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $member_id);
            $stmt->execute();
            $account = $stmt->get_result()->fetch_assoc();
            
            if ($account) {
                $apiResponse->success($account, 'Account balance retrieved');
            } else {
                $apiResponse->error('Account not found', 404);
            }
        }
        break;
        
    default:
        $apiResponse->error('Method not allowed', 405);
}
