<?php
// admin/availability-review.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()) {
    header('Location: ../login.php');
    exit;
}

$user = getCurrentUser();
if (!in_array($user['role_level'], [1, 2, 3])) {
    header('Location: dashboard.php');
    exit;
}

$pageTitle = 'بررسی درخواست‌های زمان‌بندی';
$pageSubtitle = 'تأیید، رد یا درخواست اصلاح زمان‌های ثبت‌شده اساتید';

// ===== دریافت فیلترها =====
$statusFilter = isset($_GET['status']) ? $_GET['status'] : 'pending';
$termFilter = isset($_GET['term_id']) ? (int)$_GET['term_id'] : 0;
$teacherFilter = isset($_GET['teacher_id']) ? (int)$_GET['teacher_id'] : 0;

$whereConditions = ["1=1"];
$params = [];

if ($statusFilter != 'all') {
    $whereConditions[] = "a.status = ?";
    $params[] = $statusFilter;
}

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

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

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

// ===== دریافت لیست درخواست‌ها =====
$requests = 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,
            ti.field_of_study, ti.degree, ti.preferred_courses
     FROM teacher_availability a
     LEFT JOIN users u ON a.teacher_id = u.id
     LEFT JOIN terms t ON a.term_id = t.id
     LEFT JOIN teacher_info ti ON a.teacher_id = ti.teacher_id
     WHERE $whereSQL
     ORDER BY a.created_at DESC",
    $params
);

// ===== گروه‌بندی بر اساس استاد و ترم =====
$groupedRequests = [];
foreach ($requests as $req) {
    $key = $req['teacher_id'] . '_' . $req['term_id'];
    if (!isset($groupedRequests[$key])) {
        $groupedRequests[$key] = [
            'teacher_id' => $req['teacher_id'],
            'teacher_name' => $req['teacher_name'],
            'teacher_family' => $req['teacher_family'],
            'national_code' => $req['national_code'],
            'term_id' => $req['term_id'],
            'term_name' => $req['term_name'],
            'term_code' => $req['term_code'],
            'field_of_study' => $req['field_of_study'],
            'degree' => $req['degree'],
            'preferred_courses' => $req['preferred_courses'],
            'status' => $req['status'],
            'slots' => [],
            'review_comment' => $req['review_comment'],
            'reviewed_at' => $req['reviewed_at']
        ];
    }
    $groupedRequests[$key]['slots'][] = [
        'day_of_week' => $req['day_of_week'],
        'time_slot' => $req['time_slot'],
        'id' => $req['id'],
        'status' => $req['status']
    ];
}

// ===== دریافت لیست ترم‌ها و اساتید =====
$allTerms = getAllTerms();
$allTeachers = getAllTeachers();

// ===== پردازش فرم =====
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $teacher_id = isset($_POST['teacher_id']) ? (int)$_POST['teacher_id'] : 0;
    $term_id = isset($_POST['term_id']) ? (int)$_POST['term_id'] : 0;
    $comment = trim($_POST['comment'] ?? '');
    $slot_id = isset($_POST['slot_id']) ? (int)$_POST['slot_id'] : 0;
    
    if ($action == 'delete_slot' && $slot_id > 0) {
        $result = deleteData('teacher_availability', 'id = :id', ['id' => $slot_id]);
        if ($result !== false) {
            $message = '✅ سانس با موفقیت حذف شد.';
            $messageType = 'success';
        } else {
            $message = '❌ خطا در حذف سانس.';
            $messageType = 'danger';
        }
    } elseif ($action == 'delete_all' && $teacher_id > 0 && $term_id > 0) {
        $result = deleteData('teacher_availability', 'teacher_id = :teacher_id AND term_id = :term_id', [
            'teacher_id' => $teacher_id,
            'term_id' => $term_id
        ]);
        if ($result !== false) {
            $message = '✅ همه زمان‌های استاد با موفقیت حذف شد.';
            $messageType = 'success';
        } else {
            $message = '❌ خطا در حذف زمان‌ها.';
            $messageType = 'danger';
        }
    } elseif ($action == 'approve' && $teacher_id > 0 && $term_id > 0) {
        $result = updateData('teacher_availability', [
            'status' => 'approved',
            'reviewed_by' => $user['id'],
            'reviewed_at' => date('Y-m-d H:i:s'),
            'review_comment' => $comment
        ], 'teacher_id = :teacher_id AND term_id = :term_id', [
            'teacher_id' => $teacher_id,
            'term_id' => $term_id
        ]);
        if ($result !== false) {
            $message = '✅ زمان‌های استاد با موفقیت تأیید شد.';
            $messageType = 'success';
        } else {
            $message = '❌ خطا در تأیید زمان‌ها.';
            $messageType = 'danger';
        }
    } elseif ($action == 'reject' && $teacher_id > 0 && $term_id > 0) {
        $result = updateData('teacher_availability', [
            'status' => 'rejected',
            'reviewed_by' => $user['id'],
            'reviewed_at' => date('Y-m-d H:i:s'),
            'review_comment' => $comment
        ], 'teacher_id = :teacher_id AND term_id = :term_id', [
            'teacher_id' => $teacher_id,
            'term_id' => $term_id
        ]);
        if ($result !== false) {
            $message = '❌ زمان‌های استاد رد شد.';
            $messageType = 'success';
        } else {
            $message = '❌ خطا در رد زمان‌ها.';
            $messageType = 'danger';
        }
    } elseif ($action == 'needs_revision' && $teacher_id > 0 && $term_id > 0) {
        $result = updateData('teacher_availability', [
            'status' => 'needs_revision',
            'reviewed_by' => $user['id'],
            'reviewed_at' => date('Y-m-d H:i:s'),
            'review_comment' => $comment
        ], 'teacher_id = :teacher_id AND term_id = :term_id', [
            'teacher_id' => $teacher_id,
            'term_id' => $term_id
        ]);
        if ($result !== false) {
            $message = '✏️ درخواست اصلاح زمان‌ها برای استاد ارسال شد.';
            $messageType = 'success';
        } else {
            $message = '❌ خطا در ثبت درخواست اصلاح.';
            $messageType = 'danger';
        }
    }
    
    // ===== به‌روزرسانی لیست =====
    $requests = 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,
                ti.field_of_study, ti.degree, ti.preferred_courses
         FROM teacher_availability a
         LEFT JOIN users u ON a.teacher_id = u.id
         LEFT JOIN terms t ON a.term_id = t.id
         LEFT JOIN teacher_info ti ON a.teacher_id = ti.teacher_id
         WHERE $whereSQL
         ORDER BY a.created_at DESC",
        $params
    );
    
    $groupedRequests = [];
    foreach ($requests as $req) {
        $key = $req['teacher_id'] . '_' . $req['term_id'];
        if (!isset($groupedRequests[$key])) {
            $groupedRequests[$key] = [
                'teacher_id' => $req['teacher_id'],
                'teacher_name' => $req['teacher_name'],
                'teacher_family' => $req['teacher_family'],
                'national_code' => $req['national_code'],
                'term_id' => $req['term_id'],
                'term_name' => $req['term_name'],
                'term_code' => $req['term_code'],
                'field_of_study' => $req['field_of_study'],
                'degree' => $req['degree'],
                'preferred_courses' => $req['preferred_courses'],
                'status' => $req['status'],
                'slots' => [],
                'review_comment' => $req['review_comment'],
                'reviewed_at' => $req['reviewed_at']
            ];
        }
        $groupedRequests[$key]['slots'][] = [
            'day_of_week' => $req['day_of_week'],
            'time_slot' => $req['time_slot'],
            'id' => $req['id'],
            'status' => $req['status']
        ];
    }
}

$content = 'availability-review-content.php';
require_once '../includes/layout.php';
?>