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

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

// Enable error reporting for debugging (remove in production if sensitive)
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");
    }

    // Fetch visit details
    // Ensure all joined columns exist or use COALESCE/Check schema
    // We select specific columns to avoid 'ambiguous column' errors or fetching too much
    // Updated to join employees instead of doctors
    $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");
    }

    // Fetch prescriptions
    // Check if table exists implicitly by try-catch
    $stmt = $db->prepare("SELECT * FROM visit_prescriptions WHERE visit_id = ?");
    $stmt->execute([$visit_id]);
    $prescriptions = $stmt->fetchAll();


    // Fetch Company Settings
    $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>Prescription #<?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; }
        .rx-symbol { font-size: 40px; font-weight: bold; font-family: cursive; margin-bottom: 10px; }
        
        /* Grid Table Styles */
        .drug-grid { width: 100%; border-collapse: collapse; table-layout: fixed; }
        .drug-grid td { border: 1px solid #000; padding: 8px; vertical-align: top; }
        .drug-name { font-weight: bold; font-size: 15px; margin-bottom: 4px; display: block; }
        .drug-meta { font-size: 13px; line-height: 1.4; }
        .drug-meta strong { color: #555; }

        @media print {
            .no-print { display: none; }
            body { padding: 20px; }
            .drug-grid td { page-break-inside: avoid; }
        }
    </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"])) echo "Phone: " . htmlspecialchars($settings["company_phone"]); ?> 
            <?php if (!empty($settings["company_phone"]) && !empty($settings["company_email"])) echo " | "; ?>
            <?php if (!empty($settings["company_email"])) echo "Email: " . htmlspecialchars($settings["company_email"]); ?>
        </p>
    </div>

    <div class="row mb-4">
        <div class="col-6">
            <h5 class="fw-bold">Doctor:</h5>
            <p class="mb-0"><?php echo $visit['doctor_name_' . $lang] ?? $visit['doctor_name_en']; ?></p>
            <p class="text-muted small"><?php echo $visit['specialization_' . $lang] ?? $visit['specialization_en']; ?></p>
        </div>
        <div class="col-6 text-end">
            <h5 class="fw-bold">Date:</h5>
            <p><?php echo date('d M Y', strtotime($visit['visit_date'] ?? 'now')); ?></p>
        </div>
    </div>

    <div class="row mb-5 border p-3 rounded">
        <div class="col-md-6">
            <strong>Patient Name:</strong> <?php echo htmlspecialchars($visit['patient_name']); ?>
        </div>
        <div class="col-md-3">
            <strong>Age:</strong> <?php echo calculate_age($visit['dob']); ?>
        </div>
        <div class="col-md-3">
            <strong>Gender:</strong> <?php echo $visit['gender']; ?>
        </div>
    </div>

    <div class="rx-symbol">Rx</div>

    <div class="prescription-body mb-5">
        <?php if (empty($prescriptions)): ?>
            <p class="text-muted text-center py-5">No medications prescribed.</p>
        <?php else: ?>
            <table class="drug-grid">
                <?php 
                $chunks = array_chunk($prescriptions, 3); // 3 columns
                foreach ($chunks as $row): 
                ?>
                <tr>
                    <?php foreach ($row as $p): ?>
                    <td>
                        <div class="drug-name"><?php echo htmlspecialchars($p['drug_name']); ?></div>
                        <div class="drug-meta">
                            <div><strong>Dose:</strong> <?php echo htmlspecialchars($p['dosage']); ?></div>
                            <div><strong>Instr:</strong> <?php echo htmlspecialchars($p['instructions']); ?></div>
                        </div>
                    </td>
                    <?php endforeach; ?>
                    
                    <?php 
                    // Fill empty cells if the last row has fewer than 3 items
                    $missing = 3 - count($row);
                    for ($i = 0; $i < $missing; $i++): 
                    ?>
                    <td>&nbsp;</td>
                    <?php endfor; ?>
                </tr>
                <?php endforeach; ?>
            </table>
        <?php endif; ?>
    </div>

    <div class="prescription-footer">
        <div class="row">
            <div class="col-8">
                <p class="small text-muted">This prescription is valid for 30 days from the date of issue.</p>
            </div>
            <div class="col-4 text-center">
                <div class="border-bottom border-dark mb-2" style="height: 50px;"></div>
                <p class="fw-bold">Doctor's Signature</p>
            </div>
        </div>
    </div>
</div>

</body>
</html>