<?php
/**
 * Beneficiaries API Endpoints
 * v1/beneficiaries
 */

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

switch ($method) {
    case 'GET':
        // Get beneficiaries
        $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);
        }
        
        $sql = "SELECT * FROM beneficiaries WHERE member_id = ? ORDER BY created_at DESC";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $member_id);
        $stmt->execute();
        $beneficiaries = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        
        $apiResponse->success($beneficiaries, 'Beneficiaries retrieved');
        break;
        
    case 'POST':
        // Add beneficiary (Members only)
        if ($user['role_name'] !== 'MEMBER') {
            $apiResponse->error('Only members can add beneficiaries', 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 = ['first_name', 'last_name', 'relationship', 'allocation_percentage'];
        foreach ($required as $field) {
            if (!isset($input[$field])) {
                $apiResponse->error("Field required: $field", 400);
            }
        }
        
        // Validate allocation percentage
        $totalAllocation = $input['allocation_percentage'];
        $checkSql = "SELECT SUM(allocation_percentage) as total FROM beneficiaries WHERE member_id = ?";
        $checkStmt = $conn->prepare($checkSql);
        $checkStmt->bind_param("i", $member_id);
        $checkStmt->execute();
        $existing = $checkStmt->get_result()->fetch_assoc();
        $totalAllocation += $existing['total'] ?? 0;
        
        if ($totalAllocation > 100) {
            $apiResponse->error('Total allocation cannot exceed 100%', 400);
        }
        
        // Create beneficiary
        $sql = "INSERT INTO beneficiaries (
                   member_id, first_name, last_name, middle_name,
                   relationship, allocation_percentage, date_of_birth,
                   phone_number, email, national_id
               ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("issssdssss",
            $member_id,
            $input['first_name'],
            $input['last_name'],
            $input['middle_name'] ?? null,
            $input['relationship'],
            $input['allocation_percentage'],
            $input['date_of_birth'] ?? null,
            $input['phone_number'] ?? null,
            $input['email'] ?? null,
            $input['national_id'] ?? null
        );
        
        if ($stmt->execute()) {
            $beneficiary_id = $conn->insert_id;
            $apiResponse->success(['beneficiary_id' => $beneficiary_id], 'Beneficiary added successfully', 201);
        } else {
            $apiResponse->error('Failed to add beneficiary', 500);
        }
        break;
        
    default:
        $apiResponse->error('Method not allowed', 405);
}
