<?php
// admin/dashboard.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: ../teacher/profile.php');
    exit;
}

$pageTitle = 'داشبورد مدیریت';
$pageSubtitle = 'نمای کلی از وضعیت سامانه';

// ===== آمار =====
$totalTeachers = getTotalTeachers();
$teachersWithSheba = getTeachersWithSheba();
$teachersWithoutSheba = $totalTeachers - $teachersWithSheba;
$pendingSheba = getPendingSheba();

// ===== آمار تیکت‌ها =====
$ticketStats = [
    'total' => fetchCount("SELECT id FROM tickets"),
    'new' => fetchCount("SELECT id FROM tickets WHERE status = 'new'"),
    'replied' => fetchCount("SELECT id FROM tickets WHERE status = 'replied'"),
    'closed' => fetchCount("SELECT id FROM tickets WHERE status = 'closed'"),
];

// ===== آمار امروز، دیروز، هفته، ترم =====
$today = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));
$weekStart = date('Y-m-d', strtotime('this week'));
$activeTerm = getActiveTerm();

$stats = [
    'today' => fetchCount("SELECT id FROM users WHERE DATE(created_at) = ?", [$today]),
    'yesterday' => fetchCount("SELECT id FROM users WHERE DATE(created_at) = ?", [$yesterday]),
    'this_week' => fetchCount("SELECT id FROM users WHERE DATE(created_at) >= ?", [$weekStart]),
    'this_term' => $activeTerm ? fetchCount("SELECT id FROM users WHERE DATE(created_at) >= ?", [$activeTerm['start_date']]) : 0,
];

// ============================================================
// آمار مالی ۳ ترم گذشته
// ============================================================
$lastThreeTerms = fetchAll("SELECT id, name, code FROM terms ORDER BY id DESC LIMIT 3");
$financialStats = [];

foreach ($lastThreeTerms as $term) {
    $termId = $term['id'];
    
    $sql = "
        SELECT 
            c.course_type,
            c.hours,
            cs.sessions_count,
            cs.student_count,
            s.amount_per_hour,
            s.amount_per_student,
            u.degree
        FROM courses c
        LEFT JOIN course_sessions cs ON c.id = cs.course_id AND c.term_id = cs.term_id
        LEFT JOIN users u ON c.teacher_id = u.id
        LEFT JOIN salary_settings s ON s.degree = u.degree AND s.course_type = c.course_type
        WHERE c.term_id = ?
    ";
    $courses = fetchAll($sql, [$termId]);
    
    $termTotalAmount = 0;
    $termTotalTax = 0;
    $termTotalInsurance = 0;
    $termTotalNet = 0;
    
    $taxSettings = getTaxSettings();
    $taxPercent = $taxSettings['tax_percent'] ?? 0;
    $insurancePercent = $taxSettings['insurance_percent'] ?? 0;
    
    foreach ($courses as $course) {
        if ($course['course_type'] == 'theoretical') {
            $courseAmount = ($course['sessions_count'] ?? 0) * ($course['hours'] ?? 1) * ($course['amount_per_hour'] ?? 0);
        } else {
            $courseAmount = ($course['student_count'] ?? 0) * ($course['amount_per_student'] ?? 0);
        }
        
        $courseTax = $courseAmount * ($taxPercent / 100);
        $courseInsurance = $courseAmount * ($insurancePercent / 100);
        $courseNet = $courseAmount - $courseTax - $courseInsurance;
        
        $termTotalAmount += $courseAmount;
        $termTotalTax += $courseTax;
        $termTotalInsurance += $courseInsurance;
        $termTotalNet += $courseNet;
    }
    
    $financialStats[$termId] = [
        'name' => $term['name'],
        'code' => $term['code'],
        'total_amount' => $termTotalAmount,
        'total_tax' => $termTotalTax,
        'total_insurance' => $termTotalInsurance,
        'total_net' => $termTotalNet,
        'course_count' => count($courses)
    ];
}

// ============================================================
// داده‌های نمودار پرداخت‌های ماهانه (۶ ماه اخیر)
// ============================================================
$monthlyData = [];
$monthLabels = [];

// ===== استفاده از تابع gregorianToJalali برای نام ماه =====
for ($i = 5; $i >= 0; $i--) {
    $month = date('Y-m', strtotime("-$i months"));
    $timestamp = strtotime("-$i months");
    
    // استخراج نام ماه شمسی
    $dateParts = explode('-', date('Y-m-d', $timestamp));
    list($jy, $jm, $jd) = gregorianToJalali($dateParts[0], $dateParts[1], $dateParts[2]);
    
    $monthNames = [
        1 => 'فروردین', 2 => 'اردیبهشت', 3 => 'خرداد',
        4 => 'تیر', 5 => 'مرداد', 6 => 'شهریور',
        7 => 'مهر', 8 => 'آبان', 9 => 'آذر',
        10 => 'دی', 11 => 'بهمن', 12 => 'اسفند'
    ];
    $monthLabels[] = $monthNames[$jm] ?? $jm;
    
    // دریافت مجموع پرداختی آن ماه
    $sql = "
        SELECT COALESCE(SUM(t.amount), 0) as total
        FROM transactions t
        WHERE DATE_FORMAT(t.payment_date, '%Y-%m') = ?
    ";
    $result = fetchOne($sql, [$month]);
    $monthlyData[] = (float)($result['total'] ?? 0);
}

// ============================================================
// آخرین تراکنش‌ها
// ============================================================
$recentTransactions = fetchAll(
    "SELECT t.*, u.name, u.family 
     FROM transactions t 
     LEFT JOIN users u ON t.teacher_id = u.id 
     ORDER BY t.id DESC 
     LIMIT 5"
);

// ============================================================
// آخرین مدرسین وارد شده
// ============================================================
$recentLogins = fetchAll(
    "SELECT u.*, r.name as role_name 
     FROM users u 
     LEFT JOIN roles r ON u.role_id = r.id 
     WHERE u.role_id = (SELECT id FROM roles WHERE level = 6) 
     AND u.last_login IS NOT NULL 
     ORDER BY u.last_login DESC 
     LIMIT 10"
);

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