<?php
/**
 * صفحة المهام - Smart Doctor
 */
$page = 'tasks';
$filter = $_GET['filter'] ?? 'all'; // all, pending, completed, overdue, today
$category = $_GET['category'] ?? '';

$tasks = [];
$stats = ['total' => 0, 'pending' => 0, 'completed' => 0, 'overdue' => 0, 'today' => 0];

try {
    $db->query('SELECT id FROM doctor_tasks LIMIT 1');
    
    // الإحصائيات
    $stmt = $db->prepare('SELECT 
        COUNT(*) AS total,
        SUM(CASE WHEN is_completed = 0 THEN 1 ELSE 0 END) AS pending,
        SUM(CASE WHEN is_completed = 1 THEN 1 ELSE 0 END) AS completed,
        SUM(CASE WHEN is_completed = 0 AND due_date < CURDATE() THEN 1 ELSE 0 END) AS overdue,
        SUM(CASE WHEN is_completed = 0 AND due_date = CURDATE() THEN 1 ELSE 0 END) AS today
        FROM doctor_tasks WHERE doctor_account_id = ?');
    $stmt->execute([$doctorAuth->accountId()]);
    $stats = $stmt->fetch();
    
    // بناء الاستعلام
    $where = 'doctor_account_id = ?';
    $params = [$doctorAuth->accountId()];
    
    if ($filter === 'pending') {
        $where .= ' AND is_completed = 0';
    } elseif ($filter === 'completed') {
        $where .= ' AND is_completed = 1';
    } elseif ($filter === 'overdue') {
        $where .= ' AND is_completed = 0 AND due_date < CURDATE()';
    } elseif ($filter === 'today') {
        $where .= ' AND is_completed = 0 AND due_date = CURDATE()';
    }
    
    if ($category) {
        $where .= ' AND category = ?';
        $params[] = $category;
    }
    
    $stmt = $db->prepare("SELECT t.*, 
        p.full_name AS patient_name,
        o.order_number
        FROM doctor_tasks t
        LEFT JOIN patients p ON p.id = t.patient_id
        LEFT JOIN lab_orders o ON o.id = t.order_id
        WHERE $where 
        ORDER BY 
            CASE WHEN is_completed = 0 AND due_date < CURDATE() THEN 0 ELSE 1 END,
            CASE priority WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 ELSE 3 END,
            due_date ASC, due_time ASC
        LIMIT 100");
    $stmt->execute($params);
    $tasks = $stmt->fetchAll();
} catch (Throwable $e) {}

// إضافة مهمة
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_task'])) {
    $taskText = trim($_POST['task_text'] ?? '');
    $priority = in_array($_POST['priority'] ?? 'medium', ['low', 'medium', 'high', 'urgent']) ? $_POST['priority'] : 'medium';
    $dueDate = $_POST['due_date'] ?? null;
    $dueTime = $_POST['due_time'] ?? null;
    $category = trim($_POST['category'] ?? '');
    $patientId = !empty($_POST['patient_id']) ? (int)$_POST['patient_id'] : null;
    $orderId = !empty($_POST['order_id']) ? (int)$_POST['order_id'] : null;
    $notes = trim($_POST['notes'] ?? '');
    
    if ($taskText !== '') {
        try {
            $stmt = $db->prepare('INSERT INTO doctor_tasks (doctor_account_id, task_text, priority, due_date, due_time, category, patient_id, order_id, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
            $stmt->execute([$doctorAuth->accountId(), $taskText, $priority, $dueDate ?: null, $dueTime ?: null, $category ?: null, $patientId, $orderId, $notes ?: null]);
            $_SESSION['doctor_msg'] = 'تم إضافة المهمة.';
            header('Location: doctor.php?page=tasks');
            exit;
        } catch (Throwable $e) {
            $_SESSION['doctor_error'] = 'فشل إضافة المهمة.';
        }
    }
}

// تحديث حالة المهمة
if (isset($_GET['toggle']) && $_GET['toggle'] > 0) {
    $taskId = (int)$_GET['toggle'];
    try {
        $stmt = $db->prepare('SELECT is_completed FROM doctor_tasks WHERE id = ? AND doctor_account_id = ?');
        $stmt->execute([$taskId, $doctorAuth->accountId()]);
        $task = $stmt->fetch();
        if ($task) {
            $newStatus = $task['is_completed'] ? 0 : 1;
            $db->prepare('UPDATE doctor_tasks SET is_completed = ?, completed_at = ? WHERE id = ?')->execute([$newStatus, $newStatus ? date('Y-m-d H:i:s') : null, $taskId]);
        }
        header('Location: doctor.php?page=tasks&filter=' . $filter);
        exit;
    } catch (Throwable $e) {}
}

// حذف مهمة
if (isset($_GET['delete']) && $_GET['delete'] > 0) {
    $taskId = (int)$_GET['delete'];
    try {
        $db->prepare('DELETE FROM doctor_tasks WHERE id = ? AND doctor_account_id = ?')->execute([$taskId, $doctorAuth->accountId()]);
        $_SESSION['doctor_msg'] = 'تم حذف المهمة.';
        header('Location: doctor.php?page=tasks');
        exit;
    } catch (Throwable $e) {}
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/svg+xml" href="favicon.svg">
    <title>المهام - Smart Doctor</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
<?php include __DIR__ . '/_layout.php'; ?>
<main class="content">
    <?php
    $doctorPageTitle = '✅ المهام';
    $doctorPageDesc = 'قائمة مهامك المرتبطة بالمرضى والطلبات؛ تابع ما يحتاج إكمالاً اليوم.';
    $doctorPageLinks = [
        ['href' => 'doctor.php?page=reminders', 'label' => '⏰ التذكيرات'],
        ['href' => 'doctor.php?page=alerts', 'label' => '🔔 التنبيهات'],
        ['href' => 'doctor.php?page=dashboard', 'label' => '🏠 الرئيسية'],
    ];
    include __DIR__ . '/_page_intro.php';
    ?>

    <!-- إحصائيات سريعة -->
    <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(140px, 1fr));gap:12px;margin-bottom:24px;">
        <div class="card" style="text-align:center;padding:16px;">
            <div style="font-size:1.75rem;font-weight:bold;color:var(--primary);"><?php echo $stats['total']; ?></div>
            <div style="color:var(--text-muted);font-size:0.9rem;margin-top:4px;">إجمالي</div>
        </div>
        <div class="card" style="text-align:center;padding:16px;border-right:4px solid #f59e0b;">
            <div style="font-size:1.75rem;font-weight:bold;color:#f59e0b;"><?php echo $stats['pending']; ?></div>
            <div style="color:var(--text-muted);font-size:0.9rem;margin-top:4px;">قيد التنفيذ</div>
        </div>
        <div class="card" style="text-align:center;padding:16px;border-right:4px solid #22c55e;">
            <div style="font-size:1.75rem;font-weight:bold;color:#22c55e;"><?php echo $stats['completed']; ?></div>
            <div style="color:var(--text-muted);font-size:0.9rem;margin-top:4px;">مكتملة</div>
        </div>
        <div class="card" style="text-align:center;padding:16px;border-right:4px solid #ef4444;">
            <div style="font-size:1.75rem;font-weight:bold;color:#ef4444;"><?php echo $stats['overdue']; ?></div>
            <div style="color:var(--text-muted);font-size:0.9rem;margin-top:4px;">متأخرة</div>
        </div>
        <div class="card" style="text-align:center;padding:16px;border-right:4px solid #3b82f6;">
            <div style="font-size:1.75rem;font-weight:bold;color:#3b82f6;"><?php echo $stats['today']; ?></div>
            <div style="color:var(--text-muted);font-size:0.9rem;margin-top:4px;">اليوم</div>
        </div>
    </div>

    <!-- إضافة مهمة -->
    <div class="card" style="margin-bottom:24px;">
        <h3 style="margin:0 0 16px;padding-bottom:12px;border-bottom:1px solid var(--border);">➕ إضافة مهمة جديدة</h3>
        <form method="post">
            <div style="display:grid;grid-template-columns:2fr 1fr 1fr 1fr;gap:12px;margin-bottom:12px;">
                <input type="text" name="task_text" placeholder="نص المهمة..." required style="padding:10px;border-radius:8px;border:1px solid var(--border);">
                <select name="priority" style="padding:10px;border-radius:8px;border:1px solid var(--border);">
                    <option value="low">منخفضة</option>
                    <option value="medium" selected>متوسطة</option>
                    <option value="high">مهمة</option>
                    <option value="urgent">عاجلة</option>
                </select>
                <input type="date" name="due_date" style="padding:10px;border-radius:8px;border:1px solid var(--border);">
                <input type="time" name="due_time" style="padding:10px;border-radius:8px;border:1px solid var(--border);">
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr auto;gap:12px;">
                <input type="text" name="category" placeholder="الفئة (اختياري)" style="padding:10px;border-radius:8px;border:1px solid var(--border);">
                <input type="number" name="patient_id" placeholder="معرف المريض (اختياري)" style="padding:10px;border-radius:8px;border:1px solid var(--border);">
                <input type="number" name="order_id" placeholder="معرف الطلب (اختياري)" style="padding:10px;border-radius:8px;border:1px solid var(--border);">
                <button type="submit" name="add_task" class="btn-primary" style="padding:10px 20px;">إضافة</button>
            </div>
            <textarea name="notes" placeholder="ملاحظات إضافية (اختياري)" rows="2" style="width:100%;margin-top:12px;padding:10px;border-radius:8px;border:1px solid var(--border);resize:vertical;"></textarea>
        </form>
    </div>

    <!-- فلاتر -->
    <div class="card" style="margin-bottom:20px;">
        <div style="display:flex;gap:8px;flex-wrap:wrap;padding:12px;">
            <a href="doctor.php?page=tasks&filter=all" class="btn-secondary <?php echo $filter === 'all' ? 'active' : ''; ?>" style="<?php echo $filter === 'all' ? 'background:var(--primary);color:white;' : ''; ?>">الكل</a>
            <a href="doctor.php?page=tasks&filter=pending" class="btn-secondary <?php echo $filter === 'pending' ? 'active' : ''; ?>" style="<?php echo $filter === 'pending' ? 'background:var(--primary);color:white;' : ''; ?>">قيد التنفيذ</a>
            <a href="doctor.php?page=tasks&filter=today" class="btn-secondary <?php echo $filter === 'today' ? 'active' : ''; ?>" style="<?php echo $filter === 'today' ? 'background:var(--primary);color:white;' : ''; ?>">اليوم</a>
            <a href="doctor.php?page=tasks&filter=overdue" class="btn-secondary <?php echo $filter === 'overdue' ? 'active' : ''; ?>" style="<?php echo $filter === 'overdue' ? 'background:var(--primary);color:white;' : ''; ?>">متأخرة</a>
            <a href="doctor.php?page=tasks&filter=completed" class="btn-secondary <?php echo $filter === 'completed' ? 'active' : ''; ?>" style="<?php echo $filter === 'completed' ? 'background:var(--primary);color:white;' : ''; ?>">مكتملة</a>
        </div>
    </div>

    <!-- قائمة المهام -->
    <?php if (empty($tasks)): ?>
    <div class="card" style="text-align:center;padding:48px 24px;">
        <div style="font-size:3rem;margin-bottom:16px;opacity:0.5;">✅</div>
        <h3 style="margin:0 0 8px;">لا توجد مهام</h3>
        <p style="color:var(--text-muted);margin:0;">ابدأ بإضافة مهمة جديدة</p>
    </div>
    <?php else: ?>
    <div class="card">
        <div style="display:flex;flex-direction:column;gap:0;">
            <?php foreach ($tasks as $task): ?>
            <?php
            $isOverdue = !$task['is_completed'] && $task['due_date'] && strtotime($task['due_date']) < strtotime('today');
            $isToday = !$task['is_completed'] && $task['due_date'] && $task['due_date'] === date('Y-m-d');
            $priorityColors = ['low' => '#6b7280', 'medium' => '#3b82f6', 'high' => '#f59e0b', 'urgent' => '#ef4444'];
            $priorityLabels = ['low' => 'منخفضة', 'medium' => 'متوسطة', 'high' => 'مهمة', 'urgent' => 'عاجلة'];
            ?>
            <div class="doctor-task-item" style="padding:16px;border-bottom:1px solid var(--border);display:flex;gap:16px;align-items:flex-start;transition:background 0.2s;<?php echo $isOverdue ? 'background:rgba(239,68,68,0.05);border-right:4px solid #ef4444;' : ($isToday ? 'background:rgba(245,158,11,0.05);border-right:4px solid #f59e0b;' : ''); ?>">
                <div style="flex-shrink:0;margin-top:4px;">
                    <input type="checkbox" <?php echo $task['is_completed'] ? 'checked' : ''; ?> 
                        onchange="location.href='doctor.php?page=tasks&toggle=<?php echo $task['id']; ?>&filter=<?php echo $filter; ?>'"
                        style="width:20px;height:20px;cursor:pointer;">
                </div>
                <div style="flex:1;min-width:0;">
                    <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;margin-bottom:6px;">
                        <h3 style="margin:0;font-size:1.05rem;<?php echo $task['is_completed'] ? 'text-decoration:line-through;opacity:0.6;' : ''; ?>">
                            <?php echo htmlspecialchars($task['task_text'], ENT_QUOTES, 'UTF-8'); ?>
                        </h3>
                        <div style="display:flex;gap:6px;flex-shrink:0;flex-wrap:wrap;">
                            <span style="padding:4px 8px;background:<?php echo $priorityColors[$task['priority']]; ?>20;color:<?php echo $priorityColors[$task['priority']]; ?>;border-radius:6px;font-size:0.75rem;font-weight:500;">
                                <?php echo $priorityLabels[$task['priority']]; ?>
                            </span>
                            <?php if ($task['category']): ?>
                            <span style="padding:4px 8px;background:var(--bg-secondary);border-radius:6px;font-size:0.75rem;"><?php echo htmlspecialchars($task['category'], ENT_QUOTES, 'UTF-8'); ?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php if ($task['patient_name'] || $task['order_number']): ?>
                    <div style="margin:6px 0;font-size:0.9rem;color:var(--text-muted);">
                        <?php if ($task['patient_name']): ?>
                        <span>👤 <a href="doctor.php?page=results&patient_id=<?php echo $task['patient_id']; ?>"><?php echo htmlspecialchars($task['patient_name'], ENT_QUOTES, 'UTF-8'); ?></a></span>
                        <?php endif; ?>
                        <?php if ($task['order_number']): ?>
                        <span style="margin-right:12px;">📋 <a href="doctor.php?page=results&order_id=<?php echo $task['order_id']; ?>"><?php echo htmlspecialchars($task['order_number'], ENT_QUOTES, 'UTF-8'); ?></a></span>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                    <?php if ($task['notes']): ?>
                    <p style="margin:6px 0 0;color:var(--text-secondary);font-size:0.9rem;font-style:italic;">
                        <?php echo nl2br(htmlspecialchars($task['notes'], ENT_QUOTES, 'UTF-8')); ?>
                    </p>
                    <?php endif; ?>
                    <div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;font-size:0.85rem;color:var(--text-muted);margin-top:8px;">
                        <?php if ($task['due_date']): ?>
                        <span style="<?php echo $isOverdue ? 'color:#ef4444;font-weight:600;' : ($isToday ? 'color:#f59e0b;font-weight:600;' : ''); ?>">
                            📅 <?php echo date('Y-m-d', strtotime($task['due_date'])); ?>
                            <?php if ($task['due_time']): ?>
                            <?php echo date('H:i', strtotime($task['due_time'])); ?>
                            <?php endif; ?>
                            <?php if ($isOverdue): ?>
                            <span style="color:#ef4444;">(متأخرة)</span>
                            <?php elseif ($isToday): ?>
                            <span style="color:#f59e0b;">(اليوم)</span>
                            <?php endif; ?>
                        </span>
                        <?php endif; ?>
                        <?php if ($task['is_completed'] && $task['completed_at']): ?>
                        <span style="color:#22c55e;">✓ مكتملة: <?php echo date('Y-m-d H:i', strtotime($task['completed_at'])); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                <div style="flex-shrink:0;">
                    <a href="doctor.php?page=tasks&delete=<?php echo $task['id']; ?>" onclick="return confirm('هل أنت متأكد من حذف هذه المهمة؟');" style="padding:4px 10px;color:#ef4444;font-size:0.85rem;" title="حذف">🗑️</a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
</main>
</body>
</html>
