<?php
header('Content-Type: application/json');
include 'layouts/dbconn.php';

try {
    $member_no = $_POST['member_no'] ?? '';
    $corp_id = $_POST['corp_id'] ?? '';

    if (!$member_no || !$corp_id) {
        throw new Exception('Missing required parameters');
    }

    $sql = "SELECT m.*, 
            c.corporate as corporate_name,
            c.corp_id
            FROM member_info m 
            LEFT JOIN corporate c ON m.corp_id = c.corp_id
            WHERE m.member_no = ? 
            AND m.corp_id = ?
            AND m.status = 1";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ss', $member_no, $corp_id);
    $stmt->execute();
    $member = $stmt->get_result()->fetch_assoc();

    if (!$member) {
        throw new Exception('Member not found');
    }

    // Get member benefits
    $sql = "SELECT b.code as benefit_code, 
            b.benefit as benefit_name,
            mb.limit,
            mb.category,
            COALESCE(SUM(cl.invoiced_amount), 0) as used_amount,
            COUNT(DISTINCT cl.claim_no) as claim_count
            FROM member_benefits mb
            LEFT JOIN benefit b ON mb.benefit = b.code
            LEFT JOIN bills cl ON mb.member_no = cl.member_no 
                AND mb.benefit = cl.claim_nature
                AND cl.vet_status = 1
            WHERE mb.member_no = ?
            GROUP BY b.code";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $member_no);
    $stmt->execute();
    $benefits = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

    foreach ($benefits as &$benefit) {
        $benefit['used_amount'] = floatval($benefit['used_amount']);
        $benefit['limit'] = floatval($benefit['limit']);
        $benefit['available'] = $benefit['limit'] - $benefit['used_amount'];
        $benefit['utilization'] = ($benefit['used_amount'] / $benefit['limit']) * 100;
    }

    $member['benefits'] = $benefits;

    echo json_encode([
        'success' => true,
        'member' => $member
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>