<?php
/**
 * Statements API Endpoints
 * v1/statements
 */

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

switch ($method) {
    case 'GET':
        // Get member statement
        $member_id = $queryParams['member_id'] ?? null;
        
        // If member, get their member_id
        if ($user['role_name'] === 'MEMBER' && !$member_id) {
            $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);
        }
        
        // Get account summary
        $accountSql = "SELECT ma.*, ps.scheme_name, m.member_number, m.first_name, m.last_name
                      FROM member_accounts ma
                      INNER 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 = ?";
        $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 12";
        $contributionsStmt = $conn->prepare($contributionsSql);
        $contributionsStmt->bind_param("i", $member_id);
        $contributionsStmt->execute();
        $contributions = $contributionsStmt->get_result()->fetch_all(MYSQLI_ASSOC);
        
        // Get recent withdrawals
        $withdrawalsSql = "SELECT * FROM withdrawal_requests 
                          WHERE member_id = ? 
                          ORDER BY requested_date DESC 
                          LIMIT 10";
        $withdrawalsStmt = $conn->prepare($withdrawalsSql);
        $withdrawalsStmt->bind_param("i", $member_id);
        $withdrawalsStmt->execute();
        $withdrawals = $withdrawalsStmt->get_result()->fetch_all(MYSQLI_ASSOC);
        
        $apiResponse->success([
            'account' => $account,
            'contributions' => $contributions,
            'withdrawals' => $withdrawals,
            'generated_at' => date('Y-m-d H:i:s')
        ], 'Statement retrieved');
        break;
        
    default:
        $apiResponse->error('Method not allowed', 405);
}
