<?php
/**
 * Premiums API Endpoints
 * v1/premiums
 */

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

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