<?php
// teacher/certificate-request.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 ($user['role_level'] != 6) {
    header('Location: ../admin/dashboard.php');
    exit;
}

$pageTitle = 'درخواست گواهی تدریس';
$pageSubtitle = 'ثبت درخواست گواهی تدریس برای ترم‌های مورد نظر';

$teacherTerms = fetchAll(
    "SELECT DISTINCT t.id, t.name, t.code 
     FROM courses c
     LEFT JOIN terms t ON c.term_id = t.id
     WHERE c.teacher_id = ? AND t.id IS NOT NULL
     ORDER BY t.id DESC",
    [$user['id']]
);

$requests = fetchAll(
    "SELECT r.*, t.name as term_name, t.code as term_code,
            u.name as approver_name, u.family as approver_family
     FROM certificate_requests r
     LEFT JOIN terms t ON r.term_id = t.id
     LEFT JOIN users u ON r.approved_by = u.id
     WHERE r.teacher_id = ?
     ORDER BY r.id DESC",
    [$user['id']]
);

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action == 'request') {
        $title = trim($_POST['title'] ?? '');
        $term_ids = $_POST['term_ids'] ?? [];
        
        if (empty($title)) {
            $message = '❌ لطفاً عنوان گواهی را وارد کنید.';
            $messageType = 'danger';
        } elseif (empty($term_ids)) {
            $message = '❌ لطفاً حداقل یک ترم را انتخاب کنید.';
            $messageType = 'danger';
        } else {
            $success = true;
            $errorMsg = '';
            
            foreach ($term_ids as $term_id) {
                $existing = fetchOne(
                    "SELECT id FROM certificate_requests 
                     WHERE teacher_id = ? AND term_id = ? AND status != 'rejected'",
                    [$user['id'], (int)$term_id]
                );
                
                if ($existing) {
                    $termName = fetchOne("SELECT name FROM terms WHERE id = ?", [(int)$term_id]);
                    $errorMsg .= 'ترم ' . ($termName['name'] ?? '') . ' قبلاً درخواست شده است. ';
                    continue;
                }
                
                $data = [
                    'teacher_id' => $user['id'],
                    'term_id' => (int)$term_id,
                    'title' => $title,
                    'status' => 'pending'
                ];
                $result = insertData('certificate_requests', $data);
                if (!$result) {
                    $success = false;
                }
            }
            
            if ($success && empty($errorMsg)) {
                $message = '✅ درخواست گواهی با موفقیت ثبت شد. منتظر تأیید مدیر باشید.';
                $messageType = 'success';
                $requests = fetchAll(
                    "SELECT r.*, t.name as term_name, t.code as term_code,
                            u.name as approver_name, u.family as approver_family
                     FROM certificate_requests r
                     LEFT JOIN terms t ON r.term_id = t.id
                     LEFT JOIN users u ON r.approved_by = u.id
                     WHERE r.teacher_id = ?
                     ORDER BY r.id DESC",
                    [$user['id']]
                );
            } elseif (!empty($errorMsg)) {
                $message = '⚠️ ' . $errorMsg;
                $messageType = 'warning';
            } else {
                $message = '❌ خطا در ثبت درخواست. لطفاً دوباره تلاش کنید.';
                $messageType = 'danger';
            }
        }
    }
}

$content = 'certificate-request-content.php';
require_once '../includes/layout.php';
?>