<?php
// admin/availability-export.php - خروجی اکسل و پرینت لیست زمان‌بندی

session_start();
require_once '../config/database.php';
require_once '../includes/db.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

if (!isLoggedIn()) {
    die('ابتدا وارد شوید.');
}

$user = getCurrentUser();
if (!in_array($user['role_level'], [1, 2, 3])) {
    die('دسترسی غیرمجاز.');
}

$teacher_id = isset($_GET['teacher_id']) ? (int)$_GET['teacher_id'] : 0;
$term_id = isset($_GET['term_id']) ? (int)$_GET['term_id'] : 0;
$print = isset($_GET['print']) ? (int)$_GET['print'] : 0;

// ===== دریافت داده‌ها =====
$whereConditions = ["1=1"];
$params = [];

if ($teacher_id > 0) {
    $whereConditions[] = "a.teacher_id = ?";
    $params[] = $teacher_id;
}

if ($term_id > 0) {
    $whereConditions[] = "a.term_id = ?";
    $params[] = $term_id;
}

$whereSQL = implode(' AND ', $whereConditions);

$data = fetchAll(
    "SELECT a.*, 
            u.name as teacher_name, u.family as teacher_family, u.national_code,
            t.name as term_name, t.code as term_code
     FROM teacher_availability a
     LEFT JOIN users u ON a.teacher_id = u.id
     LEFT JOIN terms t ON a.term_id = t.id
     WHERE $whereSQL
     ORDER BY u.family ASC, u.name ASC, a.day_of_week ASC, a.time_slot ASC",
    $params
);

$daysMap = [
    'saturday' => 'شنبه',
    'sunday' => 'یک‌شنبه',
    'monday' => 'دوشنبه',
    'tuesday' => 'سه‌شنبه',
    'wednesday' => 'چهارشنبه',
    'thursday' => 'پنج‌شنبه'
];

$slots = ['08-10', '10-12', '12-14', '14-16', '16-18', '18-20'];

// ===== گروه‌بندی =====
$grouped = [];
foreach ($data as $row) {
    $key = $row['teacher_id'] . '_' . $row['term_id'];
    if (!isset($grouped[$key])) {
        $grouped[$key] = [
            'teacher_name' => $row['teacher_name'],
            'teacher_family' => $row['teacher_family'],
            'national_code' => $row['national_code'],
            'term_name' => $row['term_name'],
            'term_code' => $row['term_code'],
            'slots' => []
        ];
    }
    $grouped[$key]['slots'][] = [
        'day' => $row['day_of_week'],
        'time' => $row['time_slot']
    ];
}

// ===== اگر حالت پرینت باشد =====
if ($print) {
    ?>
    <!DOCTYPE html>
    <html lang="fa" dir="rtl">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>لیست زمان‌بندی اساتید</title>
        <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;700;900&display=swap" rel="stylesheet">
        <style>
            * { font-family: 'Vazirmatn', sans-serif; margin: 0; padding: 0; box-sizing: border-box; }
            body { padding: 20px; background: white; }
            .header { text-align: center; padding-bottom: 20px; border-bottom: 3px solid #1a237e; margin-bottom: 20px; }
            .header h1 { font-size: 22px; color: #1a237e; }
            .header p { font-size: 14px; color: #666; margin-top: 4px; }
            table { width: 100%; border-collapse: collapse; font-size: 13px; }
            th { background: #1a237e; color: white; padding: 8px 10px; text-align: center; }
            td { padding: 6px 10px; border-bottom: 1px solid #e5e7eb; text-align: center; }
            .teacher-name { font-weight: 700; color: #1a237e; }
            .footer { text-align: center; font-size: 12px; color: #999; margin-top: 20px; padding-top: 10px; border-top: 1px solid #e5e7eb; }
            .slot-yes { color: #059669; font-weight: 700; }
            .slot-no { color: #d1d5db; }
            @media print {
                body { padding: 10px; }
                .no-print { display: none !important; }
            }
        </style>
    </head>
    <body>
        <div class="header">
            <h1>لیست زمان‌بندی تدریس اساتید</h1>
            <p>تاریخ چاپ: <?= jalaliDate(date('Y-m-d H:i:s')) ?></p>
            <?php if ($teacher_id > 0 && !empty($data)): ?>
                <p style="font-size:13px;color:#1a237e;">
                    استاد: <?= htmlspecialchars($data[0]['teacher_name'] . ' ' . $data[0]['teacher_family']) ?>
                </p>
            <?php endif; ?>
        </div>
        
        <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 $i = 1; foreach ($grouped as $key => $item): 
                    $daySlots = [];
                    foreach ($daysMap as $dayKey => $dayLabel) {
                        $daySlots[$dayKey] = [];
                        foreach ($item['slots'] as $slot) {
                            if ($slot['day'] == $dayKey) {
                                $daySlots[$dayKey][] = $slot['time'];
                            }
                        }
                    }
                ?>
                <tr>
                    <td><?= $i++ ?></td>
                    <td class="teacher-name"><?= htmlspecialchars($item['teacher_name'] . ' ' . $item['teacher_family']) ?></td>
                    <td><?= $item['national_code'] ?></td>
                    <td><?= htmlspecialchars($item['term_name']) ?></td>
                    <?php foreach ($daysMap as $dayKey => $dayLabel): ?>
                        <td>
                            <?php if (!empty($daySlots[$dayKey])): ?>
                                <?= implode(', ', $daySlots[$dayKey]) ?>
                            <?php else: ?>
                                <span class="slot-no">—</span>
                            <?php endif; ?>
                        </td>
                    <?php endforeach; ?>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <div class="footer">
            تمامی حقوق محفوظ است © <?= date('Y') ?>
        </div>
        
        <div class="no-print" style="text-align:center;margin-top:20px;">
            <button onclick="window.print()" style="padding:8px 24px;background:#1a237e;color:white;border:none;border-radius:8px;cursor:pointer;font-family:'Vazirmatn',sans-serif;font-size:14px;">
                <i class="fas fa-print"></i> چاپ
            </button>
            <button onclick="window.close()" style="padding:8px 24px;background:#6c757d;color:white;border:none;border-radius:8px;cursor:pointer;font-family:'Vazirmatn',sans-serif;font-size:14px;margin-right:8px;">
                <i class="fas fa-times"></i> بستن
            </button>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// ===== حالت اکسل =====
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="زمانبندی_اساتید_' . date('Ymd') . '.csv"');

$output = fopen('php://output', 'w');
fwrite($output, "\xEF\xBB\xBF");

// ===== هدر =====
fputcsv($output, ['ردیف', 'نام استاد', 'کد ملی', 'ترم', 'روز', 'سانس']);

// ===== داده‌ها =====
$i = 1;
foreach ($grouped as $item) {
    foreach ($item['slots'] as $slot) {
        fputcsv($output, [
            $i++,
            $item['teacher_name'] . ' ' . $item['teacher_family'],
            $item['national_code'],
            $item['term_name'],
            $daysMap[$slot['day']],
            $slot['time']
        ]);
    }
}

fclose($output);
exit;
?>