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

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

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

    if (!$visit_id) {
        throw new Exception("Invalid Visit ID");
    }

    $stmt = $db->prepare(
        "SELECT 
            v.*, 
            p.name as patient_name, 
            p.dob, 
            p.gender, 
            e.name_en as doctor_name_en, 
            e.name_ar as doctor_name_ar, 
            dept.name_en as specialization_en, 
            dept.name_ar as specialization_ar
        FROM visits v
        JOIN patients p ON v.patient_id = p.id
        LEFT JOIN employees e ON v.doctor_id = e.id
        LEFT JOIN departments dept ON e.department_id = dept.id
        WHERE v.id = ?"
    );
    $stmt->execute([$visit_id]);
    $visit = $stmt->fetch();

    if (!$visit) {
        throw new Exception("Visit not found");
    }

    $lang = $_SESSION['lang'] ?? 'en';

    // 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'];
    }

} 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><?php echo __('print_sick_leave'); ?> #<?php echo $visit_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; }
        .prescription-header { border-bottom: 2px solid #000; padding-bottom: 20px; margin-bottom: 30px; }
        .company-logo { max-height: 80px; }
        .prescription-footer { border-top: 2px solid #000; padding-top: 20px; margin-top: 50px; }
        .certificate-title { font-size: 32px; font-weight: bold; text-align: center; text-transform: uppercase; margin-bottom: 40px; text-decoration: underline; }
        .content-body { font-size: 18px; line-height: 2; margin-bottom: 40px; }
        .data-field { font-weight: bold; border-bottom: 1px dotted #000; display: inline-block; min-width: 150px; padding: 0 5px; text-align: center; } 
        
        @media print {
            .no-print { display: none; }
            body { padding: 40px; }
        }
    </style>
</head>
<body onload="window.print()">

<div class="container">
    <div class="no-print mb-3 text-end">
        <button onclick="window.print()" class="btn btn-primary">Print</button>
        <button onclick="window.close()" class="btn btn-secondary">Close</button>
    </div>

    <div class="prescription-header text-center">
        <?php if (!empty($settings['company_logo'])): ?>
            <img src="<?php echo htmlspecialchars($settings['company_logo']); ?>" alt="Logo" class="company-logo mb-2">
        <?php endif; ?>
        <h2 class="fw-bold m-0"><?php echo htmlspecialchars($settings['company_name'] ?? 'Hospital Management System'); ?></h2>
        <p class="mb-1"><?php echo htmlspecialchars($settings['company_address'] ?? '123 Medical Center Street, City, Country'); ?></p>
        <p class="mb-0">
            <?php if (!empty($settings['company_phone'])): ?>
                Phone: <?php echo htmlspecialchars($settings['company_phone']); ?>
            <?php else: ?>
                Phone: +123 456 7890
            <?php endif; ?>
            
            <?php if ((!empty($settings['company_phone']) || true) && (!empty($settings['company_email']) || true)) echo ' | '; ?>
            
            <?php if (!empty($settings['company_email'])): ?>
                Email: <?php echo htmlspecialchars($settings['company_email']); ?>
            <?php else: ?>
                Email: info@hospital.com
            <?php endif; ?>
        </p>
        <p class="mb-0 small text-muted">
            <?php if (!empty($settings['company_ctr_no'])) echo 'CTR No: ' . htmlspecialchars($settings['company_ctr_no']); ?>
            <?php if (!empty($settings['company_ctr_no']) && !empty($settings['company_registration_no'])) echo ' | ';
            ?>
            <?php if (!empty($settings['company_registration_no'])) echo 'Reg No: ' . htmlspecialchars($settings['company_registration_no']); ?>
            <?php if ((!empty($settings['company_ctr_no']) || !empty($settings['company_registration_no'])) && !empty($settings['company_vat_no'])) echo ' | ';
            ?>
            <?php if (!empty($settings['company_vat_no'])) echo 'VAT No: ' . htmlspecialchars($settings['company_vat_no']); ?>
        </p>
    </div>

    <div class="certificate-title">
        <?php echo $lang == 'ar' ? 'شهادة إجازة مرضية' : 'Medical Sick Leave Certificate'; ?>
    </div>

    <div class="content-body">
        <p>
            <?php if($lang == 'ar'): ?>
            تشهد العيادة بأن المريض 
            <span class="data-field"><?php echo htmlspecialchars($visit['patient_name']); ?></span>, 
            العمر: <span class="data-field"><?php echo calculate_age($visit['dob']); ?></span>, 
            الجنس: <span class="data-field"><?php echo $visit['gender'] == 'Male' ? 'ذكر' : 'أنثى'; ?></span>, 
            قد تم فحصه وعلاجه في منشأتنا بتاريخ 
            <span class="data-field"><?php echo date('d M Y', strtotime($visit['visit_date'] ?? 'now')); ?></span>.
            <?php else: ?>
            This is to certify that 
            <span class="data-field"><?php echo htmlspecialchars($visit['patient_name']); ?></span>, 
            Age: <span class="data-field"><?php echo calculate_age($visit['dob']); ?></span>, 
            Gender: <span class="data-field"><?php echo $visit['gender']; ?></span>, 
            was examined and treated at our facility on 
            <span class="data-field"><?php echo date('d M Y', strtotime($visit['visit_date'] ?? 'now')); ?></span>.
            <?php endif; ?>
        </p>

        <p>
            <?php if($lang == 'ar'): ?>
            بناءً على الفحص الطبي، يُنصح المريض بأخذ إجازة مرضية لمدة 
            <span class="data-field"><?php echo htmlspecialchars($visit['sick_leave_days'] ?? 0); ?></span> أيام, 
            ابتداءً من تاريخ 
            <span class="data-field"><?php echo htmlspecialchars($visit['sick_leave_start_date'] ?? ''); ?></span>.
            <?php else: ?>
            Based on the medical examination, the patient is advised to take a medical leave of absence for 
            <span class="data-field"><?php echo htmlspecialchars($visit['sick_leave_days'] ?? 0); ?></span> days, 
            starting from 
            <span class="data-field"><?php echo htmlspecialchars($visit['sick_leave_start_date'] ?? ''); ?></span>.
            <?php endif; ?>
        </p>

        <?php if (!empty($visit['sick_leave_remarks'])): ?>
        <p>
            <strong><?php echo $lang == 'ar' ? 'ملاحظات / توصيات:' : 'Remarks / Recommendations:'; ?></strong><br>
            <span style="white-space: pre-line;"><?php echo htmlspecialchars($visit['sick_leave_remarks']); ?></span>
        </p>
        <?php endif; ?>
    </div>

    <div class="prescription-footer mt-5">
        <div class="row">
            <div class="col-8">
                <p class="small text-muted">
                    <?php echo $lang == 'ar' ? 'تم إصدار هذه الشهادة بناءً على تقييم الطبيب وهي صالحة فقط للتواريخ المذكورة.' : 'This certificate is issued based on the doctor\'s assessment and is valid only for the stated dates.'; ?>
                </p>
            </div>
            <div class="col-4 text-center">
                <div class="border-bottom border-dark mb-2" style="height: 50px;"></div>
                <p class="fw-bold mb-0">Dr. <?php echo $visit['doctor_name_' . $lang] ?? $visit['doctor_name_en']; ?></p>
                <p class="small text-muted"><?php echo $visit['specialization_' . $lang] ?? $visit['specialization_en']; ?></p>
            </div>
        </div>
    </div>
</div>

</body>
</html>