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

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

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

try {
    $db = db();
    $bill_id = $_GET['bill_id'] ?? 0;

    if (!$bill_id) {
        throw new Exception("Invalid Bill ID");
    }

    // Fetch Bill Details
    $stmt = $db->prepare("SELECT * FROM bills WHERE id = ?");
    $stmt->execute([$bill_id]);
    $bill = $stmt->fetch();

    if (!$bill) {
        throw new Exception("Bill not found");
    }

    // Fetch Visit and Patient Details
    // Updated to join employees instead of doctors
    $stmt = $db->prepare("
        SELECT 
            v.*, 
            p.name as patient_name, 
            p.phone as patient_phone,
            p.civil_id,
            e.name_en as doctor_name_en, 
            e.name_ar as doctor_name_ar
        FROM visits v
        JOIN patients p ON v.patient_id = p.id
        LEFT JOIN employees e ON v.doctor_id = e.id
        WHERE v.id = ?
    ");
    $stmt->execute([$bill['visit_id']]);
    $visit = $stmt->fetch();

    // Fetch Bill Items
    $stmt = $db->prepare("SELECT * FROM bill_items WHERE bill_id = ?");
    $stmt->execute([$bill_id]);
    $items = $stmt->fetchAll();

    // 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>Invoice #<?php echo $bill_id; ?></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> Print</button>
        <button onclick="window.close()" class="btn btn-secondary">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>
                        Phone: <?php echo htmlspecialchars($settings['company_phone'] ?? '+123 456 7890'); ?><br>
                        Email: <?php echo htmlspecialchars($settings['company_email'] ?? 'info@hospital.com'); ?>
                    </div>
                </div>
                <div class="col-6 text-end">
                    <h1 class="invoice-title"><?php echo __('invoice'); ?></h1>
                    <p class="lead mb-0">#INV-<?php echo str_pad($bill_id, 6, '0', STR_PAD_LEFT); ?></p>
                    <p class="text-muted small">Date: <?php echo date('d M Y', strtotime($bill['created_at'])); ?></p>
                </div>
            </div>
        </div>

        <!-- Patient & Visit Details -->
        <div class="row mb-4">
            <div class="col-6">
                <h6 class="text-uppercase text-muted small fw-bold mb-2">Bill To:</h6>
                <h5 class="fw-bold mb-1"><?php echo htmlspecialchars($visit['patient_name']); ?></h5>
                <p class="mb-0 text-muted">
                    <?php if ($visit['patient_phone']) echo 'Phone: ' . htmlspecialchars($visit['patient_phone']) . '<br>'; ?>
                    <?php if ($visit['civil_id']) echo 'ID: ' . htmlspecialchars($visit['civil_id']); ?>
                </p>
            </div>
            <div class="col-6 text-end">
                <h6 class="text-uppercase text-muted small fw-bold mb-2">Visit Details:</h6>
                <p class="mb-0">
                    <strong>Doctor:</strong> <?php echo htmlspecialchars($visit['doctor_name_' . $lang] ?? $visit['doctor_name_en']); ?><br>
                    <strong>Visit ID:</strong> #<?php echo $visit['id']; ?><br>
                    <strong>Status:</strong> <span class="badge bg-light text-dark border"><?php echo $bill['status']; ?></span>
                </p>
            </div>
        </div>

        <!-- Items Table -->
        <table class="table table-bordered mb-4">
            <thead>
                <tr>
                    <th class="text-center" width="50">#</th>
                    <th><?php echo __('description'); ?></th>
                    <th class="text-end" width="150"><?php echo __('amount'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php $i = 1; foreach ($items as $item): ?>
                <tr>
                    <td class="text-center"><?php echo $i++; ?></td>
                    <td><?php echo htmlspecialchars($item['description']); ?></td>
                    <td class="text-end"><?php echo format_currency($item['amount']); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="2" class="text-end fw-bold">Total Amount</td>
                    <td class="text-end fw-bold"><?php echo format_currency($bill['total_amount']); ?></td>
                </tr>
                <?php if ($bill['insurance_covered'] > 0): ?>
                <tr>
                    <td colspan="2" class="text-end text-success">Insurance Covered</td>
                    <td class="text-end text-success">- <?php echo format_currency($bill['insurance_covered']); ?></td>
                </tr>
                <?php endif; ?>
                <tr>
                    <td colspan="2" class="text-end fw-bold fs-5">Patient Due</td>
                    <td class="text-end fw-bold fs-5"><?php echo format_currency($bill['patient_payable']); ?></td>
                </tr>
            </tfoot>
        </table>

        <!-- Payment Info -->
        <div class="row">
            <div class="col-md-6">
                <?php if ($bill['status'] == 'Paid'): ?>
                    <div class="alert alert-success d-inline-block py-2 px-3">
                        <i class="bi bi-check-circle-fill me-1"></i> <strong>PAID</strong> via <?php echo htmlspecialchars($bill['payment_method']); ?>
                    </div>
                <?php else: ?>
                    <div class="alert alert-warning d-inline-block py-2 px-3">
                        <i class="bi bi-clock me-1"></i> <strong>PENDING</strong>
                    </div>
                <?php endif; ?>
                
                <?php if (!empty($bill['notes'])): ?>
                    <p class="text-muted small mt-2"><strong>Notes:</strong> <?php echo htmlspecialchars($bill['notes']); ?></p>
                <?php endif; ?>
            </div>
            <div class="col-md-6 text-end">
                <!-- Signature or Thank you -->
                <br><br>
                <p class="fw-bold mb-0">_________________________</p>
                <p class="small text-muted">Authorized Signature</p>
            </div>
        </div>

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

</body>
</html>