<?php

// Fetch visit & patient details
$stmt = $pdo->prepare("
    SELECT v.*, 
           p.id AS patient_id,
           p.first_name, p.middle_name, p.last_name,
           p.d_o_b, p.gender, p.phone, p.email,
           p.emergency_contact_name, p.emergency_contact_phone,
           p.country, p.province, p.district, p.sector, p.cell, p.village,
           p.file_id,
           d.name AS department_name,
           u.username AS doctor_name,
           i.name AS insurance_name,
           inv.id AS invoice_id,
           inv.invoice_number
    FROM visits v
    JOIN patients p ON p.id = v.patient_id
    LEFT JOIN departments d ON d.id = v.department_id
    LEFT JOIN users u ON u.id = v.treated_by
    LEFT JOIN insurance_partners i ON i.id = v.insurance_id
    LEFT JOIN invoices inv ON inv.visit_id = v.id
    WHERE v.id = ?
");
$stmt->execute([$visit_id]);
$visit = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$visit && $visit_id > 0) {
    $_SESSION['flash'] = ['message' => 'Visit not found.', 'color' => '#dc3545'];
    header('Location: visits.php');
    exit;
}

// ---------------- DETERMINE $view_link BASED ON USER ROLE ----------------
if (in_array($role, ['Receptionist', 'Cashier', 'Doctor'])) {

    // If invoice exists → open invoice
    if (!empty($visit['invoice_id'])) {
        $view_link = "invoices.php?id={$visit['invoice_id']}";
    } else {
        // No invoice → open invoice builder
        $view_link = "invoices.php?visit_id={$visit_id}&patient_id={$visit['patient_id']}";
    }

} else {
    // All other roles → open visit ticket
    $view_link = "visit_ticket.php?id={$visit_id}";
}

// ---------------- Patient address ----------------
$address = '';
if ($visit) {
    $address = trim($visit['country'].' '.$visit['province'].' '.$visit['district'].' '.$visit['sector'].' '.$visit['cell'].' '.$visit['village']);
    $address = preg_replace('/\s+/', ' ', $address);
}

// Check if visit is discharged
$isDischarged = !empty($visit['discharge_time']);

?>

<!-- ===================== CARDS ROW ===================== -->

<div class="row">

    <!-- PATIENT INFORMATION -->
    <div class="col-sm-12 col-md-4">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title">Patient Information</h4>
                <a class="heading-elements-toggle"><i class="icon-ellipsis font-medium-3"></i></a>
            </div>
            <div class="card-body collapse in">
                <div class="card-block">
                    <div class="card-text">
                        <p><strong>Name:</strong> <?= htmlspecialchars($visit['first_name'].' '.($visit['middle_name'] ?: '').' '.$visit['last_name']) ?></p>
                        <p><strong>Age:</strong> <?= calculate_age($visit['d_o_b']) ?></p>
                        <p><strong>Gender:</strong> <?= htmlspecialchars($visit['gender']) ?></p>
                        <p><strong>File ID:</strong> <?= htmlspecialchars($visit['file_id']) ?></p>
                        <p><strong>Phone:</strong> <?= htmlspecialchars($visit['phone'] ?: '-') ?></p>
                        <p><strong>Address:</strong> <?= htmlspecialchars($address ?: '-') ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- VISIT INFORMATION -->
    <div class="col-sm-12 col-md-4">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title">Visit Information</h4>
                <a class="heading-elements-toggle"><i class="icon-ellipsis font-medium-3"></i></a>
            </div>
            <div class="card-body collapse in">
                <div class="card-block">
                    <div class="card-text">

                        <p><strong>Invoice Number:</strong>
                            <a href="invoices.php?visit_id=<?= $visit_id ?>&patient_id=<?= $visit['patient_id'] ?>">
                                <?= htmlspecialchars($visit['invoice_number'] ?: 'Open Invoice') ?>
                            </a>
                        </p>

                        <p><strong>Visit Date:</strong> <?= htmlspecialchars(date("Y-m-d H:i:s", strtotime($visit['visit_date']))) ?></p>
                        <p><strong>Department:</strong> <?= htmlspecialchars($visit['department_name'] ?: '-') ?></p>
                        <p><strong>Treated by:</strong> <?= htmlspecialchars($visit['doctor_name'] ?: '-') ?></p>
                        <p><strong>Visit Type:</strong> <?= htmlspecialchars($visit['visit_type'] ?: '-') ?> Patient</p>
                        <p><strong>Disease Type:</strong> <?= htmlspecialchars($visit['disease_type'] ?? '-') ?></p>
                        <p><strong>Voucher ID:</strong> <?= htmlspecialchars($visit['voucher_id'] ?? '-') ?></p>
                        
                        <!-- Discharge Status -->
                        <?php if ($isDischarged): ?>
                        <p><strong>Discharge Status:</strong> 
                            <span class="badge badge-success">Discharged</span>
                        </p>
                        <?php else: ?>
                        <p><strong>Discharge Status:</strong> 
                            <span class="badge badge-warning">Not Discharged</span>
                        </p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- INSURANCE INFORMATION -->
    <div class="col-sm-12 col-md-4">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title">Insurance Information</h4>
                <a class="heading-elements-toggle"><i class="icon-ellipsis font-medium-3"></i></a>
            </div>
            <div class="card-body collapse in">
                <div class="card-block">
                    <div class="card-text">
                        <p><strong>Insurance Name:</strong> <?= htmlspecialchars($visit['insurance_name'] ?: '-') ?></p>
                        <p><strong>Insurance Card Number:</strong> <?= htmlspecialchars($visit['insurance_card_number'] ?? '-') ?></p>
                        <p><strong>Patient Copay: </strong> <?= htmlspecialchars($visit['patient_co_pay_percentage'] ?? '-') ?> %</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div> <!-- /.row -->

<!-- Discharge Alert Banner -->
<?php if ($isDischarged): ?>
<div class="row">
    <div class="col-sm-12">
        <div class="alert alert-success alert-dismissible mb-2" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">×</span>
            </button>
            <strong><i class="icon-check"></i> Patient Discharged</strong> - 
            This patient was discharged on <?= date("F d, Y \a\\t H:i", strtotime($visit['discharge_time'])) ?>. 
            Treatment is complete.
        </div>
    </div>
</div>
<?php endif; ?>