<?php
session_start();
include 'layouts/dbconn.php';
require_once 'bills_processor.php';

/**
 * Saves a group of bills under a single claim
 */
function saveBillGroup($claim_group, $claim_no, $conn) {
    try {
        foreach ($claim_group['bills'] as $bill) {
            $sql = "INSERT INTO bills (
                claim_no,
                claim_form_no,
                invoice_no,
                service,
                provider,
                member_no,
                claim_nature,
                batch_no,
                invoice_date,
                invoiced_amount,
                date_received,
                vet_status,
                deduction_amount,
                deduction_reason,
                amount_payable,
                paid,
                user_id,
                date_entered,
                pre_auth_no,
                corp_id,
                family_no,
                pri_dep
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, CURDATE(), ?, ?, ?, ?)";

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Failed to prepare statement: " . $conn->error);
            }

            // Check for pre-authorization
            $pre_auth = findPreAuthorization(
                $bill['member_no'], 
                $bill['service'], 
                $bill['provider'], 
                $conn
            );

            $pre_auth_no = $pre_auth ? $pre_auth['pre_auth_no'] : null;
            $user_id = $_SESSION['user_id'];

            $stmt->bind_param(
                'sssiissssdsdidsisiss',
                $claim_no,
                $claim_no,  // Using claim_no as claim_form_no
                $bill['invoice_no'],
                $bill['service'],
                $bill['provider'],
                $bill['member_no'],
                $bill['claim_nature'],
                $bill['batch_no'],
                $bill['invoice_date'],
                $bill['invoiced_amount'],
                $bill['date_received'],
                $bill['vet_status'],
                $bill['deduction_amount'],
                $bill['deduction_reason'],
                $bill['amount_payable'],
                $user_id,
                $pre_auth_no,
                $bill['corp_id'],
                $bill['family_no'],
                $bill['pri_dep']
            );

            if (!$stmt->execute()) {
                throw new Exception("Failed to save bill: " . $stmt->error);
            }

            // Update pre-authorization if used
            if ($pre_auth) {
                updatePreAuth($pre_auth['pre_auth_no'], $claim_no, $conn);
            }
        }

        return true;
    } catch (Exception $e) {
        error_log("Error saving bill group: " . $e->getMessage());
        throw new Exception("Failed to save bill group");
    }
}

/**
 * Updates pre-authorization with claim number
 */
function updatePreAuth($pre_auth_no, $claim_no, $conn) {
    try {
        $sql = "UPDATE pre_authorization 
                SET claim_no = ?,
                    claim_date = CURDATE(),
                    status = 'USED'
                WHERE pre_auth_no = ?";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param('si', $claim_no, $pre_auth_no);
        
        if (!$stmt->execute()) {
            throw new Exception("Failed to update pre-authorization");
        }

        return true;
    } catch (Exception $e) {
        error_log("Error updating pre-authorization: " . $e->getMessage());
        throw new Exception("Failed to update pre-authorization");
    }
}

/**
 * Saves claim diagnosis if provided
 */
function saveClaimDiagnosis($claim_no, $diagnosis, $conn) {
    try {
        $sql = "INSERT INTO claim_diagnosis (
            claim_no,
            diagnosis_code,
            primary_diagnosis,
            user_id,
            date_entered
        ) VALUES (?, ?, ?, ?, CURDATE())";

        $stmt = $conn->prepare($sql);
        $user_id = $_SESSION['user_id'];
        $is_primary = 1;

        $stmt->bind_param('ssis', $claim_no, $diagnosis, $is_primary, $user_id);
        
        if (!$stmt->execute()) {
            throw new Exception("Failed to save diagnosis");
        }

        return true;
    } catch (Exception $e) {
        error_log("Error saving claim diagnosis: " . $e->getMessage());
        throw new Exception("Failed to save claim diagnosis");
    }
}

/**
 * Logs claim activity
 */
function logClaimActivity($claim_no, $action, $details, $conn) {
    try {
        $sql = "INSERT INTO activity_log (
            user_id,
            action,
            table_name,
            record_id,
            new_values,
            ip_address,
            user_agent,
            action_date
        ) VALUES (?, ?, 'bills', ?, ?, ?, ?, NOW())";

        $stmt = $conn->prepare($sql);
        
        $user_id = $_SESSION['user_id'];
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $new_values = json_encode($details);

        $stmt->bind_param(
            'ssssss',
            $user_id,
            $action,
            $claim_no,
            $new_values,
            $ip_address,
            $user_agent
        );
        
        if (!$stmt->execute()) {
            throw new Exception("Failed to log activity");
        }

        return true;
    } catch (Exception $e) {
        error_log("Error logging claim activity: " . $e->getMessage());
        // Don't throw - logging failure shouldn't stop the process
        return false;
    }
}

/**
 * Checks for duplicate invoices
 */
function checkDuplicateInvoice($invoice_no, $provider, $conn) {
    try {
        $sql = "SELECT COUNT(*) as count FROM bills 
                WHERE invoice_no = ? AND provider = ?";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('si', $invoice_no, $provider);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        
        return $result['count'] > 0;
    } catch (Exception $e) {
        error_log("Error checking duplicate invoice: " . $e->getMessage());
        throw new Exception("Failed to check duplicate invoice");
    }
}
$conn->close();
?>