<?php
session_start();
header('Content-Type: text/html; charset=utf-8');

include '../layouts/dbconn.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo '<div class="alert alert-danger">Unauthorized access</div>';
    exit();
}

if (!isset($_POST['patient_id'])) {
    echo '<div class="alert alert-danger">Missing patient ID</div>';
    exit();
}

$patient_id = intval($_POST['patient_id']);

// Get prescriptions for this patient
$query = "SELECT 
    pr.*,
    m.medication_name,
    m.strength,
    m.form,
    m.manufacturer,
    c.consultation_id,
    c.consultation_date,
    doc_user.full_name as prescribed_by_name,
    d.specialization
FROM prescriptions pr
LEFT JOIN medications m ON pr.medication_id = m.medication_id
INNER JOIN consultations c ON pr.consultation_id = c.consultation_id
INNER JOIN doctors d ON c.doctor_id = d.doctor_id
INNER JOIN users doc_user ON d.user_id = doc_user.user_id
WHERE pr.patient_id = ?
ORDER BY pr.created_at DESC";

$stmt = $conn->prepare($query);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 0) {
    echo '<div class="alert alert-info">No prescriptions found for this patient.</div>';
    exit();
}
?>

<div class="table-responsive">
    <table class="table table-hover align-middle">
        <thead class="table-light">
            <tr>
                <th>Date</th>
                <th>Medication</th>
                <th>Dosage</th>
                <th>Frequency</th>
                <th>Duration</th>
                <th>Prescribed By</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($prescription = $result->fetch_assoc()): ?>
            <tr>
                <td>
                    <?php echo date('M d, Y', strtotime($prescription['created_at'])); ?>
                    <br>
                    <small class="text-muted"><?php echo date('h:i A', strtotime($prescription['created_at'])); ?></small>
                </td>
                <td>
                    <strong><?php echo htmlspecialchars($prescription['medication_name']); ?></strong>
                    <br>
                    <small class="text-muted">
                        <?php echo htmlspecialchars($prescription['strength'] . ' ' . $prescription['form']); ?>
                    </small>
                    <?php if ($prescription['manufacturer']): ?>
                    <br><small class="text-muted">By: <?php echo htmlspecialchars($prescription['manufacturer']); ?></small>
                    <?php endif; ?>
                </td>
                <td><?php echo htmlspecialchars($prescription['dosage']); ?></td>
                <td><?php echo htmlspecialchars($prescription['frequency']); ?></td>
                <td><?php echo htmlspecialchars($prescription['duration']); ?></td>
                <td>
                    <?php echo htmlspecialchars($prescription['prescribed_by_name']); ?>
                    <br>
                    <small class="text-muted"><?php echo htmlspecialchars($prescription['specialization']); ?></small>
                </td>
                <td>
                    <?php
                    $status_badge = [
                        'ACTIVE' => 'success',
                        'COMPLETED' => 'secondary',
                        'DISCONTINUED' => 'danger',
                        'PENDING' => 'warning'
                    ];
                    $badge_class = $status_badge[$prescription['status']] ?? 'secondary';
                    ?>
                    <span class="badge bg-<?php echo $badge_class; ?>">
                        <?php echo htmlspecialchars($prescription['status']); ?>
                    </span>
                    <?php if ($prescription['dispensed_date']): ?>
                    <br><small class="text-success">Dispensed: <?php echo date('M d', strtotime($prescription['dispensed_date'])); ?></small>
                    <?php endif; ?>
                </td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <a href="view_consultation.php?id=<?php echo $prescription['consultation_id']; ?>" 
                           class="btn btn-outline-info" title="View Consultation">
                            <i class="ri-file-text-line"></i>
                        </a>
                        <?php if ($prescription['status'] == 'ACTIVE'): ?>
                        <button class="btn btn-outline-primary" 
                                onclick="printPrescription(<?php echo $prescription['prescription_id']; ?>)" 
                                title="Print Prescription">
                            <i class="ri-printer-line"></i>
                        </button>
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
            <?php 
            // Show instructions if available
            if ($prescription['instructions']): 
            ?>
            <tr>
                <td colspan="8" class="bg-light">
                    <small><strong>Instructions:</strong> <?php echo nl2br(htmlspecialchars($prescription['instructions'])); ?></small>
                </td>
            </tr>
            <?php endif; ?>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<script>
function printPrescription(prescriptionId) {
    window.open('print_prescription.php?id=' + prescriptionId, '_blank');
}
</script>

<?php
$conn->close();
?>