<?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'] != 'representative') {
    header('Location: ../index.php');
    exit;
}

$repId = $_SESSION['user_id'];

// ========== دریافت لیست دانشجویان معرفی شده ==========
$membersQuery = "SELECT m.*, 
                        e.name as education_name, 
                        c.name as course_name,
                        r.name as referral_name,
                        u.fullname as created_by_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
                 WHERE m.representative_id = ?
                 ORDER BY m.created_at DESC";

$membersStmt = $pdo->prepare($membersQuery);
$membersStmt->execute([$repId]);
$members = $membersStmt->fetchAll();

$totalMembers = count($members);

// ========== آمار مقاطع ==========
$educationStats = $pdo->query("
    SELECT e.name, COUNT(m.id) as count 
    FROM members m 
    LEFT JOIN educations e ON m.education_id = e.id 
    WHERE m.representative_id = $repId
    GROUP BY m.education_id
")->fetchAll();

// ========== آمار رشته‌ها ==========
$fieldStats = $pdo->query("
    SELECT c.name, COUNT(m.id) as count 
    FROM members m 
    LEFT JOIN courses c ON m.course_id = c.id 
    WHERE m.representative_id = $repId AND m.course_id IS NOT NULL
    GROUP BY m.course_id
    ORDER BY count DESC
")->fetchAll();

// ========== آمار وضعیت تماس ==========
$statusStats = $pdo->query("
    SELECT registration_status, COUNT(*) as count 
    FROM members 
    WHERE representative_id = $repId
    GROUP BY registration_status
")->fetchAll(PDO::FETCH_KEY_PAIR);

// ========== آمار وضعیت مدارک ==========
$documentStatusStats = $pdo->query("
    SELECT document_status, COUNT(*) as count 
    FROM members 
    WHERE representative_id = $repId
    GROUP BY document_status
")->fetchAll(PDO::FETCH_KEY_PAIR);

// ========== پرینت ==========
if (isset($_GET['export']) && $_GET['export'] == 'print') {
    ?>
    <!DOCTYPE html>
    <html dir="rtl">
    <head>
        <meta charset="UTF-8">
        <title>پرینت لیست دانشجویان</title>
        <style>
            body { font-family: 'Vazir', 'Tahoma', sans-serif; padding: 20px; }
            table { width: 100%; border-collapse: collapse; }
            th { background: #4f46e5; color: white; padding: 8px; }
            td { padding: 6px; border: 1px solid #ddd; }
            .header { text-align: center; margin-bottom: 20px; }
            .footer { text-align: center; margin-top: 20px; font-size: 12px; color: #888; }
        </style>
    </head>
    <body>
        <div class="header">
            <h2>📊 گزارش دانشجویان معرفی شده</h2>
            <p>نام معرف‌کننده: <?php echo htmlspecialchars($_SESSION['user_name']); ?></p>
            <p>تاریخ چاپ: <?php echo getCurrentPersianDateTimeFa(); ?></p>
        </div>
        <table>
            <thead><tr><th>#</th><th>نام</th><th>کد ملی</th><th>مقطع</th><th>رشته</th><th>وضعیت تماس</th><th>وضعیت مدارک</th><th>تاریخ ثبت</th></tr></thead>
            <tbody>
                <?php $counter = 1; foreach ($members 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['registration_status']); ?></td>
                    <td><?php echo htmlspecialchars($row['document_status']); ?></td>
                    <td><?php echo convertToPersianDateFa($row['created_at']); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <div class="footer">تعداد کل: <?php echo toPersianNumbers(count($members)); ?> نفر</div>
        <div style="text-align:center; margin-top:20px;">
            <button onclick="window.print()" style="padding:10px 30px; background:#4f46e5; color:white; border:none; border-radius:5px; cursor:pointer;">🖨️ پرینت</button>
            <button onclick="window.close()" style="padding:10px 30px; background:#dc3545; color:white; border:none; border-radius:5px; cursor:pointer;">❌ بستن</button>
        </div>
    </body>
    </html>
    <?php
    exit;
}
?>
<?php include '../includes/header.php'; ?>

<div class="row mb-4">
    <div class="col-md-12">
        <h4 class="fw-bold">📊 داشبورد من</h4>
        <p class="text-muted"><?php echo htmlspecialchars($_SESSION['user_name']); ?> عزیز، خوش آمدید!</p>
    </div>
</div>

<!-- ===== آمار ===== -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="dashboard-card">
            <h3><?php echo toPersianNumbers($totalMembers); ?></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="row mb-4">
    <div class="col-md-6">
        <div class="card"><div class="card-header">📚 تفکیک مقاطع تحصیلی</div>
            <div class="card-body"><table class="table table-sm"><?php foreach ($educationStats as $row): ?><tr><td><?php echo htmlspecialchars($row['name'] ?? 'نامشخص'); ?></td><td><span class="badge bg-primary"><?php echo toPersianNumbers($row['count']); ?></span></td></tr><?php endforeach; ?></table></div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card"><div class="card-header">🎓 تفکیک رشته‌های تحصیلی</div>
            <div class="card-body"><table class="table table-sm"><?php foreach ($fieldStats as $row): ?><tr><td><?php echo htmlspecialchars($row['name'] ?? 'نامشخص'); ?></td><td><span class="badge bg-success"><?php echo toPersianNumbers($row['count']); ?></span></td></tr><?php endforeach; ?></table></div>
        </div>
    </div>
</div>

<!-- ===== لیست دانشجویان ===== -->
<div class="card">
    <div class="card-header">
        <i class="bi bi-people"></i> لیست دانشجویان معرفی شده
        <a href="?export=print" class="btn btn-sm btn-info float-start" target="_blank"><i class="bi bi-printer"></i> پرینت</a>
    </div>
    <div class="card-body">
        <?php if (count($members) > 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></tr></thead>
                    <tbody>
                        <?php $counter = 1; foreach ($members 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><span class="badge bg-<?php echo getContactStatusColor($row['registration_status']); ?>"><?php echo htmlspecialchars($row['registration_status']); ?></span></td>
                            <td><span class="badge bg-<?php echo getDocumentStatusColor($row['document_status']); ?>"><?php echo htmlspecialchars($row['document_status']); ?></span></td>
                            <td><?php echo convertToPersianDateFa($row['created_at']); ?></td>
                            <td>
                                <?php if ($row['document_status'] != 'تایید شده'): ?>
                                    <a href="/portal/admin/edit_member.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-warning"><i class="bi bi-pencil"></i> ویرایش</a>
                                <?php else: ?>
                                    <span class="badge bg-success">تکمیل شده</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="text-center py-4"><i class="bi bi-inbox" style="font-size: 3rem; color: #ccc;"></i><p class="mt-2">هیچ دانشجویی توسط شما معرفی نشده است.</p></div>
        <?php endif; ?>
    </div>
</div>

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