<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../config/database.php';
require_once '../includes/functions.php';

if (!isset($_SESSION['user_level']) || $_SESSION['user_level'] != 'expert') {
    header('Location: ../index.php');
    exit;
}

$expertId = $_SESSION['user_id'];

// ========== دریافت لیست دانشجویان در انتظار پیگیری ==========
$pendingQuery = "SELECT m.*, 
                        e.name as education_name, 
                        c.name as course_name,
                        r.name as referral_name,
                        u.fullname as created_by_name,
                        rep.fullname as representative_name
                 FROM members m 
                 LEFT JOIN educations e ON m.education_id = e.id 
                 LEFT JOIN courses c ON m.course_id = c.id
                 LEFT JOIN referrals r ON m.referral_id = r.id 
                 LEFT JOIN users u ON m.created_by = u.id
                 LEFT JOIN users rep ON m.representative_id = rep.id
                 WHERE (m.created_by = ? OR m.representative_id IN (SELECT id FROM users WHERE level = 'representative'))
                 AND m.registration_status IN ('تماس گرفته نشده', 'در انتظار پاسخ', 'عدم پاسخ گویی')
                 AND m.status = 'active'
                 ORDER BY m.created_at DESC";

$pendingStmt = $pdo->prepare($pendingQuery);
$pendingStmt->execute([$expertId]);
$pendingMembers = $pendingStmt->fetchAll();

$totalPending = count($pendingMembers);

$statusStats = [];
foreach ($pendingMembers as $member) {
    $status = $member['registration_status'];
    $statusStats[$status] = ($statusStats[$status] ?? 0) + 1;
}

$representativesQuery = "SELECT u.id, u.fullname, COUNT(m.id) as student_count
                         FROM users u
                         LEFT JOIN members m ON m.representative_id = u.id AND m.status = 'active'
                         WHERE u.level = 'representative'
                         GROUP BY u.id";
$representatives = $pdo->query($representativesQuery)->fetchAll();
?>
<?php include '../includes/header.php'; ?>

<div class="row mb-4">
    <div class="col-md-12">
        <h4 class="fw-bold">📋 داشبورد پیگیری</h4>
        <p class="text-muted">دانشجویانی که نیاز به پیگیری دارند</p>
    </div>
</div>

<!-- ===== آمار ===== -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="dashboard-card">
            <h3><?php echo toPersianNumbers($totalPending); ?></h3>
            <div class="label">کل دانشجویان در انتظار پیگیری</div>
        </div>
    </div>
    <?php foreach ($statusStats as $status => $count): ?>
        <div class="col-md-3">
            <div class="dashboard-card">
                <h3><?php echo toPersianNumbers($count); ?></h3>
                <div class="label"><?php echo $status; ?></div>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<!-- ===== فیلترها ===== -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row">
            <div class="col-md-3">
                <select name="status_filter" class="form-select">
                    <option value="">همه وضعیت‌ها</option>
                    <?php foreach (getContactStatusOptions() as $option): ?>
                        <option value="<?php echo $option; ?>"><?php echo $option; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <select name="representative_filter" class="form-select">
                    <option value="">همه معرف‌کنندگان</option>
                    <?php foreach ($representatives as $rep): ?>
                        <option value="<?php echo $rep['id']; ?>"><?php echo htmlspecialchars($rep['fullname']) . ' (' . toPersianNumbers($rep['student_count']) . ' نفر)'; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <input type="text" name="search" class="form-control" placeholder="جستجوی نام..." value="<?php echo $_GET['search'] ?? ''; ?>">
            </div>
            <div class="col-md-3">
                <button type="submit" class="btn btn-pastel w-100">🔍 فیلتر</button>
            </div>
        </form>
    </div>
</div>

<!-- ===== جدول ===== -->
<div class="card">
    <div class="card-header">
        <i class="bi bi-list-check"></i> لیست دانشجویان در انتظار پیگیری
        <span class="badge bg-primary ms-2"><?php echo toPersianNumbers($totalPending); ?></span>
    </div>
    <div class="card-body">
        <?php if (count($pendingMembers) > 0): ?>
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>نام</th>
                            <th>کد ملی</th>
                            <th>مقطع</th>
                            <th>رشته</th>
                            <th>معرف</th>
                            <th>معرف‌کننده</th>
                            <th>وضعیت تماس</th>
                            <th>تاریخ ثبت</th>
                            <th>عملیات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $counter = 1; ?>
                        <?php foreach ($pendingMembers as $row): ?>
                        <tr>
                            <td><?php echo toPersianNumbers($counter++); ?></td>
                            <td><?php echo htmlspecialchars($row['fullname']); ?></td>
                            <td><?php echo toPersianNumbers($row['national_code']); ?></td>
                            <td><?php echo htmlspecialchars($row['education_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['course_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['referral_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['representative_name'] ?? '-'); ?></td>
                            <td>
                                <span class="badge bg-<?php echo getContactStatusColor($row['registration_status']); ?>">
                                    <?php echo htmlspecialchars($row['registration_status']); ?>
                                </span>
                            </td>
                            <td><?php echo convertToPersianDateFa($row['created_at']); ?></td>
                            <td>
                                <a href="/portal/admin/edit_member.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-primary">
                                    <i class="bi bi-pencil"></i> پیگیری
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="text-center py-4">
                <i class="bi bi-check-circle-fill text-success" style="font-size: 3rem;"></i>
                <p class="mt-2">همه دانشجویان پیگیری شده‌اند!</p>
            </div>
        <?php endif; ?>
    </div>
</div>

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