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

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    // Validate search input and corporate ID
    if (!isset($_POST['search'])) {
        throw new Exception('No search term provided');
    }

    $search = '%' . $_POST['search'] . '%';
    $corp_id = $_POST['corp_id'] ?? null;

    if (empty($corp_id)) {
        throw new Exception('Corporate ID is required');
    }

    // First get member details with corporate filter
    $sql = "SELECT 
        m.*,
        c.corporate as corporate_name,
        TIMESTAMPDIFF(YEAR, m.dob, CURDATE()) as age
    FROM member_info m
    LEFT JOIN corporate c ON m.corp_id = c.corp_id
    WHERE m.corp_id = ? 
    AND (m.member_no LIKE ?
       OR m.surname LIKE ?
       OR m.first_name LIKE ?
       OR CONCAT(m.first_name, ' ', m.surname) LIKE ?)
    AND m.status = 1
    LIMIT 10";

    $stmt = $conn->prepare($sql);
    if ($stmt === false) {
        throw new Exception("Prepare failed: " . $conn->error);
    }

    $stmt->bind_param("sssss", $corp_id, $search, $search, $search, $search);
    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }

    $result = $stmt->get_result();
    $members = [];

    while ($row = $result->fetch_assoc()) {
        // Format basic member data
        $member = [
            'member_no' => $row['member_no'],
            'family_no' => $row['family_no'],
            'surname' => $row['surname'],
            'first_name' => $row['first_name'],
            'relation_to_principal' => $row['relation_to_principal'],
            'name' => $row['first_name'] . ' ' . $row['surname'],
            'corporate_name' => $row['corporate_name'],
            'corp_id' => $row['corp_id'],
            'age' => $row['age'],
            'gender' => $row['gender'],
            'status' => $row['status']
        ];

        // Get benefit limits and utilization
        $sql_benefits = "SELECT 
            mb.benefit,
            mb.limit,
            mb.category,
            mb.sharing,
            b.benefit as benefit_name,
            COALESCE(SUM(bl.amount_payable), 0) as claims_total,
            COALESCE(COUNT(DISTINCT bl.claim_no), 0) as claim_count,
            COALESCE(SUM(pa.reserve), 0) as preauth_total,
            COALESCE(COUNT(DISTINCT pa.pre_auth_code), 0) as preauth_count
        FROM member_benefits mb
        LEFT JOIN benefit b ON mb.benefit = b.code
        LEFT JOIN bills bl ON mb.member_no = bl.member_no 
            AND mb.benefit = bl.service
            AND bl.vet_status = 1  -- Only count approved claims
            AND YEAR(bl.invoice_date) = YEAR(CURDATE())  -- Current year claims
        LEFT JOIN pre_authorization pa ON mb.member_no = pa.member_no 
            AND mb.benefit = pa.authority_type
            AND pa.status = 'ACTIVE'  -- Only count active pre-auths
            AND YEAR(pa.date_reported) = YEAR(CURDATE())  -- Current year pre-auths
        WHERE mb.member_no = ?
        GROUP BY mb.benefit, mb.limit, mb.category, mb.sharing, b.benefit";

        $stmt_benefits = $conn->prepare($sql_benefits);
        if ($stmt_benefits === false) {
            throw new Exception("Prepare benefits query failed: " . $conn->error);
        }

        $stmt_benefits->bind_param('s', $row['member_no']);
        if (!$stmt_benefits->execute()) {
            throw new Exception("Execute benefits query failed: " . $stmt_benefits->error);
        }

        $result_benefits = $stmt_benefits->get_result();
        $benefits = [];

        while ($benefit = $result_benefits->fetch_assoc()) {
            $used_claims = floatval($benefit['claims_total']);
            $used_preauths = floatval($benefit['preauth_total']);
            $total_used = $used_claims + $used_preauths;
            $limit = floatval($benefit['limit']);
            $available = $limit - $total_used;
            $percent_used = $limit > 0 ? ($total_used / $limit * 100) : 0;
        
            $benefits[] = [
                'benefit_code' => $benefit['benefit'],
                'benefit_name' => $benefit['benefit_name'],
                'category' => $benefit['category'],
                'sharing' => $benefit['sharing'],
                'limit' => $limit,
                'used_claims' => $used_claims,
                'used_preauths' => $used_preauths,
                'total_used' => $total_used,
                'available' => $available,
                'percent_used' => $percent_used,
                'claim_count' => $benefit['claim_count'],
                'preauth_count' => $benefit['preauth_count'],
                'status' => $percent_used >= 100 ? 'Exhausted' : 
                           ($percent_used >= 80 ? 'Critical' : 
                           ($percent_used >= 50 ? 'Warning' : 'Good'))
            ];
        }

        // Get active pre-authorizations
        $sql_preauths = "SELECT 
            p.*,
            s.service as service_name,
            pv.provider_name
        FROM pre_authorization p
        LEFT JOIN services s ON p.pre_diagnosis = s.code
        LEFT JOIN providers pv ON p.provider = pv.provider_id
        WHERE p.member_no = ?
        AND p.status = 'ACTIVE'
        ORDER BY p.date_reported DESC";

        $stmt_preauths = $conn->prepare($sql_preauths);
        $stmt_preauths->bind_param('s', $row['member_no']);
        $stmt_preauths->execute();
        $result_preauths = $stmt_preauths->get_result();
        
        $active_preauths = [];
        while ($preauth = $result_preauths->fetch_assoc()) {
            $active_preauths[] = [
                'pre_auth_code' => $preauth['pre_auth_code'],
                'date_reported' => $preauth['date_reported'],
                'provider_name' => $preauth['provider_name'],
                'service_name' => $preauth['service_name'],
                'authority_type' => $preauth['authority_type'],
                'reserve' => $preauth['reserve'],
                'notes' => $preauth['notes']
            ];
        }

        // Get recent claims
        $sql_claims = "SELECT 
            b.claim_no,
            b.invoice_no,
            b.invoice_date,
            b.invoiced_amount,
            b.amount_payable,
            b.vet_status,
            s.service as service_name,
            p.provider_name,
            b.pre_auth_no
        FROM bills b
        LEFT JOIN services s ON b.service = s.code
        LEFT JOIN providers p ON b.provider = p.provider_id
        WHERE b.member_no = ?
        ORDER BY b.invoice_date DESC
        LIMIT 5";

        $stmt_claims = $conn->prepare($sql_claims);
        $stmt_claims->bind_param('s', $row['member_no']);
        $stmt_claims->execute();
        $result_claims = $stmt_claims->get_result();
        
        $recent_claims = [];
        while ($claim = $result_claims->fetch_assoc()) {
            $recent_claims[] = [
                'claim_no' => $claim['claim_no'],
                'invoice_no' => $claim['invoice_no'],
                'invoice_date' => $claim['invoice_date'],
                'invoiced_amount' => $claim['invoiced_amount'],
                'amount_payable' => $claim['amount_payable'],
                'service_name' => $claim['service_name'],
                'provider_name' => $claim['provider_name'],
                'pre_auth_no' => $claim['pre_auth_no'],
                'status' => $claim['vet_status'] == 1 ? 'Approved' : 
                           ($claim['vet_status'] == 2 ? 'Rejected' : 
                           ($claim['vet_status'] == 3 ? 'Deferred' : 'Pending'))
            ];
        }

        // Add all data to member array
        $member['benefits'] = $benefits;
        $member['active_preauths'] = $active_preauths;
        $member['recent_claims'] = $recent_claims;
        $members[] = $member;
    }

    // Return success response with member data
    echo json_encode([
        'success' => true, 
        'members' => $members,
        'timestamp' => date('Y-m-d H:i:s')
    ]);

} catch (Exception $e) {
    // Log error and return error response
    error_log("Member search error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'error' => $e->getMessage(),
        'timestamp' => date('Y-m-d H:i:s')
    ]);
}

// Close database connection
$conn->close();
?>