<?php
/**
 * Contributions API Endpoints
 * v1/contributions
 */

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

switch ($method) {
    case 'GET':
        // Get contributions
        $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[] = "c.member_id = ?";
            $params[] = $member_id;
            $types .= 'i';
        }
        
        if (isset($queryParams['status'])) {
            $where[] = "c.status = ?";
            $params[] = $queryParams['status'];
            $types .= 's';
        }
        
        if (isset($queryParams['date_from'])) {
            $where[] = "DATE(c.contribution_period) >= ?";
            $params[] = $queryParams['date_from'];
            $types .= 's';
        }
        
        if (isset($queryParams['date_to'])) {
            $where[] = "DATE(c.contribution_period) <= ?";
            $params[] = $queryParams['date_to'];
            $types .= 's';
        }
        
        $whereClause = implode(' AND ', $where);
        
        // Get total
        $countSql = "SELECT COUNT(*) as total FROM contributions c WHERE $whereClause";
        $countStmt = $conn->prepare($countSql);
        if (!empty($params)) {
            $countStmt->bind_param($types, ...$params);
        }
        $countStmt->execute();
        $total = $countStmt->get_result()->fetch_assoc()['total'];
        
        // Get contributions
        $sql = "SELECT c.*, m.member_number, m.first_name, m.last_name, ps.scheme_name
                FROM contributions c
                INNER JOIN members m ON c.member_id = m.member_id
                LEFT JOIN pension_schemes ps ON m.scheme_id = ps.scheme_id
                WHERE $whereClause
                ORDER BY c.contribution_period DESC
                LIMIT ? OFFSET ?";
        
        $params[] = $per_page;
        $params[] = $offset;
        $types .= 'ii';
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $contributions = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        
        $apiResponse->paginated($contributions, $page, $per_page, $total, 'Contributions retrieved');
        break;
        
    case 'POST':
        // Create contribution (for employers/admins)
        if (!in_array($user['role_name'], ['ADMIN', 'EMPLOYER'])) {
            $apiResponse->error('Permission denied', 403);
        }
        
        $required = ['member_id', 'contribution_period', 'contribution_type', 'contribution_amount'];
        foreach ($required as $field) {
            if (!isset($input[$field])) {
                $apiResponse->error("Field required: $field", 400);
            }
        }
        
        $sql = "INSERT INTO contributions (
                   member_id, contribution_period, contribution_type,
                   contribution_amount, status, created_by
               ) VALUES (?, ?, ?, ?, 'PENDING', ?)";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("issdi",
            $input['member_id'],
            $input['contribution_period'],
            $input['contribution_type'],
            $input['contribution_amount'],
            $user['user_id']
        );
        
        if ($stmt->execute()) {
            $contribution_id = $conn->insert_id;
            $apiResponse->success(['contribution_id' => $contribution_id], 'Contribution created', 201);
        } else {
            $apiResponse->error('Failed to create contribution', 500);
        }
        break;
        
    default:
        $apiResponse->error('Method not allowed', 405);
}
