<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!isset($_SESSION['admin_id'])) { header("Location: login.php"); exit(); }
include '../include/config.php';

// Check if qr_code column exists, if not add it
$check = $conn->query("SHOW COLUMNS FROM patients LIKE 'qr_code'");
if ($check->num_rows == 0) {
    $conn->query("ALTER TABLE patients ADD COLUMN qr_code VARCHAR(255)");
}

$patients = $conn->query("SELECT patient_id, first_name, last_name, qr_code FROM patients ORDER BY created_at DESC");

if (isset($_GET['generate'])) {
    $patient_id = $_GET['patient_id'];
    $qr_data = "https://UHD.com.ng/patient/pin_login.php?patient_id=" . urlencode($patient_id);
    $qr_url = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" . urlencode($qr_data);
    $conn->query("UPDATE patients SET qr_code = '$qr_url' WHERE patient_id = '$patient_id'");
    header("Location: generate_qr.php?success=1");
    exit();
}
?>
<!DOCTYPE html>
<html>
<head><title>Hospital Cards</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"></head>
<body>
<div class="container mt-4">
    <h2>Hospital Card Generator</h2>
    <?php if(isset($_GET['success'])): ?>
        <div class="alert alert-success">QR Code generated!</div>
    <?php endif; ?>
    <div class="row">
        <?php if($patients && $patients->num_rows > 0): ?>
            <?php while($p = $patients->fetch_assoc()): ?>
            <div class="col-md-3 mb-3">
                <div class="card text-center">
                    <div class="card-body">
                        <?php if(!empty($p['qr_code'])): ?>
                            <img src="<?= $p['qr_code'] ?>" style="width: 120px;">
                        <?php else: ?>
                            <a href="?generate=1&patient_id=<?= $p['patient_id'] ?>" class="btn btn-primary btn-sm">Generate QR</a>
                        <?php endif; ?>
                        <h6 class="mt-2"><?= htmlspecialchars($p['first_name'].' '.$p['last_name']) ?></h6>
                        <p class="mb-0">ID: <?= $p['patient_id'] ?></p>
                        <p>PIN: <?= substr($p['patient_id'], 0, 4) ?></p>
                    </div>
                </div>
            </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div class="col-12"><p>No patients found.</p></div>
        <?php endif; ?>
    </div>
    <a href="dashboard.php" class="btn btn-secondary">Back</a>
</div>
</body>
</html>