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

// ========== دریافت فیلترها از URL ==========
$search_name = $_GET['search_name'] ?? '';
$search_field = $_GET['search_field'] ?? '';
$search_status = $_GET['search_status'] ?? '';
$search_education = $_GET['search_education'] ?? '';
$search_gender = $_GET['search_gender'] ?? '';
$search_from_date = $_GET['from_date'] ?? '';
$search_to_date = $_GET['to_date'] ?? '';
$search_contact_status = $_GET['search_contact_status'] ?? '';
$search_document_status = $_GET['search_document_status'] ?? '';
$search_payment = $_GET['search_payment'] ?? '';

// ========== ساخت کوئری با فیلترها ==========
$query = "SELECT m.*, e.name as education_name, r.name as referral_name, c.name as course_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 
          WHERE 1=1";

$params = [];

if (!empty($search_name)) {
    $query .= " AND m.fullname LIKE ?";
    $params[] = "%$search_name%";
}
if (!empty($search_field)) {
    $query .= " AND c.name LIKE ?";
    $params[] = "%$search_field%";
}
if (!empty($search_status)) {
    $query .= " AND m.registration_status = ?";
    $params[] = $search_status;
}
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_contact_status)) {
    $query .= " AND m.registration_status = ?";
    $params[] = $search_contact_status;
}
if (!empty($search_document_status)) {
    $query .= " AND m.document_status = ?";
    $params[] = $search_document_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();

// ========== تنظیم هدرها برای خروجی CSV ==========
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=گزارش_' . jdate('Y_n_j') . '.csv');

$output = fopen('php://output', 'w');
fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

fputcsv($output, ['ردیف', 'نام', 'شماره تماس', 'کد ملی', 'مقطع تحصیلی', 'رشته تحصیلی', 'جنسیت', 'وضعیت تماس', 'وضعیت مدارک', 'وضعیت پرداخت', 'معرف', 'تاریخ ثبت']);

$counter = 1;
foreach($members as $row) {
    fputcsv($output, [
        $counter++,
        $row['fullname'],
        $row['phone'],
        $row['national_code'],
        $row['education_name'],
        $row['course_name'],
        $row['gender'],
        $row['registration_status'],
        $row['document_status'],
        $row['payment_status'],
        $row['referral_name'],
        convertToPersianDate($row['created_at'])
    ]);
}
fclose($output);
exit;
?>