<?php
require 'db/config.php';
require 'helpers.php';

require_once __DIR__ . '/includes/auth.php';
check_auth();

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

try {
    $db = db();
    $insurance_id = $_GET['id'] ?? 0;
    $start_date = $_GET['start_date'] ?? date('Y-m-01');
    $end_date = $_GET['end_date'] ?? date('Y-m-d');

    if (!$insurance_id) {
        throw new Exception("Invalid Insurance Company ID");
    }

    // Fetch Insurance Company Details
    $stmt = $db->prepare("SELECT * FROM insurance_companies WHERE id = ?");
    $stmt->execute([$insurance_id]);
    $insurance = $stmt->fetch();

    if (!$insurance) {
        throw new Exception("Insurance Company not found");
    }

    // Fetch Linked Bills
    // Linking via patients table: bills -> patients -> insurance_company_id
    $query = "
        SELECT 
            b.*, 
            p.name as patient_name, 
            p.policy_number,
            p.civil_id,
            d.name_en as doctor_name_en
        FROM bills b
        JOIN patients p ON b.patient_id = p.id
        LEFT JOIN visits v ON b.visit_id = v.id
        LEFT JOIN employees d ON v.doctor_id = d.id
        WHERE p.insurance_company_id = ?
        AND b.insurance_covered > 0
        AND DATE(b.created_at) BETWEEN ? AND ?
        ORDER BY b.created_at DESC
    ";
    
    $stmt = $db->prepare($query);
    $stmt->execute([$insurance_id, $start_date, $end_date]);
    $bills = $stmt->fetchAll();

    // Calculate Totals
    $total_claim = 0;
    foreach ($bills as $bill) {
        $total_claim += $bill['insurance_covered'];
    }

    // Fetch Company Settings (Logo, Address, etc.)
    $stmt = $db->query("SELECT setting_key, setting_value FROM settings");
    $settings = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $settings[$row[setting_key]] = $row[setting_value];
    }

    $lang = $_SESSION['lang'] ?? 'en';
} catch (Exception $e) {
    die("Error: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="<?php echo $lang; ?>" dir="<?php echo $lang == 'ar' ? 'rtl' : 'ltr'; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Statement - <?php echo htmlspecialchars($insurance['name_en']); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { font-family: 'Times New Roman', Times, serif; color: #333; }
        .invoice-header { border-bottom: 2px solid #ddd; padding-bottom: 20px; margin-bottom: 30px; }
        .invoice-footer { border-top: 2px solid #ddd; padding-top: 20px; margin-top: 50px; }
        .company-logo { max-height: 80px; }
        .invoice-title { font-size: 2rem; color: #555; text-transform: uppercase; letter-spacing: 2px; }
        
        .table thead th { border-bottom: 2px solid #333; background-color: #f8f9fa; }
        .table-bordered td, .table-bordered th { border-color: #dee2e6; }
        
        @media print {
            .no-print { display: none !important; }
            body { padding: 20px; background: white; }
            .card { border: none !important; box-shadow: none !important; }
        }
    </style>
</head>
<body onload="window.print()">

<div class="container my-5">
    <div class="no-print mb-4 text-end">
        <button onclick="window.print()" class="btn btn-primary"><i class="bi bi-printer"></i> <?php echo __('print'); ?></button>
        <button onclick="window.close()" class="btn btn-secondary"><?php echo __('close'); ?></button>
    </div>

    <div class="card p-4">
        <!-- Header -->
        <div class="invoice-header">
            <div class="row align-items-center">
                <div class="col-6">
                    <?php if (!empty($settings['company_logo'])): ?>
                        <img src="<?php echo htmlspecialchars($settings['company_logo']); ?>" alt="Logo" class="company-logo mb-2">
                    <?php else: ?>
                        <h2 class="fw-bold m-0"><?php echo htmlspecialchars($settings['company_name'] ?? 'Hospital Name'); ?></h2>
                    <?php endif; ?>
                    <div class="small text-muted">
                        <?php echo htmlspecialchars($settings['company_address'] ?? '123 Medical Center St.'); ?><br>
                        <?php echo __('phone'); ?>: <?php echo htmlspecialchars($settings['company_phone'] ?? '+123 456 7890'); ?><br>
                        <?php echo __('email'); ?>: <?php echo htmlspecialchars($settings['company_email'] ?? 'info@hospital.com'); ?>
                    </div>
                </div>
                <div class="col-6 text-end">
                    <h1 class="invoice-title"><?php echo __('statement'); ?></h1>
                    <p class="lead mb-0"><?php echo htmlspecialchars($insurance['name_en']); ?></p>
                    <p class="text-muted small">
                        <?php echo __('date'); ?>: <?php echo date('d M Y', strtotime($start_date)); ?> - <?php echo date('d M Y', strtotime($end_date)); ?>
                    </p>
                </div>
            </div>
        </div>

        <!-- Insurance Details -->
        <div class="row mb-4">
            <div class="col-12">
                <h6 class="text-uppercase text-muted small fw-bold mb-2"><?php echo __('insurance_company'); ?>:</h6>
                <h5 class="fw-bold mb-1"><?php echo htmlspecialchars($insurance['name_en']); ?></h5>
                <p class="mb-0 text-muted">
                    <?php if ($insurance['phone']) echo __('phone') . ': ' . htmlspecialchars($insurance['phone']) . '<br>'; ?>
                    <?php if ($insurance['email']) echo __('email') . ': ' . htmlspecialchars($insurance['email']); ?>
                </p>
            </div>
        </div>

        <!-- Bills Table -->
        <table class="table table-bordered mb-4">
            <thead>
                <tr>
                    <th class="text-center" width="50">#</th>
                    <th><?php echo __('date'); ?></th>
                    <th><?php echo __('patient'); ?></th>
                    <th><?php echo __('policy_number'); ?></th>
                    <th><?php echo __('doctor'); ?></th>
                    <th class="text-end"><?php echo __('total_amount'); ?></th>
                    <th class="text-end"><?php echo __('insurance_covered'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($bills)): ?>
                <tr>
                    <td colspan="7" class="text-center py-4 text-muted"><?php echo __('no_records_found'); ?></td>
                </tr>
                <?php else: ?>
                <?php $i = 1; foreach ($bills as $bill): ?>
                <tr>
                    <td class="text-center"><?php echo $i++; ?></td>
                    <td><?php echo date('Y-m-d', strtotime($bill['created_at'])); ?></td>
                    <td>
                        <?php echo htmlspecialchars($bill['patient_name']); ?>
                        <?php if ($bill['civil_id']): ?>
                        <br><small class="text-muted"><?php echo htmlspecialchars($bill['civil_id']); ?></small>
                        <?php endif; ?>
                    </td>
                    <td><?php echo htmlspecialchars($bill['policy_number'] ?: '-'); ?></td>
                    <td><?php echo htmlspecialchars($bill['doctor_name_en'] ?: '-'); ?></td>
                    <td class="text-end"><?php echo format_currency($bill['total_amount']); ?></td>
                    <td class="text-end fw-bold"><?php echo format_currency($bill['insurance_covered']); ?></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
            <tfoot>
                <tr class="table-light">
                    <td colspan="6" class="text-end fw-bold fs-5"><?php echo __('total'); ?></td>
                    <td class="text-end fw-bold fs-5"><?php echo format_currency($total_claim); ?></td>
                </tr>
            </tfoot>
        </table>

        <!-- Footer -->
        <div class="invoice-footer text-center small text-muted">
            <p class="mb-1">Thank you for your partnership!</p>
            <p>Generated on <?php echo date('Y-m-d H:i:s'); ?></p>
        </div>
    </div>
</div>

</body>
</html>
