<?php
/**
 * Claims API Endpoints
 * v1/claims
 */

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

switch ($method) {
    case 'GET':
        // Get claims
        $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[] = "lc.member_id = ?";
            $params[] = $member_id;
            $types .= 'i';
        }
        
        if (isset($queryParams['status'])) {
            $where[] = "lc.claim_status = ?";
            $params[] = $queryParams['status'];
            $types .= 's';
        }
        
        $whereClause = implode(' AND ', $where);
        
        // Get total
        $countSql = "SELECT COUNT(*) as total FROM life_claims lc WHERE $whereClause";
        $countStmt = $conn->prepare($countSql);
        if (!empty($params)) {
            $countStmt->bind_param($types, ...$params);
        }
        $countStmt->execute();
        $total = $countStmt->get_result()->fetch_assoc()['total'];
        
        // Get claims
        $sql = "SELECT lc.*, lp.policy_number, m.member_number, m.first_name, m.last_name
                FROM life_claims lc
                INNER JOIN life_policies lp ON lc.policy_id = lp.policy_id
                INNER JOIN members m ON lc.member_id = m.member_id
                WHERE $whereClause
                ORDER BY lc.submitted_date DESC
                LIMIT ? OFFSET ?";
        
        $params[] = $per_page;
        $params[] = $offset;
        $types .= 'ii';
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $claims = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        
        $apiResponse->paginated($claims, $page, $per_page, $total, 'Claims retrieved');
        break;
        
    case 'POST':
        // File a claim (Members only)
        if ($user['role_name'] !== 'MEMBER') {
            $apiResponse->error('Only members can file claims', 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 = ['policy_id', 'claim_type', 'claim_amount'];
        foreach ($required as $field) {
            if (!isset($input[$field])) {
                $apiResponse->error("Field required: $field", 400);
            }
        }
        
        // Create claim
        $sql = "INSERT INTO life_claims (
                   policy_id, member_id, claim_type, claim_amount,
                   claim_status, submitted_date, submitted_by
               ) VALUES (?, ?, ?, ?, 'PENDING', CURDATE(), ?)";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iisdi",
            $input['policy_id'],
            $member_id,
            $input['claim_type'],
            $input['claim_amount'],
            $user['user_id']
        );
        
        if ($stmt->execute()) {
            $claim_id = $conn->insert_id;
            $apiResponse->success(['claim_id' => $claim_id], 'Claim filed successfully', 201);
        } else {
            $apiResponse->error('Failed to file claim', 500);
        }
        break;
        
    default:
        $apiResponse->error('Method not allowed', 405);
}
