<?php
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
require_once 'includes/translation.php';

if (!isset($_SESSION['user_id'])) {
    redirect('login.php');
}

$db = new Database();
$conn = $db->getConnection();

$patient_id = $_GET['id'] ?? 0;

// Get patient details
$stmt = $conn->prepare("SELECT * FROM patients WHERE id = ?");
$stmt->execute([$patient_id]);
$patient = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$patient) {
    header("Location: " . (isset($_SERVER["HTTPS"]) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER["SCRIPT_NAME"]), "/\\") . "/" . "manage_patients.php");
    exit();
}

// Get patient reports
$stmt = $conn->prepare("
    SELECT 
        ar.id,
        ar.report_date,
        ar.status,
        ar.created_at,
        u.unit_name,
        COALESCE(a.antibiotic_name, ar.other_medication_name, 'غير محدد') as antibiotic_name,
        usr.full_name as pharmacist_name
    FROM antibiotic_reports ar
    JOIN units u ON ar.unit_id = u.id
    LEFT JOIN antibiotics a ON ar.antibiotic_id = a.id
    JOIN users usr ON ar.reporting_pharmacist_id = usr.id
    WHERE ar.patient_id = ?
    ORDER BY ar.created_at DESC
");
$stmt->execute([$patient_id]);
$reports = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Set page title
$page_title = __('view_patient') . ' - ' . __('system_name');

// Include header
include 'includes/header.php';
?>


    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0"><?php echo __('view_patient'); ?></h1>
        <div>
            <a href="edit_patient.php?id=<?php echo $patient['id']; ?>" class="btn btn-warning me-2">
                <i class="fas fa-edit"></i> <?php echo __('edit'); ?>
            </a>
            <a href="manage_patients.php" class="btn btn-secondary">
                <i class="fas fa-arrow-<?php echo Translation::getDirection() == 'rtl' ? 'right' : 'left'; ?>"></i> <?php echo __('back_to_patients'); ?>
            </a>
        </div>
    </div>

    <div class="row">
        <!-- Patient Information -->
        <div class="col-md-4 mb-4">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">معلومات المريض</h6>
                </div>
                <div class="card-body">
                    <div class="text-center mb-3">
                        <div class="avatar-circle bg-primary text-white mb-2">
                            <i class="fas fa-user fa-2x"></i>
                        </div>
                        <h5 class="mb-0"><?php echo htmlspecialchars($patient['patient_name']); ?></h5>
                        <p class="text-muted">رقم الملف: <?php echo htmlspecialchars($patient['mrn']); ?></p>
                    </div>

                    <hr>

                    <div class="mb-3">
                        <strong class="text-muted">الجنس:</strong>
                        <span class="float-end">
                            <?php echo $patient['gender'] == 'male' ? 'ذكر' : 'أنثى'; ?>
                        </span>
                    </div>

                    <div class="mb-3">
                        <strong class="text-muted">العمر:</strong>
                        <span class="float-end"><?php echo htmlspecialchars($patient['age'] ?? 'غير محدد'); ?></span>
                    </div>

                    <div class="mb-3">
                        <strong class="text-muted">رقم الهاتف:</strong>
                        <span class="float-end"><?php echo htmlspecialchars($patient['phone'] ?? 'غير محدد'); ?></span>
                    </div>

                    <div class="mb-3">
                        <strong class="text-muted"><?php echo __('date_added'); ?>:</strong>
                        <span class="float-end"><?php echo date('Y-m-d', strtotime($patient['created_at'])); ?></span>
                    </div>

                    <?php if (!empty($patient['units'])): ?>
                    <div class="mb-3">
                        <strong class="text-muted">الأقسام:</strong>
                        <div class="mt-2">
                            <?php 
                            $units = json_decode($patient['units'], true);
                            if (is_array($units)):
                                foreach ($units as $unit):
                            ?>
                            <span class="badge bg-info me-1 mb-1"><?php echo htmlspecialchars($unit); ?></span>
                            <?php 
                                endforeach;
                            endif;
                            ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Quick Stats -->
            <div class="card shadow mt-3">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-success"><?php echo __('quick_stats'); ?></h6>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <div class="d-flex justify-content-between">
                            <span class="text-muted"><?php echo __('total_reports'); ?>:</span>
                            <span class="font-weight-bold text-primary"><?php echo count($reports); ?></span>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="d-flex justify-content-between">
                            <span class="text-muted"><?php echo __('pending_reports'); ?>:</span>
                            <span class="font-weight-bold text-warning">
                                <?php echo count(array_filter($reports, function($r) { return $r['status'] == 'pending'; })); ?>
                            </span>
                        </div>
                    </div>
                    
                    <div>
                        <div class="d-flex justify-content-between">
                            <span class="text-muted"><?php echo __('completed_reports'); ?>:</span>
                            <span class="font-weight-bold text-success">
                                <?php echo count(array_filter($reports, function($r) { return $r['status'] == 'completed'; })); ?>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Patient Reports -->
        <div class="col-md-8 mb-4">
            <div class="card shadow">
                <div class="card-header py-3 d-flex justify-content-between align-items-center">
                    <h6 class="m-0 font-weight-bold text-primary"><?php echo __('patient_reports'); ?></h6>
                    <a href="clinical_pharmacy_intervention.php?patient_id=<?php echo $patient['id']; ?>" class="btn btn-sm btn-primary">
                        <i class="fas fa-plus"></i> <?php echo __('new_report'); ?>
                    </a>
                </div>
                <div class="card-body">
                    <?php if (empty($reports)): ?>
                    <div class="text-center py-4">
                        <i class="fas fa-clipboard-list fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted"><?php echo __('no_reports'); ?></h5>
                        <p class="text-muted"><?php echo __('no_reports_message'); ?></p>
                        <a href="clinical_pharmacy_intervention.php?patient_id=<?php echo $patient['id']; ?>" class="btn btn-primary">
                            <i class="fas fa-plus"></i> <?php echo __('create_new_report'); ?>
                        </a>
                    </div>
                    <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>تاريخ التقرير</th>
                                    <th>المضاد الحيوي</th>
                                    <th>القسم</th>
                                    <th>الصيدلي</th>
                                    <th>الحالة</th>
                                    <th>الإجراءات</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($reports as $report): ?>
                                <tr>
                                    <td><?php echo date('Y-m-d', strtotime($report['report_date'])); ?></td>
                                    <td><?php echo htmlspecialchars($report['antibiotic_name']); ?></td>
                                    <td><?php echo htmlspecialchars($report['unit_name']); ?></td>
                                    <td><?php echo htmlspecialchars($report['pharmacist_name']); ?></td>
                                    <td>
                                        <?php
                                        $status_class = '';
                                        $status_text = '';
                                        switch($report['status']) {
                                            case 'pending':
                                                $status_class = 'bg-warning';
                                                $status_text = 'معلق';
                                                break;
                                            case 'completed':
                                                $status_class = 'bg-success';
                                                $status_text = 'مكتمل';
                                                break;
                                            case 'cancelled':
                                                $status_class = 'bg-danger';
                                                $status_text = 'ملغي';
                                                break;
                                            default:
                                                $status_class = 'bg-secondary';
                                                $status_text = 'غير محدد';
                                        }
                                        ?>
                                        <span class="badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                    </td>
                                    <td>
                                        <a href="reports.php" class="btn btn-sm btn-info" title="<?php echo __('view'); ?>">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="edit_report.php?id=<?php echo $report['id']; ?>" class="btn btn-sm btn-warning" title="<?php echo __('edit'); ?>">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="print_report.php?id=<?php echo $report['id']; ?>" class="btn btn-sm btn-secondary" title="طباعة" target="_blank">
                                            <i class="fas fa-print"></i>
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.avatar-circle {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
}
</style>

<?php include 'includes/footer.php'; ?>
