<?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'] != 'admin' && $_SESSION['user_level'] != 'expert' && $_SESSION['user_level'] != 'reporter')) {
    header('Location: ../index.php');
    exit;
}

$search_name = $_GET['search_name'] ?? '';
$search_national = $_GET['search_national'] ?? '';
$search_field = $_GET['search_field'] ?? '';
$search_education = $_GET['search_education'] ?? '';
$search_gender = $_GET['search_gender'] ?? '';
$search_registration_status = $_GET['search_registration_status'] ?? '';
$search_payment = $_GET['search_payment'] ?? '';
$search_from_date = $_GET['from_date'] ?? '';
$search_to_date = $_GET['to_date'] ?? '';
$status_filter = $_GET['status_filter'] ?? '';
$show_deleted = $_GET['show_deleted'] ?? '0';
$export_type = $_GET['export'] ?? '';

// ========== ساخت کوئری ==========
$query = "SELECT m.*, e.name as education_name, r.name as referral_name, u.fullname as created_by_name, sf.name as study_field_name, rep.fullname as representative_name
          FROM members m 
          LEFT JOIN educations e ON m.education_id = e.id 
          LEFT JOIN study_fields sf ON m.study_field_id = sf.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 1=1";

$params = [];

// نمایش بر اساس نقش کاربر
if ($_SESSION['user_level'] == 'representative') {
    $query .= " AND m.representative_id = ?";
    $params[] = $_SESSION['user_id'];
}

// فیلتر وضعیت کلی
if (!empty($status_filter)) {
    $query .= " AND m.status = ?";
    $params[] = $status_filter;
}

// نمایش حذف شده‌ها
if ($show_deleted == '1') {
    $query .= " AND m.status = 'withdrawn'";
} else {
    $query .= " AND (m.status = 'active' OR m.status = 'completed')";
}

// جستجوها
if (!empty($search_name)) {
    $query .= " AND m.fullname LIKE ?";
    $params[] = "%$search_name%";
}
if (!empty($search_national)) {
    $query .= " AND m.national_code = ?";
    $params[] = $search_national;
}
if (!empty($search_field)) {
    $query .= " AND sf.name LIKE ?";
    $params[] = "%$search_field%";
}
if (!empty($search_education)) {
    $query .= " AND e.id = ?";
    $params[] = $search_education;
}
if (!empty($search_gender)) {
    $query .= " AND m.gender = ?";
    $params[] = $search_gender;
}
if (!empty($search_registration_status)) {
    $query .= " AND m.registration_status = ?";
    $params[] = $search_registration_status;
}
if (!empty($search_payment)) {
    $query .= " AND m.payment_status = ?";
    $params[] = $search_payment;
}
if (!empty($search_from_date)) {
    $query .= " AND DATE(m.created_at) >= ?";
    $params[] = $search_from_date;
}
if (!empty($search_to_date)) {
    $query .= " AND DATE(m.created_at) <= ?";
    $params[] = $search_to_date;
}

$query .= " ORDER BY m.created_at DESC";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$members = $stmt->fetchAll();

// دریافت لیست‌ها برای فیلتر
$educations = $pdo->query("SELECT * FROM educations ORDER BY sort_order")->fetchAll();
$statusOptions = ['active' => 'فعال', 'completed' => 'تکمیل شده', 'withdrawn' => 'انصرافی'];
$registrationStatusOptions = getRegistrationStatusOptions();
$paymentStatusOptions = getPaymentStatusOptions();

// ========== پرینت ==========
if ($export_type == '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; }
            @media print { body { padding: 10px; } }
        </style>
    </head>
    <body>
        <div class="header">
            <h2>📊 گزارش لیست دانشجویان</h2>
            <p>تاریخ چاپ: <?php echo getCurrentPersianDateTime(); ?></p>
        </div>
        <table>
            <thead>
                <tr>
                    <th>#</th><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 ($members as $row): ?>
                <tr>
                    <td><?php echo $counter++; ?></td>
                    <td><?php echo htmlspecialchars($row['fullname']); ?></td>
                    <td><?php echo htmlspecialchars($row['national_code']); ?></td>
                    <td><?php echo htmlspecialchars($row['education_name']); ?></td>
                    <td><?php echo htmlspecialchars($row['study_field_name']); ?></td>
                    <td><?php echo htmlspecialchars($row['gender']); ?></td>
                    <td><?php echo getStatusLabel($row['status']); ?></td>
                    <td><?php echo htmlspecialchars($row['payment_status']); ?></td>
                    <td><?php echo htmlspecialchars($row['registration_status']); ?></td>
                    <td><?php echo htmlspecialchars($row['referral_name']); ?></td>
                    <td><?php echo convertToPersianDate($row['created_at']); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <div class="footer">تعداد کل: <?php echo 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'; ?>

<style>
.report-filters { background: #f8fafc; padding: 20px; border-radius: 12px; margin-bottom: 20px; border: 1px solid #e9edf2; }
</style>

<div class="card">
    <div class="card-header">
        <i class="bi bi-file-earmark-text"></i> 📊 گزارشات
    </div>
    <div class="card-body">
        <!-- فیلترها -->
        <div class="report-filters">
            <h6 class="fw-bold mb-3">🔍 فیلترهای جستجو</h6>
            <form method="GET" class="row">
                <div class="col-md-3 mb-2">
                    <input type="text" name="search_name" class="form-control" placeholder="نام" value="<?php echo htmlspecialchars($search_name); ?>">
                </div>
                <div class="col-md-2 mb-2">
                    <input type="text" name="search_national" class="form-control" placeholder="کد ملی" value="<?php echo htmlspecialchars($search_national); ?>">
                </div>
                <div class="col-md-2 mb-2">
                    <input type="text" name="search_field" class="form-control" placeholder="رشته" value="<?php echo htmlspecialchars($search_field); ?>">
                </div>
                <div class="col-md-2 mb-2">
                    <select name="search_education" class="form-select">
                        <option value="">همه مقاطع</option>
                        <?php foreach ($educations as $edu): ?>
                            <option value="<?php echo $edu['id']; ?>" <?php echo ($search_education == $edu['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($edu['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3 mb-2">
                    <select name="search_gender" class="form-select">
                        <option value="">همه جنسیت‌ها</option>
                        <option value="مرد" <?php echo ($search_gender == 'مرد') ? 'selected' : ''; ?>>مرد</option>
                        <option value="زن" <?php echo ($search_gender == 'زن') ? 'selected' : ''; ?>>زن</option>
                    </select>
                </div>
                <div class="col-md-3 mb-2">
                    <select name="status_filter" class="form-select">
                        <option value="">همه وضعیت‌های کلی</option>
                        <?php foreach ($statusOptions as $key => $label): ?>
                            <option value="<?php echo $key; ?>" <?php echo ($status_filter == $key) ? 'selected' : ''; ?>>
                                <?php echo $label; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3 mb-2">
                    <select name="search_payment" class="form-select">
                        <option value="">همه وضعیت‌های پرداخت</option>
                        <?php foreach ($paymentStatusOptions as $option): ?>
                            <option value="<?php echo $option; ?>" <?php echo ($search_payment == $option) ? 'selected' : ''; ?>>
                                <?php echo $option; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3 mb-2">
                    <select name="search_registration_status" class="form-select">
                        <option value="">همه وضعیت‌های ثبت‌نام</option>
                        <?php foreach ($registrationStatusOptions as $option): ?>
                            <option value="<?php echo $option; ?>" <?php echo ($search_registration_status == $option) ? 'selected' : ''; ?>>
                                <?php echo $option; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2 mb-2">
                    <input type="text" name="from_date" class="form-control" placeholder="از تاریخ" value="<?php echo htmlspecialchars($search_from_date); ?>">
                </div>
                <div class="col-md-2 mb-2">
                    <input type="text" name="to_date" class="form-control" placeholder="تا تاریخ" value="<?php echo htmlspecialchars($search_to_date); ?>">
                </div>
                <div class="col-md-2 mb-2">
                    <button type="submit" class="btn btn-pastel w-100">🔍 فیلتر</button>
                </div>
            </form>
            
            <div class="row mt-3">
                <div class="col-md-12">
                    <a href="?show_deleted=0" class="btn btn-sm <?php echo ($show_deleted == '0') ? 'btn-primary' : 'btn-outline-secondary'; ?>">✅ کاربران فعال</a>
                    <a href="?show_deleted=1" class="btn btn-sm <?php echo ($show_deleted == '1') ? 'btn-danger' : 'btn-outline-secondary'; ?>">🗑️ کاربران انصرافی</a>
                    <span class="badge bg-primary float-end mt-2">تعداد کل: <?php echo count($members); ?> نفر</span>
                </div>
            </div>
        </div>
        
        <!-- دکمه‌های عملیات -->
        <div class="row mb-3">
            <div class="col-md-12">
                <a href="?export=print&<?php echo http_build_query($_GET); ?>" class="btn btn-info" target="_blank"><i class="bi bi-printer"></i> پرینت</a>
                <a href="export_excel.php<?php echo !empty($_GET) ? '?' . http_build_query($_GET) : ''; ?>" class="btn btn-success"><i class="bi bi-file-earmark-excel"></i> خروجی اکسل</a>
                <a href="reports.php" class="btn btn-secondary"><i class="bi bi-arrow-counterclockwise"></i> نمایش همه</a>
            </div>
        </div>
        
        <!-- جدول نتایج -->
        <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>
                        <th>معرف‌کننده</th>
                        <th>ثبت‌کننده</th>
                        <th>تاریخ ثبت</th>
                        <th>عملیات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($members) > 0): ?>
                        <?php $counter = 1; ?>
                        <?php foreach ($members as $row): ?>
                        <tr class="<?php echo ($row['status'] == 'withdrawn') ? 'table-danger' : ''; ?>">
                            <td><?php echo $counter++; ?></td>
                            <td>
                                <?php echo htmlspecialchars($row['fullname']); ?>
                                <?php if ($row['status'] == 'withdrawn'): ?>
                                    <span class="badge bg-danger">انصرافی</span>
                                <?php endif; ?>
                                <?php if ($row['registration_status'] == 'تایید شده'): ?>
                                    <span class="badge bg-success">تأیید شده</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($row['national_code']); ?></td>
                            <td><?php echo htmlspecialchars($row['education_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['study_field_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['gender']); ?></td>
                            <td>
                                <span class="badge bg-<?php echo getStatusColor($row['status']); ?>">
                                    <?php echo getStatusLabel($row['status']); ?>
                                </span>
                            </td>
                            <td>
                                <span class="badge bg-<?php echo $row['payment_status'] == 'پرداخت شده' ? 'success' : ($row['payment_status'] == 'پرداخت نشده' ? 'danger' : ($row['payment_status'] == 'عودت وجه' ? 'warning' : 'info')); ?>">
                                    <?php echo htmlspecialchars($row['payment_status']); ?>
                                </span>
                            </td>
                            <td>
                                <span class="badge bg-<?php echo getRegistrationStatusColor($row['registration_status']); ?>">
                                    <?php echo htmlspecialchars($row['registration_status']); ?>
                                </span>
                            </td>
                            <td><?php echo htmlspecialchars($row['referral_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['representative_name'] ?? '-'); ?></td>
                            <td><?php echo htmlspecialchars($row['created_by_name']); ?></td>
                            <td><?php echo convertToPersianDate($row['created_at']); ?></td>
                            <td>
                                <?php if ($row['status'] == 'withdrawn'): ?>
                                    <a href="restore_member.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-success" onclick="return confirm('آیا از بازیابی این کاربر مطمئن هستید؟')">↩️ بازیابی</a>
                                <?php else: ?>
                                    <a href="edit_member.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-primary"><i class="bi bi-pencil"></i> ویرایش</a>
                                    <?php if ($_SESSION['user_level'] == 'admin'): ?>
                                        <a href="delete_member.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('آیا از انتقال این کاربر به بایگانی مطمئن هستید؟')">🗑️ حذف</a>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="14" class="text-center py-4">هیچ رکوردی یافت نشد</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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