<?php
/**
 * تذكيرات المتابعة
 */
$reminders = [];
$today = date('Y-m-d');
try {
    $db->query('SELECT id FROM doctor_follow_up_reminders LIMIT 1');
    $stmt = $db->prepare('SELECT r.*, p.full_name AS patient_name, p.patient_code, p.phone
                          FROM doctor_follow_up_reminders r
                          JOIN patients p ON p.id = r.patient_id
                          WHERE r.doctor_account_id = ? AND r.reminder_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
                          ORDER BY r.is_done ASC, r.reminder_date ASC');
    $stmt->execute([$doctorAuth->accountId()]);
    $reminders = $stmt->fetchAll();
} catch (Throwable $e) {}

$upcoming = array_filter($reminders, fn($r) => $r['reminder_date'] >= $today && !$r['is_done']);
$overdue = array_filter($reminders, fn($r) => $r['reminder_date'] < $today && !$r['is_done']);
$done = array_filter($reminders, fn($r) => $r['is_done']);

$todayReminders = array_filter($upcoming, fn($r) => $r['reminder_date'] === $today);
$thisWeekReminders = array_filter($upcoming, function ($r) use ($today) {
    $d = strtotime($r['reminder_date']);
    $weekStart = strtotime('monday this week');
    $weekEnd = strtotime('sunday this week');
    return $d >= $weekStart && $d <= $weekEnd && $r['reminder_date'] !== $today;
});

function reminderDaysDiff($date) {
    $d = strtotime($date);
    $today = strtotime(date('Y-m-d'));
    return floor(($d - $today) / 86400);
}

$patientsForReminder = [];
$rc = ' AND o.tenant_id = ' . (int)($tenantId ?? 0);
$dc = ' AND o.doctor_id = ' . (int)($doctorId ?? 0);
try {
    $stmt = $db->prepare("SELECT p.id, p.full_name, p.patient_code FROM patients p JOIN lab_orders o ON o.patient_id = p.id WHERE 1=1 $rc $dc GROUP BY p.id ORDER BY p.full_name LIMIT 300");
    $stmt->execute();
    $patientsForReminder = $stmt->fetchAll();
} 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">
    <link rel="stylesheet" href="doctor.css">
</head>
<body>
<?php include __DIR__ . '/_layout.php'; ?>
<main class="content doctor-reminders-page">
    <div class="doctor-reminders-header">
        <div>
            <h1>تذكيرات المتابعة</h1>
            <p class="doctor-reminders-subtitle">إدارة تذكيرات متابعة المرضى</p>
        </div>
        <div class="doctor-reminders-actions">
            <a href="doctor.php?page=patients" class="btn-secondary">← المرضى</a>
            <button type="button" class="btn-secondary" id="reminderViewList" onclick="document.querySelector('.doctor-reminders-list-view').style.display='block';document.querySelector('#doctorRemindersCalendar').style.display='none';this.classList.add('active');document.getElementById('reminderViewCal').classList.remove('active')">📋 قائمة</button>
            <button type="button" class="btn-secondary" id="reminderViewCal" onclick="document.querySelector('.doctor-reminders-list-view').style.display='none';document.querySelector('#doctorRemindersCalendar').style.display='block';this.classList.add('active');document.getElementById('reminderViewList').classList.remove('active');if(typeof renderCal==='function')renderCal()">📅 تقويم</button>
        </div>
    </div>

    <div class="doctor-reminders-summary">
        <a href="#overdue" class="doctor-rem-summary-card doctor-rem-overdue">
            <span class="doctor-rem-summary-num"><?php echo count($overdue); ?></span>
            <span class="doctor-rem-summary-label">متأخرة</span>
        </a>
        <a href="#today" class="doctor-rem-summary-card doctor-rem-today">
            <span class="doctor-rem-summary-num"><?php echo count($todayReminders); ?></span>
            <span class="doctor-rem-summary-label">اليوم</span>
        </a>
        <a href="#week" class="doctor-rem-summary-card doctor-rem-week">
            <span class="doctor-rem-summary-num"><?php echo count($thisWeekReminders); ?></span>
            <span class="doctor-rem-summary-label">هذا الأسبوع</span>
        </a>
        <div class="doctor-rem-summary-card doctor-rem-done">
            <span class="doctor-rem-summary-num"><?php echo count($done); ?></span>
            <span class="doctor-rem-summary-label">منفذة</span>
        </div>
    </div>

    <div id="doctorRemindersCalendar" class="card doctor-calendar-card" style="display:none;margin-bottom:24px;">
        <h3 style="margin-top:0;">📅 تقويم التذكيرات</h3>
        <div class="doctor-calendar-nav">
            <button type="button" id="calPrev">← السابق</button>
            <span id="calMonthYear"></span>
            <button type="button" id="calNext">التالي →</button>
        </div>
        <div id="calGrid" class="doctor-calendar-grid"></div>
    </div>

    <div class="doctor-reminders-list-view">
    <?php if (!empty($patientsForReminder)): ?>
    <div class="doctor-add-reminder-card card">
        <h3 class="doctor-add-reminder-title">➕ إضافة تذكير جديد</h3>
        <form method="post" action="doctor.php?page=reminders&action=add" class="doctor-add-reminder-form">
            <input type="hidden" name="redirect" value="reminders">
            <div class="doctor-add-reminder-grid">
                <div class="doctor-form-group doctor-form-group-patient">
                    <label for="rem-patient-search">المريض</label>
                    <input type="text" id="rem-patient-search" placeholder="🔍 ابحث عن مريض..." class="doctor-patient-search-input" autocomplete="off">
                    <select name="patient_id" id="rem-patient" required>
                        <option value="" data-search="">-- اختر المريض --</option>
                        <?php foreach ($patientsForReminder as $pr): ?>
                        <option value="<?php echo (int)$pr['id']; ?>" data-search="<?php echo htmlspecialchars(mb_strtolower($pr['full_name'] . ' ' . ($pr['patient_code'] ?? '')), ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($pr['full_name'] . ' (' . $pr['patient_code'] . ')', ENT_QUOTES, 'UTF-8'); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="doctor-form-group">
                    <label for="rem-date">التاريخ</label>
                    <input type="date" name="reminder_date" id="rem-date" required value="<?php echo date('Y-m-d', strtotime('+2 weeks')); ?>">
                </div>
                <div class="doctor-form-group doctor-form-group-note">
                    <label for="rem-note">ملاحظة</label>
                    <input type="text" name="note" id="rem-note" placeholder="متابعة، إعادة فحص...">
                </div>
                <div class="doctor-add-reminder-submit">
                    <button type="submit" class="btn-primary">إضافة التذكير</button>
                </div>
            </div>
            <p class="doctor-smart-hint">💡 من صفحة المريض يُقترح تلقائياً تذكير للنتائج غير الطبيعية</p>
        </form>
    </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['doctor_msg'])): ?>
    <div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['doctor_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctor_msg']); ?></div>
    <?php endif; ?>

    <?php if (!empty($overdue)): ?>
    <section id="overdue" class="doctor-reminders-section">
        <h2 class="doctor-rem-section-title doctor-rem-overdue-title"><span class="doctor-rem-dot"></span> متأخرة (<?php echo count($overdue); ?>)</h2>
        <div class="doctor-reminders-cards">
            <?php foreach ($overdue as $r): $daysDiff = reminderDaysDiff($r['reminder_date']); ?>
            <div class="doctor-reminder-card doctor-reminder-overdue">
                <div class="doctor-reminder-card-header">
                    <a href="doctor.php?page=results&patient_id=<?php echo (int)$r['patient_id']; ?>" class="doctor-reminder-patient" data-patient-id="<?php echo (int)$r['patient_id']; ?>"><?php echo htmlspecialchars($r['patient_name'], ENT_QUOTES, 'UTF-8'); ?></a>
                    <span class="doctor-reminder-badge doctor-rem-days">متأخر <?php echo abs($daysDiff); ?> يوم</span>
                </div>
                <div class="doctor-reminder-date"><?php echo date('Y-m-d', strtotime($r['reminder_date'])); ?></div>
                <p class="doctor-reminder-note"><?php echo htmlspecialchars($r['note'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></p>
                <div class="doctor-reminder-actions">
                    <?php if (!empty($r['phone'])): ?><a href="tel:<?php echo htmlspecialchars(preg_replace('/[^0-9+]/', '', $r['phone']), ENT_QUOTES, 'UTF-8'); ?>" class="btn-secondary btn-sm" title="اتصال">📞</a><?php endif; ?>
                    <a href="doctor.php?page=results&patient_id=<?php echo (int)$r['patient_id']; ?>" class="btn-secondary btn-sm">عرض</a>
                    <a href="doctor.php?page=reminders&action=done&id=<?php echo (int)$r['id']; ?>" class="btn-primary btn-sm">✓ تم</a>
                    <button type="button" class="btn-secondary btn-sm" onclick="this.nextElementSibling.classList.toggle('show')">تعديل</button>
                    <div class="doctor-reminder-edit-form">
                        <form method="post" action="doctor.php?page=reminders&action=edit&id=<?php echo (int)$r['id']; ?>">
                            <input type="date" name="reminder_date" value="<?php echo date('Y-m-d', strtotime($r['reminder_date'])); ?>" required>
                            <input type="text" name="note" value="<?php echo htmlspecialchars($r['note'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="ملاحظة">
                            <button type="submit" class="btn-primary btn-sm">حفظ</button>
                        </form>
                    </div>
                    <a href="doctor.php?page=reminders&action=delete&id=<?php echo (int)$r['id']; ?>" onclick="return confirm('حذف التذكير؟');" class="doctor-reminder-delete">حذف</a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>

    <?php if (!empty($todayReminders)): ?>
    <section id="today" class="doctor-reminders-section">
        <h2 class="doctor-rem-section-title doctor-rem-today-title"><span class="doctor-rem-dot"></span> اليوم (<?php echo count($todayReminders); ?>)</h2>
        <div class="doctor-reminders-cards">
            <?php foreach ($todayReminders as $r): ?>
            <div class="doctor-reminder-card doctor-reminder-today">
                <div class="doctor-reminder-card-header">
                    <a href="doctor.php?page=results&patient_id=<?php echo (int)$r['patient_id']; ?>" class="doctor-reminder-patient" data-patient-id="<?php echo (int)$r['patient_id']; ?>"><?php echo htmlspecialchars($r['patient_name'], ENT_QUOTES, 'UTF-8'); ?></a>
                    <span class="doctor-reminder-badge">اليوم</span>
                </div>
                <p class="doctor-reminder-note"><?php echo htmlspecialchars($r['note'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></p>
                <div class="doctor-reminder-actions">
                    <?php if (!empty($r['phone'])): ?><a href="tel:<?php echo htmlspecialchars(preg_replace('/[^0-9+]/', '', $r['phone']), ENT_QUOTES, 'UTF-8'); ?>" class="btn-secondary btn-sm">📞</a><?php endif; ?>
                    <a href="doctor.php?page=reminders&action=done&id=<?php echo (int)$r['id']; ?>" class="btn-primary btn-sm">✓ تم</a>
                    <button type="button" class="btn-secondary btn-sm" onclick="this.nextElementSibling.classList.toggle('show')">تعديل</button>
                    <div class="doctor-reminder-edit-form">
                        <form method="post" action="doctor.php?page=reminders&action=edit&id=<?php echo (int)$r['id']; ?>">
                            <input type="date" name="reminder_date" value="<?php echo date('Y-m-d', strtotime($r['reminder_date'])); ?>" required>
                            <input type="text" name="note" value="<?php echo htmlspecialchars($r['note'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="ملاحظة">
                            <button type="submit" class="btn-primary btn-sm">حفظ</button>
                        </form>
                    </div>
                    <a href="doctor.php?page=reminders&action=delete&id=<?php echo (int)$r['id']; ?>" onclick="return confirm('حذف التذكير؟');" class="doctor-reminder-delete">حذف</a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>

    <?php if (!empty($thisWeekReminders)):
    $thisWeekSorted = $thisWeekReminders;
    usort($thisWeekSorted, fn($a,$b) => strcmp($a['reminder_date'], $b['reminder_date']));
    ?>
    <section id="week" class="doctor-reminders-section">
        <h2 class="doctor-rem-section-title doctor-rem-week-title"><span class="doctor-rem-dot"></span> هذا الأسبوع (<?php echo count($thisWeekReminders); ?>)</h2>
        <div class="doctor-reminders-cards">
            <?php foreach ($thisWeekSorted as $r): $daysDiff = reminderDaysDiff($r['reminder_date']); ?>
            <div class="doctor-reminder-card doctor-reminder-upcoming">
                <div class="doctor-reminder-card-header">
                    <a href="doctor.php?page=results&patient_id=<?php echo (int)$r['patient_id']; ?>" class="doctor-reminder-patient" data-patient-id="<?php echo (int)$r['patient_id']; ?>"><?php echo htmlspecialchars($r['patient_name'], ENT_QUOTES, 'UTF-8'); ?></a>
                    <span class="doctor-reminder-badge">خلال <?php echo $daysDiff; ?> يوم</span>
                </div>
                <div class="doctor-reminder-date"><?php echo date('Y-m-d', strtotime($r['reminder_date'])); ?></div>
                <p class="doctor-reminder-note"><?php echo htmlspecialchars($r['note'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></p>
                <div class="doctor-reminder-actions">
                    <?php if (!empty($r['phone'])): ?><a href="tel:<?php echo htmlspecialchars(preg_replace('/[^0-9+]/', '', $r['phone']), ENT_QUOTES, 'UTF-8'); ?>" class="btn-secondary btn-sm">📞</a><?php endif; ?>
                    <a href="doctor.php?page=reminders&action=done&id=<?php echo (int)$r['id']; ?>" class="btn-primary btn-sm">✓ تم</a>
                    <button type="button" class="btn-secondary btn-sm" onclick="this.nextElementSibling.classList.toggle('show')">تعديل</button>
                    <div class="doctor-reminder-edit-form">
                        <form method="post" action="doctor.php?page=reminders&action=edit&id=<?php echo (int)$r['id']; ?>">
                            <input type="date" name="reminder_date" value="<?php echo date('Y-m-d', strtotime($r['reminder_date'])); ?>" required>
                            <input type="text" name="note" value="<?php echo htmlspecialchars($r['note'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="ملاحظة">
                            <button type="submit" class="btn-primary btn-sm">حفظ</button>
                        </form>
                    </div>
                    <a href="doctor.php?page=reminders&action=delete&id=<?php echo (int)$r['id']; ?>" onclick="return confirm('حذف التذكير؟');" class="doctor-reminder-delete">حذف</a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>

    <?php
    $sundayThisWeek = strtotime('sunday this week');
    $laterReminders = array_filter($upcoming, fn($r) => $r['reminder_date'] !== $today && strtotime($r['reminder_date']) > $sundayThisWeek);
    if (!empty($laterReminders)):
    usort($laterReminders, fn($a,$b) => strcmp($a['reminder_date'], $b['reminder_date']));
    ?>
    <section class="doctor-reminders-section">
        <h2 class="doctor-rem-section-title"><span class="doctor-rem-dot"></span> لاحقاً (<?php echo count($laterReminders); ?>)</h2>
        <div class="doctor-reminders-cards">
            <?php foreach (array_slice($laterReminders, 0, 15) as $r): ?>
            <div class="doctor-reminder-card doctor-reminder-later">
                <div class="doctor-reminder-card-header">
                    <a href="doctor.php?page=results&patient_id=<?php echo (int)$r['patient_id']; ?>" class="doctor-reminder-patient" data-patient-id="<?php echo (int)$r['patient_id']; ?>"><?php echo htmlspecialchars($r['patient_name'], ENT_QUOTES, 'UTF-8'); ?></a>
                </div>
                <div class="doctor-reminder-date"><?php echo date('Y-m-d', strtotime($r['reminder_date'])); ?></div>
                <p class="doctor-reminder-note"><?php echo htmlspecialchars($r['note'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></p>
                <div class="doctor-reminder-actions">
                    <a href="doctor.php?page=reminders&action=done&id=<?php echo (int)$r['id']; ?>" class="btn-primary btn-sm">✓ تم</a>
                    <button type="button" class="btn-secondary btn-sm" onclick="this.nextElementSibling.classList.toggle('show')">تعديل</button>
                    <div class="doctor-reminder-edit-form">
                        <form method="post" action="doctor.php?page=reminders&action=edit&id=<?php echo (int)$r['id']; ?>">
                            <input type="date" name="reminder_date" value="<?php echo date('Y-m-d', strtotime($r['reminder_date'])); ?>" required>
                            <input type="text" name="note" value="<?php echo htmlspecialchars($r['note'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="ملاحظة">
                            <button type="submit" class="btn-primary btn-sm">حفظ</button>
                        </form>
                    </div>
                    <a href="doctor.php?page=reminders&action=delete&id=<?php echo (int)$r['id']; ?>" onclick="return confirm('حذف التذكير؟');" class="doctor-reminder-delete">حذف</a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>

    <?php if (!empty($done)): ?>
    <details class="doctor-reminders-done card">
        <summary class="doctor-rem-done-summary">✓ منفذة (<?php echo count($done); ?>)</summary>
        <div class="doctor-reminders-cards doctor-reminders-done-list">
            <?php foreach (array_slice($done, 0, 20) as $r): ?>
            <div class="doctor-reminder-card doctor-reminder-done">
                <a href="doctor.php?page=results&patient_id=<?php echo (int)$r['patient_id']; ?>"><?php echo htmlspecialchars($r['patient_name'], ENT_QUOTES, 'UTF-8'); ?></a>
                <span class="doctor-reminder-date"><?php echo date('Y-m-d', strtotime($r['reminder_date'])); ?></span>
                <span class="doctor-reminder-note"><?php echo htmlspecialchars($r['note'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></span>
            </div>
            <?php endforeach; ?>
        </div>
    </details>
    <?php endif; ?>

    <?php if (empty($overdue) && empty($upcoming)): ?>
    <div class="doctor-reminders-empty card">
        <div class="doctor-reminders-empty-icon">📅</div>
        <h3>لا توجد تذكيرات</h3>
        <p>أضف تذكيراً من النموذج أعلاه أو من صفحة المريض.</p>
        <a href="doctor.php?page=patients" class="btn-primary">عرض المرضى</a>
    </div>
    <?php endif; ?>
    </div>
</main>
<script>
(function(){
    var cal = document.getElementById('doctorRemindersCalendar');
    var listView = document.querySelector('.doctor-reminders-list-view');
    var d = new Date();
    var year = d.getFullYear(), month = d.getMonth() + 1;
    var monthNames = ['','يناير','فبراير','مارس','أبريل','مايو','يونيو','يوليو','أغسطس','سبتمبر','أكتوبر','نوفمبر','ديسمبر'];
    window.renderCal = function() {
        var el = document.getElementById('calMonthYear');
        if (el) el.textContent = monthNames[month] + ' ' + year;
        fetch('doctor_api.php?action=reminders_calendar&year=' + year + '&month=' + month)
            .then(function(r){ return r.json(); })
            .then(function(data){
                var byDate = data.by_date || {};
                var daysInMonth = new Date(year, month, 0).getDate();
                var firstDay = new Date(year, month - 1, 1).getDay();
                var html = '<div class="cal-weekday">أحد</div><div class="cal-weekday">إثن</div><div class="cal-weekday">ثلا</div><div class="cal-weekday">أرب</div><div class="cal-weekday">خمي</div><div class="cal-weekday">جمع</div><div class="cal-weekday">سبت</div>';
                for (var i = 0; i < (firstDay + 1) % 7; i++) html += '<div class="cal-day cal-empty"></div>';
                for (var d = 1; d <= daysInMonth; d++) {
                    var key = year + '-' + String(month).padStart(2,'0') + '-' + String(d).padStart(2,'0');
                    var cnt = byDate[key] || 0;
                    var cls = 'cal-day' + (cnt > 0 ? ' cal-has-reminder' : '');
                    html += '<div class="' + cls + '" title="' + (cnt > 0 ? cnt + ' تذكير' : '') + '">' + d + (cnt > 0 ? '<span class="cal-dot">' + cnt + '</span>' : '') + '</div>';
                }
                var grid = document.getElementById('calGrid');
                if (grid) grid.innerHTML = html;
            });
    };
    var prev = document.getElementById('calPrev');
    var next = document.getElementById('calNext');
    if (prev) prev.onclick = function(){ month--; if(month<1){month=12;year--;} renderCal(); };
    if (next) next.onclick = function(){ month++; if(month>12){month=1;year++;} renderCal(); };
    if (location.search.indexOf('view=calendar') >= 0 && listView && cal) {
        listView.style.display = 'none';
        cal.style.display = 'block';
        document.getElementById('reminderViewCal') && document.getElementById('reminderViewCal').classList.add('active');
        document.getElementById('reminderViewList') && document.getElementById('reminderViewList').classList.remove('active');
        renderCal();
    } else {
        document.getElementById('reminderViewList') && document.getElementById('reminderViewList').classList.add('active');
    }
})();

(function(){
    var search = document.getElementById('rem-patient-search');
    var select = document.getElementById('rem-patient');
    if (search && select) {
        search.addEventListener('input', function(){
            var q = this.value.trim().toLowerCase();
            var opts = select.querySelectorAll('option');
            opts.forEach(function(opt){
                var val = opt.value || '';
                var txt = (opt.getAttribute('data-search') ?? opt.textContent).toLowerCase();
                var isPlaceholder = val === '';
                if (isPlaceholder) {
                    opt.toggleAttribute('hidden', q !== '');
                } else if (q === '' || txt.indexOf(q) >= 0) {
                    opt.removeAttribute('hidden');
                } else {
                    opt.setAttribute('hidden', '');
                }
            });
        });
        search.addEventListener('keydown', function(e){
            if (e.key === 'Enter') e.preventDefault();
        });
    }
})();
</script>
</body>
</html>
