<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';
require('assets/libs/fpdf/fpdf.php'); // Assuming FPDF is available, or we use simple HTML print

if (!isset($_SESSION['user_id']) || $_SESSION['role_code'] !== 'PATIENT') {
    die("Unauthorized access");
}

$user_id = $_SESSION['user_id'];
$pat_res = $conn->query("SELECT patient_id, full_name, patient_number FROM patients WHERE user_id = $user_id")->fetch_assoc();
$patient_id = $pat_res['patient_id'];

$type = $_GET['type'] ?? '';
$id = intval($_GET['id'] ?? 0);

if (!$type || !$id) {
    die("Invalid request");
}

// Logic: Generate PDF on the fly based on type
// For now, we'll generate a simple HTML page that auto-prints/saves as PDF, 
// or use a PDF library if installed. To allow immediate "Download", we use headers.

if ($type === 'visit') {
    $sql = "SELECT c.*, u.full_name as doctor_name, d.specialization
            FROM consultations c
            JOIN doctors d ON c.doctor_id = d.user_id
            JOIN users u ON d.user_id = u.user_id
            WHERE c.consultation_id = ? AND c.patient_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $id, $patient_id);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res->num_rows === 0)
        die("Record not found or access denied.");
    $data = $res->fetch_assoc();

    // Generate Report HTML for Print/PDF
    header("Content-type: text/html");
    header("Content-Disposition: inline; filename=visit_report_$id.html");
    ?>
    <!DOCTYPE html>
    <html>

    <head>
        <title>Visit Report - <?php echo $id; ?></title>
        <style>
            body {
                font-family: Arial, sans-serif;
                line-height: 1.6;
                padding: 40px;
            }

            .header {
                border-bottom: 2px solid #333;
                padding-bottom: 20px;
                margin-bottom: 30px;
                display: flex;
                justify-content: space-between;
            }

            .logo {
                font-size: 24px;
                font-weight: bold;
                color: #2d7a2d;
            }

            .meta {
                text-align: right;
                font-size: 14px;
                color: #666;
            }

            .section {
                margin-bottom: 20px;
            }

            .section h4 {
                border-bottom: 1px solid #ddd;
                padding-bottom: 5px;
                color: #2d7a2d;
                margin-bottom: 10px;
            }

            .info-grid {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 20px;
            }

            @media print {
                .no-print {
                    display: none;
                }
            }
        </style>
    </head>

    <body onload="window.print()">
        <div class="header">
            <div class="logo">Polakis 360 ENT Clinic</div>
            <div class="meta">
                Date: <?php echo date('d M Y'); ?><br>
                Ref: VST-<?php echo $id; ?>
            </div>
        </div>

        <div class="section">
            <div class="info-grid">
                <div>
                    <strong>Patient:</strong> <?php echo $pat_res['full_name']; ?><br>
                    <strong>File No:</strong> <?php echo $pat_res['patient_number']; ?>
                </div>
                <div style="text-align: right;">
                    <strong>Doctor:</strong> Dr. <?php echo $data['doctor_name']; ?><br>
                    <strong>Specialization:</strong> <?php echo $data['specialization']; ?>
                </div>
            </div>
        </div>

        <div class="section">
            <h4>Visit Details</h4>
            <p><strong>Date:</strong> <?php echo date('d M Y', strtotime($data['consultation_date'])); ?></p>
            <p><strong>Diagnosis:</strong><br><?php echo nl2br($data['diagnosis']); ?></p>
            <p><strong>Treatment Plan:</strong><br><?php echo nl2br($data['treatment_plan']); ?></p>
        </div>

        <div class="section">
            <p style="font-size: 12px; color: #999; text-align: center; margin-top: 50px;">
                This document is generated electronically from Polakis 360 ENT System.
            </p>
        </div>

        <div class="no-print" style="text-align: center; margin-top: 20px;">
            <button onclick="window.print()" style="padding: 10px 20px; cursor: pointer;">Print Report</button>
        </div>
    </body>

    </html>
    <?php
} elseif ($type === 'prescription') {
    // Similar logic for prescription
    // ...
    echo "Prescription download logic not yet implemented.";
} else {
    echo "Invalid type.";
}
?>