<?php
/**
 * Payments API Endpoints
 * v1/payments
 */

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

switch ($method) {
    case 'GET':
        // Get payment history
        $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[] = "p.member_id = ?";
            $params[] = $member_id;
            $types .= 'i';
        }
        
        if (isset($queryParams['status'])) {
            $where[] = "p.payout_status = ?";
            $params[] = $queryParams['status'];
            $types .= 's';
        }
        
        $whereClause = implode(' AND ', $where);
        
        // Get total
        $countSql = "SELECT COUNT(*) as total FROM payouts p WHERE $whereClause";
        $countStmt = $conn->prepare($countSql);
        if (!empty($params)) {
            $countStmt->bind_param($types, ...$params);
        }
        $countStmt->execute();
        $total = $countStmt->get_result()->fetch_assoc()['total'];
        
        // Get payouts
        $sql = "SELECT p.*, m.member_number, m.first_name, m.last_name
                FROM payouts p
                LEFT JOIN members m ON p.member_id = m.member_id
                WHERE $whereClause
                ORDER BY p.created_at DESC
                LIMIT ? OFFSET ?";
        
        $params[] = $per_page;
        $params[] = $offset;
        $types .= 'ii';
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $payments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        
        $apiResponse->paginated($payments, $page, $per_page, $total, 'Payments retrieved');
        break;
        
    default:
        $apiResponse->error('Method not allowed', 405);
}
