<?php
/**
 * Withdrawals API Endpoints
 * v1/withdrawals
 */

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

switch ($method) {
    case 'GET':
        // Get withdrawals
        $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;
        }
        
        $page = $queryParams['page'] ?? 1;
        $per_page = min($queryParams['per_page'] ?? 20, 100);
        $offset = ($page - 1) * $per_page;
        
        $where = ["1=1"];
        $params = [];
        $types = '';
        
        if ($member_id) {
            $where[] = "wr.member_id = ?";
            $params[] = $member_id;
            $types .= 'i';
        }
        
        if (isset($queryParams['status'])) {
            $where[] = "wr.status = ?";
            $params[] = $queryParams['status'];
            $types .= 's';
        }
        
        $whereClause = implode(' AND ', $where);
        
        // Get total
        $countSql = "SELECT COUNT(*) as total FROM withdrawal_requests wr WHERE $whereClause";
        $countStmt = $conn->prepare($countSql);
        if (!empty($params)) {
            $countStmt->bind_param($types, ...$params);
        }
        $countStmt->execute();
        $total = $countStmt->get_result()->fetch_assoc()['total'];
        
        // Get withdrawals
        $sql = "SELECT wr.*, m.member_number, m.first_name, m.last_name, ps.scheme_name
                FROM withdrawal_requests wr
                INNER JOIN members m ON wr.member_id = m.member_id
                LEFT JOIN pension_schemes ps ON wr.scheme_id = ps.scheme_id
                WHERE $whereClause
                ORDER BY wr.requested_date DESC
                LIMIT ? OFFSET ?";
        
        $params[] = $per_page;
        $params[] = $offset;
        $types .= 'ii';
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $withdrawals = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        
        $apiResponse->paginated($withdrawals, $page, $per_page, $total, 'Withdrawals retrieved');
        break;
        
    case 'POST':
        // Create withdrawal request
        if ($user['role_name'] !== 'MEMBER') {
            $apiResponse->error('Only members can request withdrawals', 403);
        }
        
        // Get 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 not found', 404);
        }
        
        $required = ['withdrawal_type', 'requested_amount'];
        foreach ($required as $field) {
            if (!isset($input[$field])) {
                $apiResponse->error("Field required: $field", 400);
            }
        }
        
        // Get account_id
        $accountSql = "SELECT account_id, scheme_id FROM member_accounts WHERE member_id = ?";
        $accountStmt = $conn->prepare($accountSql);
        $accountStmt->bind_param("i", $member_id);
        $accountStmt->execute();
        $account = $accountStmt->get_result()->fetch_assoc();
        
        if (!$account) {
            $apiResponse->error('Account not found', 404);
        }
        
        // Validate eligibility
        $eligibilitySql = "CALL sp_validate_withdrawal_eligibility(?, ?, CURDATE(), @is_eligible, @eligible_amount, @rejection_reason)";
        $eligibilityStmt = $conn->prepare($eligibilitySql);
        $eligibilityStmt->bind_param("is", $member_id, $input['withdrawal_type']);
        $eligibilityStmt->execute();
        $eligibilityStmt->close();
        
        $result = $conn->query("SELECT @is_eligible as is_eligible, @eligible_amount as eligible_amount, @rejection_reason as rejection_reason");
        $eligibility = $result->fetch_assoc();
        
        if (!$eligibility['is_eligible']) {
            $apiResponse->error($eligibility['rejection_reason'] ?? 'Not eligible for withdrawal', 400);
        }
        
        // Create withdrawal request
        $sql = "INSERT INTO withdrawal_requests (
                   member_id, account_id, scheme_id, withdrawal_type,
                   requested_amount, eligible_amount, status, requested_by
               ) VALUES (?, ?, ?, ?, ?, ?, 'PENDING', ?)";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iiisddi",
            $member_id,
            $account['account_id'],
            $account['scheme_id'],
            $input['withdrawal_type'],
            $input['requested_amount'],
            $eligibility['eligible_amount'],
            $user['user_id']
        );
        
        if ($stmt->execute()) {
            $request_id = $conn->insert_id;
            $apiResponse->success(['request_id' => $request_id], 'Withdrawal request created', 201);
        } else {
            $apiResponse->error('Failed to create withdrawal request', 500);
        }
        break;
        
    default:
        $apiResponse->error('Method not allowed', 405);
}
