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

// Get hospitals list
$hospitals = $conn->query("SELECT * FROM partner_hospitals WHERE status = 'active' ORDER BY hospital_name");

// Get patients without cards
$patients_without_cards = $conn->query("
    SELECT p.* FROM patients p 
    LEFT JOIN issued_cards ic ON p.patient_id = ic.patient_id 
    WHERE ic.card_id IS NULL
    ORDER BY p.created_at DESC
");

// Get recently issued cards
$recent_cards = $conn->query("
    SELECT ic.*, p.first_name, p.last_name, ph.hospital_name 
    FROM issued_cards ic
    JOIN patients p ON ic.patient_id = p.patient_id
    LEFT JOIN partner_hospitals ph ON ic.hospital_id = ph.hospital_id
    ORDER BY ic.issued_date DESC LIMIT 50
");

// Handle card issuance
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['issue_card'])) {
    $patient_id = intval($_POST['patient_id']);
    $hospital_id = intval($_POST['hospital_id']);
    $card_type = $_POST['card_type'];
    $batch_number = $_POST['batch_number'];
    
    // Generate unique card number
    $card_number = 'UHD' . date('Y') . str_pad($patient_id, 6, '0', STR_PAD_LEFT) . rand(100, 999);
    
    // Generate QR data
    $qr_data = json_encode([
        'card_number' => $card_number,
        'patient_id' => $patient_id,
        'hospital_id' => $hospital_id,
        'issued_date' => date('Y-m-d'),
        'verification_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/verify_card.php'
    ]);
    
    $insert = $conn->query("
        INSERT INTO issued_cards (patient_id, hospital_id, card_number, qr_code_data, issued_by, card_type, batch_number)
        VALUES ($patient_id, $hospital_id, '$card_number', '" . addslashes($qr_data) . "', '{$_SESSION['admin_id']}', '$card_type', '$batch_number')
    ");
    
    if ($insert) {
        $success = "Card issued successfully! Card Number: $card_number";
        // Generate QR code image
        $qr_api = "https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=" . urlencode($qr_data);
    } else {
        $error = "Error: " . $conn->error;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Central Card Issuance - UHD</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        body { background: #0a3d2f; font-family: 'Segoe UI', sans-serif; }
        .card-issuance { background: white; border-radius: 15px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .qr-preview { width: 150px; height: 150px; background: #f8f9fa; border-radius: 10px; display: flex; align-items: center; justify-content: center; }
        .badge-active { background: #28a745; color: white; }
        .navbar { background: #064e3b !important; }
        .btn-gold { background: #d4a017; color: #1a0f08; }
        .btn-gold:hover { background: #b8860b; color: white; }
    </style>
</head>
<body>
<nav class="navbar navbar-dark">
    <div class="container">
        <span class="navbar-brand"><i class="fas fa-id-card"></i> Central Card Issuance System</span>
        <a href="dashboard.php" class="btn btn-light btn-sm">Back to Dashboard</a>
    </div>
</nav>

<div class="container mt-4">
    <div class="row">
        <!-- Left Column - Issue New Card -->
        <div class="col-md-5">
            <div class="card-issuance">
                <h4><i class="fas fa-plus-circle text-success"></i> Issue New Card</h4>
                <?php if(isset($success)): ?>
                    <div class="alert alert-success"><?= $success ?></div>
                    <?php if(isset($qr_api)): ?>
                        <div class="text-center">
                            <img src="<?= $qr_api ?>" alt="QR Code" style="width: 200px;">
                            <p><small>Scan to verify patient identity</small></p>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
                <?php if(isset($error)): ?>
                    <div class="alert alert-danger"><?= $error ?></div>
                <?php endif; ?>
                
                <form method="POST">
                    <div class="mb-3">
                        <label>Select Patient *</label>
                        <select name="patient_id" class="form-select" required>
                            <option value="">-- Select Patient --</option>
                            <?php while($p = $patients_without_cards->fetch_assoc()): ?>
                                <option value="<?= $p['patient_id'] ?>">
                                    <?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?> (ID: <?= $p['patient_id'] ?>)
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label>Assign to Hospital/Clinic *</label>
                        <select name="hospital_id" class="form-select" required>
                            <option value="">-- Select Hospital --</option>
                            <?php while($h = $hospitals->fetch_assoc()): ?>
                                <option value="<?= $h['hospital_id'] ?>"><?= htmlspecialchars($h['hospital_name']) ?> (<?= $h['hospital_code'] ?>)</option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label>Card Type *</label>
                        <select name="card_type" class="form-select" required>
                            <option value="plastic">Plastic Card (Premium)</option>
                            <option value="paper">Paper Card (Standard)</option>
                            <option value="digital">Digital Only</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label>Batch Number</label>
                        <input type="text" name="batch_number" class="form-control" placeholder="e.g., BATCH-2024-001">
                    </div>
                    
                    <button type="submit" name="issue_card" class="btn-gold btn w-100">
                        <i class="fas fa-print"></i> Issue Card & Print
                    </button>
                </form>
            </div>
            
            <!-- Add New Hospital -->
            <div class="card-issuance">
                <h5><i class="fas fa-hospital"></i> Register New Hospital</h5>
                <form method="POST" action="register_hospital.php">
                    <div class="mb-2">
                        <input type="text" name="hospital_name" class="form-control" placeholder="Hospital/Clinic Name" required>
                    </div>
                    <div class="mb-2">
                        <input type="text" name="phone" class="form-control" placeholder="Phone Number" required>
                    </div>
                    <div class="mb-2">
                        <input type="email" name="email" class="form-control" placeholder="Email">
                    </div>
                    <button type="submit" class="btn btn-primary btn-sm w-100">Register Hospital</button>
                </form>
            </div>
        </div>
        
        <!-- Right Column - Recent Cards -->
        <div class="col-md-7">
            <div class="card-issuance">
                <h4><i class="fas fa-history"></i> Recently Issued Cards</h4>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr><th>Card #</th><th>Patient</th><th>Hospital</th><th>Type</th><th>Date</th><th>Status</th></tr>
                        </thead>
                        <tbody>
                            <?php while($card = $recent_cards->fetch_assoc()): ?>
                            <tr>
                                <td><code><?= $card['card_number'] ?></code></td>
                                <td><?= htmlspecialchars($card['first_name'] . ' ' . $card['last_name']) ?></td>
                                <td><?= htmlspecialchars($card['hospital_name'] ?? 'N/A') ?></td>
                                <td><span class="badge bg-info"><?= $card['card_type'] ?></span></td>
                                <td><?= date('M d, Y', strtotime($card['issued_date'])) ?></td>
                                <td><span class="badge badge-active"><?= $card['card_status'] ?></span></td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>