<?php
/**
 * الوصفات الطبية
 */

use App\Core\Auth;
use App\Core\Tenant;

$action = $_GET['action'] ?? 'index';
$tenantId = Tenant::id();

if (!($auth instanceof Auth) || !$auth->can('prescriptions.view')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى هذه الصفحة';
    return;
}

// معالجة الصرف
if ($action === 'dispense' && isset($_GET['id'])) {
    if (!($auth instanceof Auth) || !$auth->can('prescriptions.dispense')) {
        http_response_code(403);
        echo 'غير مسموح بصرف الوصفات';
        return;
    }
    $prescId = (int)$_GET['id'];
    try {
        $stmt = $db->prepare('SELECT * FROM prescriptions WHERE id = ? AND tenant_id = ?');
        $stmt->execute([$prescId, $tenantId]);
        $prescription = $stmt->fetch();
        
        if ($prescription && !$prescription['is_dispensed']) {
            $stmt = $db->prepare('UPDATE prescriptions SET is_dispensed = 1, dispensed_at = NOW(), dispensed_by = ? WHERE id = ?');
            $stmt->execute([$_SESSION['user_id'] ?? null, $prescId]);
            
            if (isset($auditLog)) {
                $auditLog->log('prescription_dispensed', 'prescription', $prescId, null, null, $_SESSION['user_id'] ?? null);
            }
            $_SESSION['prescriptions_msg'] = 'تم صرف الوصفة بنجاح';
        }
    } catch (Throwable $e) {
        $_SESSION['prescriptions_error'] = 'خطأ في صرف الوصفة: ' . $e->getMessage();
    }
    header('Location: index.php?page=prescriptions&action=view&id=' . $prescId);
    exit;
}

// معالجة الإضافة
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!($auth instanceof Auth) || !$auth->can('prescriptions.create')) {
        http_response_code(403);
        echo 'غير مسموح بإضافة الوصفات';
        return;
    }
    
    $visitId = (int)($_POST['visit_id'] ?? 0);
    $doctorId = (int)($_POST['doctor_id'] ?? 0);
    $patientId = (int)($_POST['patient_id'] ?? 0);
    $prescriptionDate = trim($_POST['prescription_date'] ?? date('Y-m-d H:i:s'));
    $notes = trim($_POST['notes'] ?? '');
    $medications = $_POST['medications'] ?? [];
    
    if ($visitId > 0 && $doctorId > 0 && $patientId > 0 && !empty($medications)) {
        $prescriptionNumber = 'PRES-' . date('YmdHis') . rand(100, 999);
        
        try {
            $db->beginTransaction();
            
            $stmt = $db->prepare(
                'INSERT INTO prescriptions 
                 (prescription_number, visit_id, doctor_id, patient_id, prescription_date, notes, tenant_id)
                 VALUES (?, ?, ?, ?, ?, ?, ?)'
            );
            $stmt->execute([$prescriptionNumber, $visitId, $doctorId, $patientId, $prescriptionDate, $notes ?: null, $tenantId]);
            $prescId = (int)$db->lastInsertId();
            
            // إضافة الأدوية
            foreach ($medications as $med) {
                if (!empty($med['name'])) {
                    $stmt = $db->prepare(
                        'INSERT INTO prescription_items 
                         (prescription_id, medication_name, dosage, frequency, duration, quantity, instructions, item_order)
                         VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
                    );
                    $stmt->execute([
                        $prescId,
                        trim($med['name']),
                        trim($med['dosage'] ?? ''),
                        trim($med['frequency'] ?? ''),
                        trim($med['duration'] ?? ''),
                        !empty($med['quantity']) ? (int)$med['quantity'] : null,
                        trim($med['instructions'] ?? ''),
                        (int)($med['order'] ?? 0)
                    ]);
                }
            }
            
            $db->commit();
            
            if (isset($auditLog)) {
                $auditLog->log('prescription_created', 'prescription', $prescId, null, json_encode(['prescription_number' => $prescriptionNumber], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
            }
            $_SESSION['prescriptions_msg'] = 'تم إنشاء الوصفة بنجاح';
            header('Location: index.php?page=prescriptions&action=view&id=' . $prescId);
            exit;
        } catch (Throwable $e) {
            $db->rollBack();
            $_SESSION['prescriptions_error'] = 'خطأ في إنشاء الوصفة: ' . $e->getMessage();
        }
    } else {
        $_SESSION['prescriptions_error'] = 'يرجى إدخال جميع البيانات المطلوبة';
    }
    header('Location: index.php?page=prescriptions&action=create' . ($visitId ? '&visit_id=' . $visitId : ''));
    exit;
}

$msg = $_SESSION['prescriptions_msg'] ?? null;
$error = $_SESSION['prescriptions_error'] ?? null;
unset($_SESSION['prescriptions_msg'], $_SESSION['prescriptions_error']);

// عرض القائمة
if ($action === 'index') {
    $search = trim($_GET['search'] ?? '');
    $dateFilter = trim($_GET['date'] ?? '');
    
    $where = ['p.tenant_id = ?'];
    $params = [$tenantId];
    
    if ($search !== '') {
        $where[] = '(pt.full_name LIKE ? OR pt.patient_code LIKE ? OR p.prescription_number LIKE ?)';
        $searchParam = "%$search%";
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
    }
    
    if ($dateFilter !== '') {
        $where[] = 'DATE(p.prescription_date) = ?';
        $params[] = $dateFilter;
    }
    
    try {
        $stmt = $db->prepare(
            'SELECT p.*, pt.full_name as patient_name, pt.patient_code,
             d.full_name as doctor_name, v.visit_number
             FROM prescriptions p
             JOIN patients pt ON p.patient_id = pt.id
             JOIN clinic_doctors d ON p.doctor_id = d.id
             LEFT JOIN patient_visits v ON p.visit_id = v.id
             WHERE ' . implode(' AND ', $where) . '
             ORDER BY p.prescription_date DESC
             LIMIT 200'
        );
        $stmt->execute($params);
        $prescriptions = $stmt->fetchAll();
    } catch (Throwable $e) {
        $prescriptions = [];
    }
    
    ?>
    <div class="page-header">
        <h1>الوصفات الطبية</h1>
        <?php if ($auth->can('prescriptions.create')): ?>
            <a href="index.php?page=prescriptions&action=create" class="btn btn-primary">+ وصفة جديدة</a>
        <?php endif; ?>
    </div>
    
    <?php if ($msg): ?><div class="alert alert-success"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>
    
    <div class="search-box">
        <form method="get" action="index.php">
            <input type="hidden" name="page" value="prescriptions">
            <input type="text" name="search" placeholder="بحث..." value="<?= htmlspecialchars($search) ?>" style="width: 200px;">
            <input type="date" name="date" value="<?= htmlspecialchars($dateFilter) ?>" style="padding: 8px;">
            <button type="submit" class="btn">بحث</button>
            <?php if ($search || $dateFilter): ?>
                <a href="index.php?page=prescriptions" class="btn">إلغاء</a>
            <?php endif; ?>
        </form>
    </div>
    
    <table class="data-table">
        <thead>
            <tr>
                <th>رقم الوصفة</th>
                <th>التاريخ</th>
                <th>المريض</th>
                <th>الطبيب</th>
                <th>الزيارة</th>
                <th>الحالة</th>
                <th>الإجراءات</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($prescriptions)): ?>
                <tr><td colspan="7" style="text-align: center; padding: 20px;">لا توجد وصفات</td></tr>
            <?php else: ?>
                <?php foreach ($prescriptions as $presc): ?>
                    <tr>
                        <td><?= htmlspecialchars($presc['prescription_number']) ?></td>
                        <td><?= date('Y-m-d H:i', strtotime($presc['prescription_date'])) ?></td>
                        <td><?= htmlspecialchars($presc['patient_name']) ?></td>
                        <td><?= htmlspecialchars($presc['doctor_name']) ?></td>
                        <td><?= htmlspecialchars($presc['visit_number'] ?? '-') ?></td>
                        <td>
                            <span class="badge badge-<?= $presc['is_dispensed'] ? 'success' : 'warning' ?>">
                                <?= $presc['is_dispensed'] ? 'تم الصرف' : 'لم يتم الصرف' ?>
                            </span>
                        </td>
                        <td>
                            <a href="index.php?page=prescriptions&action=view&id=<?= $presc['id'] ?>" class="btn btn-sm">عرض</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
    <?php
}

// عرض الوصفة
elseif ($action === 'view') {
    $id = (int)($_GET['id'] ?? 0);
    try {
        $stmt = $db->prepare(
            'SELECT p.*, pt.full_name as patient_name, pt.patient_code, pt.phone as patient_phone,
             d.full_name as doctor_name, d.specialty as doctor_specialty,
             v.visit_number, c.name as clinic_name
             FROM prescriptions p
             JOIN patients pt ON p.patient_id = pt.id
             JOIN clinic_doctors d ON p.doctor_id = d.id
             LEFT JOIN patient_visits v ON p.visit_id = v.id
             LEFT JOIN clinics c ON d.clinic_id = c.id
             WHERE p.id = ? AND p.tenant_id = ?'
        );
        $stmt->execute([$id, $tenantId]);
        $prescription = $stmt->fetch();
    } catch (Throwable $e) {
        $prescription = false;
    }
    
    if (!$prescription) {
        echo '<div class="alert alert-danger">الوصفة غير موجودة</div>';
        echo '<a href="index.php?page=prescriptions" class="btn">العودة</a>';
        return;
    }
    
    // جلب الأدوية
    $medications = [];
    try {
        $stmt = $db->prepare('SELECT * FROM prescription_items WHERE prescription_id = ? ORDER BY item_order, id');
        $stmt->execute([$id]);
        $medications = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    ?>
    <div class="page-header">
        <h1>الوصفة الطبية</h1>
        <div>
            <?php if ($auth->can('prescriptions.dispense') && !$prescription['is_dispensed']): ?>
                <a href="index.php?page=prescriptions&action=dispense&id=<?= $id ?>" class="btn btn-primary" onclick="return confirm('هل تريد صرف هذه الوصفة؟');">صرف الوصفة</a>
            <?php endif; ?>
            <a href="index.php?page=prescriptions" class="btn">العودة</a>
        </div>
    </div>
    
    <div class="info-card">
        <h3>معلومات الوصفة</h3>
        <table class="info-table">
            <tr><th>رقم الوصفة:</th><td><?= htmlspecialchars($prescription['prescription_number']) ?></td></tr>
            <tr><th>التاريخ:</th><td><?= date('Y-m-d H:i', strtotime($prescription['prescription_date'])) ?></td></tr>
            <tr><th>المريض:</th><td><?= htmlspecialchars($prescription['patient_name']) ?> (<?= htmlspecialchars($prescription['patient_code']) ?>)</td></tr>
            <tr><th>الطبيب:</th><td><?= htmlspecialchars($prescription['doctor_name']) ?> - <?= htmlspecialchars($prescription['doctor_specialty'] ?? '') ?></td></tr>
            <tr><th>العيادة:</th><td><?= htmlspecialchars($prescription['clinic_name'] ?? '-') ?></td></tr>
            <?php if ($prescription['visit_number']): ?>
                <tr><th>الزيارة:</th><td><?= htmlspecialchars($prescription['visit_number']) ?></td></tr>
            <?php endif; ?>
            <tr><th>الحالة:</th>
                <td>
                    <span class="badge badge-<?= $prescription['is_dispensed'] ? 'success' : 'warning' ?>">
                        <?= $prescription['is_dispensed'] ? 'تم الصرف' : 'لم يتم الصرف' ?>
                    </span>
                </td>
            </tr>
        </table>
    </div>
    
    <div class="info-card">
        <h3>الأدوية</h3>
        <?php if (empty($medications)): ?>
            <p style="color: #666; text-align: center; padding: 20px;">لا توجد أدوية</p>
        <?php else: ?>
            <table class="data-table">
                <thead>
                    <tr>
                        <th>الدواء</th>
                        <th>الجرعة</th>
                        <th>التكرار</th>
                        <th>المدة</th>
                        <th>الكمية</th>
                        <th>تعليمات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($medications as $med): ?>
                        <tr>
                            <td><strong><?= htmlspecialchars($med['medication_name']) ?></strong></td>
                            <td><?= htmlspecialchars($med['dosage'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($med['frequency'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($med['duration'] ?? '-') ?></td>
                            <td><?= $med['quantity'] ?: '-' ?></td>
                            <td><?= htmlspecialchars($med['instructions'] ?? '-') ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
    
    <?php if ($prescription['notes']): ?>
        <div class="info-card">
            <h3>ملاحظات</h3>
            <p><?= nl2br(htmlspecialchars($prescription['notes'])) ?></p>
        </div>
    <?php endif; ?>
    <?php
}

// إضافة وصفة جديدة
elseif ($action === 'create') {
    $visitId = !empty($_GET['visit_id']) ? (int)$_GET['visit_id'] : 0;
    
    // جلب بيانات الزيارة إذا كانت موجودة
    $visit = null;
    if ($visitId > 0) {
        try {
            $stmt = $db->prepare(
                'SELECT v.*, p.id as patient_id, p.full_name as patient_name, d.id as doctor_id, d.full_name as doctor_name
                 FROM patient_visits v
                 JOIN patients p ON v.patient_id = p.id
                 JOIN clinic_doctors d ON v.doctor_id = d.id
                 WHERE v.id = ? AND v.tenant_id = ?'
            );
            $stmt->execute([$visitId, $tenantId]);
            $visit = $stmt->fetch();
        } catch (Throwable $e) {}
    }
    
    ?>
    <div class="page-header">
        <h1>وصفة طبية جديدة</h1>
        <a href="index.php?page=prescriptions" class="btn">العودة</a>
    </div>
    
    <form method="post" action="index.php?page=prescriptions&action=create" class="form-card" id="prescriptionForm">
        <input type="hidden" name="visit_id" value="<?= $visitId ?>">
        <input type="hidden" name="doctor_id" value="<?= $visit ? $visit['doctor_id'] : '' ?>" id="doctor_id">
        <input type="hidden" name="patient_id" value="<?= $visit ? $visit['patient_id'] : '' ?>" id="patient_id">
        
        <?php if ($visit): ?>
            <div class="alert alert-info">
                <strong>الزيارة:</strong> <?= htmlspecialchars($visit['visit_number']) ?><br>
                <strong>المريض:</strong> <?= htmlspecialchars($visit['patient_name']) ?><br>
                <strong>الطبيب:</strong> <?= htmlspecialchars($visit['doctor_name']) ?>
            </div>
        <?php endif; ?>
        
        <div class="form-group">
            <label>تاريخ الوصفة</label>
            <input type="datetime-local" name="prescription_date" value="<?= date('Y-m-d\TH:i') ?>" required>
        </div>
        
        <h3>الأدوية</h3>
        <div id="medications_list">
            <div class="medication-item" style="border: 1px solid #e0e0e0; padding: 15px; margin-bottom: 10px; border-radius: 8px;">
                <div class="form-row">
                    <div class="form-group" style="flex: 2;">
                        <label>اسم الدواء *</label>
                        <input type="text" name="medications[0][name]" required>
                    </div>
                    <div class="form-group">
                        <label>الجرعة</label>
                        <input type="text" name="medications[0][dosage]" placeholder="مثل: 500mg">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>التكرار</label>
                        <input type="text" name="medications[0][frequency]" placeholder="مثل: مرتين يومياً">
                    </div>
                    <div class="form-group">
                        <label>المدة</label>
                        <input type="text" name="medications[0][duration]" placeholder="مثل: 7 أيام">
                    </div>
                    <div class="form-group">
                        <label>الكمية</label>
                        <input type="number" name="medications[0][quantity]" min="1">
                    </div>
                </div>
                <div class="form-group">
                    <label>تعليمات خاصة</label>
                    <textarea name="medications[0][instructions]" rows="2"></textarea>
                </div>
                <input type="hidden" name="medications[0][order]" value="0">
            </div>
        </div>
        <button type="button" class="btn" onclick="addMedication()">+ إضافة دواء آخر</button>
        
        <div class="form-group" style="margin-top: 20px;">
            <label>ملاحظات</label>
            <textarea name="notes" rows="3"></textarea>
        </div>
        
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">إنشاء الوصفة</button>
            <a href="index.php?page=prescriptions" class="btn">إلغاء</a>
        </div>
    </form>
    
    <script>
    let medIndex = 1;
    function addMedication() {
        const list = document.getElementById('medications_list');
        const newItem = document.createElement('div');
        newItem.className = 'medication-item';
        newItem.style.cssText = 'border: 1px solid #e0e0e0; padding: 15px; margin-bottom: 10px; border-radius: 8px;';
        newItem.innerHTML = `
            <div class="form-row">
                <div class="form-group" style="flex: 2;">
                    <label>اسم الدواء *</label>
                    <input type="text" name="medications[${medIndex}][name]" required>
                </div>
                <div class="form-group">
                    <label>الجرعة</label>
                    <input type="text" name="medications[${medIndex}][dosage]" placeholder="مثل: 500mg">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>التكرار</label>
                    <input type="text" name="medications[${medIndex}][frequency]" placeholder="مثل: مرتين يومياً">
                </div>
                <div class="form-group">
                    <label>المدة</label>
                    <input type="text" name="medications[${medIndex}][duration]" placeholder="مثل: 7 أيام">
                </div>
                <div class="form-group">
                    <label>الكمية</label>
                    <input type="number" name="medications[${medIndex}][quantity]" min="1">
                </div>
            </div>
            <div class="form-group">
                <label>تعليمات خاصة</label>
                <textarea name="medications[${medIndex}][instructions]" rows="2"></textarea>
            </div>
            <input type="hidden" name="medications[${medIndex}][order]" value="${medIndex}">
            <button type="button" class="btn btn-sm" onclick="this.parentElement.remove()">حذف</button>
        `;
        list.appendChild(newItem);
        medIndex++;
    }
    </script>
    <?php
}
