<?php
// admin/certificate-requests.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 = 'بررسی و تأیید درخواست‌های گواهی تدریس اساتید';

// ===== دریافت همه درخواست‌ها =====
$requests = fetchAll(
    "SELECT r.*, 
            u.name as teacher_name, u.family as teacher_family, u.national_code,
            t.name as term_name, t.code as term_code,
            a.name as approver_name, a.family as approver_family
     FROM certificate_requests r
     LEFT JOIN users u ON r.teacher_id = u.id
     LEFT JOIN terms t ON r.term_id = t.id
     LEFT JOIN users a ON r.approved_by = a.id
     ORDER BY r.id DESC"
);

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

// ===== پردازش تأیید یا رد =====
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $request_id = isset($_POST['request_id']) ? (int)$_POST['request_id'] : 0;
    
    if ($action == 'approve') {
        $letter_number = trim($_POST['letter_number'] ?? '');
        $approval_date_shamsi = trim($_POST['approval_date'] ?? '');
        
        if (empty($letter_number)) {
            $message = '❌ لطفاً شماره نامه را وارد کنید.';
            $messageType = 'danger';
        } elseif (empty($approval_date_shamsi)) {
            $message = '❌ لطفاً تاریخ تأیید را وارد کنید.';
            $messageType = 'danger';
        } else {
            // ===== تبدیل تاریخ شمسی به میلادی =====
            $approval_date = shamsiToMiladi($approval_date_shamsi);
            
            if ($approval_date) {
                $updateData = [
                    'status' => 'approved',
                    'letter_number' => $letter_number,
                    'approval_date' => $approval_date,
                    'approved_by' => $user['id']
                ];
                $result = updateData('certificate_requests', $updateData, 'id = :id', ['id' => $request_id]);
                
                if ($result !== false) {
                    $message = '✅ گواهی با موفقیت تأیید شد.';
                    $messageType = 'success';
                    // به‌روزرسانی لیست
                    $requests = fetchAll(
                        "SELECT r.*, 
                                u.name as teacher_name, u.family as teacher_family, u.national_code,
                                t.name as term_name, t.code as term_code,
                                a.name as approver_name, a.family as approver_family
                         FROM certificate_requests r
                         LEFT JOIN users u ON r.teacher_id = u.id
                         LEFT JOIN terms t ON r.term_id = t.id
                         LEFT JOIN users a ON r.approved_by = a.id
                         ORDER BY r.id DESC"
                    );
                } else {
                    $message = '❌ خطا در تأیید گواهی.';
                    $messageType = 'danger';
                }
            } else {
                $message = '❌ تاریخ وارد شده نامعتبر است.';
                $messageType = 'danger';
            }
        }
    } elseif ($action == 'reject') {
        $updateData = ['status' => 'rejected'];
        $result = updateData('certificate_requests', $updateData, 'id = :id', ['id' => $request_id]);
        
        if ($result !== false) {
            $message = '✅ گواهی رد شد.';
            $messageType = 'success';
            // به‌روزرسانی لیست
            $requests = fetchAll(
                "SELECT r.*, 
                        u.name as teacher_name, u.family as teacher_family, u.national_code,
                        t.name as term_name, t.code as term_code,
                        a.name as approver_name, a.family as approver_family
                 FROM certificate_requests r
                 LEFT JOIN users u ON r.teacher_id = u.id
                 LEFT JOIN terms t ON r.term_id = t.id
                 LEFT JOIN users a ON r.approved_by = a.id
                 ORDER BY r.id DESC"
            );
        } else {
            $message = '❌ خطا در رد گواهی.';
            $messageType = 'danger';
        }
    }
}

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