<?php
// admin/report-payment.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, 5])) {
    header('Location: dashboard.php');
    exit;
}

$pageTitle = 'گزارش پرداخت اساتید';
$pageSubtitle = 'مشاهده و خروجی گزارش حق التدریس';

// ===== دریافت فیلترها =====
$teacher_id = isset($_GET['teacher_id']) ? (int)$_GET['teacher_id'] : 0;
$term_id = isset($_GET['term_id']) ? (int)$_GET['term_id'] : 0;
$degree = isset($_GET['degree']) ? (int)$_GET['degree'] : 0;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// ===== بررسی وجود جستجو =====
$hasSearch = ($teacher_id > 0 || $term_id > 0 || $degree > 0 || !empty($search));

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

// ===== دریافت تنظیمات مالیات و بیمه =====
$taxSettings = getTaxSettings();
$taxPercent = $taxSettings['tax_percent'] ?? 0;
$insurancePercent = $taxSettings['insurance_percent'] ?? 0;

// ============================================================
// متغیرهای خروجی
// ============================================================
$reportData = [];
$totalAmount = 0;
$totalTax = 0;
$totalInsurance = 0;
$totalNet = 0;
$termSummary = []; // خلاصه هر ترم

// ============================================================
// شرط‌های جستجو
// ============================================================
$whereConditions = ["u.role_id = (SELECT id FROM roles WHERE level = 6)", "u.is_active = 1"];
$params = [];

// ===== جستجو بر اساس نام/کد ملی =====
if (!empty($search) && $teacher_id == 0) {
    $whereConditions[] = "(u.name LIKE ? OR u.family LIKE ? OR u.national_code LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

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

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

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

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

// ============================================================
// کوئری اصلی - فقط اگر جستجو انجام شده باشد
// ============================================================
$results = [];

if ($hasSearch) {
    $sql = "
        SELECT 
            u.id as teacher_id,
            u.name,
            u.family,
            u.national_code,
            u.sheba_number,
            u.degree,
            c.id as course_id,
            c.name as course_name,
            c.course_type,
            c.units,
            c.hours,
            COALESCE(cs.sessions_count, 0) as sessions_count,
            COALESCE(cs.student_count, 0) as student_count,
            t.id as term_id,
            t.name as term_name,
            t.code as term_code,
            s.amount_per_hour,
            s.amount_per_student
        FROM users u
        LEFT JOIN courses c ON c.teacher_id = u.id
        LEFT JOIN terms t ON c.term_id = t.id
        LEFT JOIN course_sessions cs ON cs.course_id = c.id AND cs.term_id = t.id
        LEFT JOIN salary_settings s ON s.degree = u.degree AND s.course_type = c.course_type
        WHERE $whereSQL
        ORDER BY u.family ASC, u.name ASC, t.id DESC, c.name ASC
    ";

    $results = fetchAll($sql, $params);
}

// ============================================================
// پردازش داده‌ها
// ============================================================
$groupedData = [];

foreach ($results as $row) {
    $teacherKey = $row['teacher_id'];
    $termKey = $row['term_id'] ?? 0;
    
    // ===== گروه‌بندی استاد =====
    if (!isset($groupedData[$teacherKey])) {
        $groupedData[$teacherKey] = [
            'teacher_id' => $row['teacher_id'],
            'name' => $row['name'],
            'family' => $row['family'],
            'national_code' => $row['national_code'],
            'sheba_number' => $row['sheba_number'],
            'degree' => $row['degree'],
            'terms' => []
        ];
    }
    
    // ===== گروه‌بندی ترم =====
    if (!isset($groupedData[$teacherKey]['terms'][$termKey])) {
        $groupedData[$teacherKey]['terms'][$termKey] = [
            'term_id' => $row['term_id'],
            'term_name' => $row['term_name'] ?? 'بدون ترم',
            'term_code' => $row['term_code'] ?? '-',
            'courses' => [],
            'term_total' => 0,
            'term_tax' => 0,
            'term_insurance' => 0,
            'term_net' => 0
        ];
    }
    
    // ===== محاسبه مبلغ هر درس =====
    if ($row['course_type'] == 'theoretical') {
        $courseAmount = ($row['sessions_count'] ?? 0) * ($row['hours'] ?? 1) * ($row['amount_per_hour'] ?? 0);
    } else {
        $courseAmount = ($row['student_count'] ?? 0) * ($row['amount_per_student'] ?? 0);
    }
    
    $courseTax = $courseAmount * ($taxPercent / 100);
    $courseInsurance = $courseAmount * ($insurancePercent / 100);
    $courseNet = $courseAmount - $courseTax - $courseInsurance;
    
    $groupedData[$teacherKey]['terms'][$termKey]['courses'][] = [
        'course_id' => $row['course_id'],
        'course_name' => $row['course_name'],
        'course_type' => $row['course_type'],
        'units' => $row['units'],
        'hours' => $row['hours'],
        'sessions_count' => $row['sessions_count'],
        'student_count' => $row['student_count'],
        'amount_per_hour' => $row['amount_per_hour'] ?? 0,
        'amount_per_student' => $row['amount_per_student'] ?? 0,
        'amount' => $courseAmount,
        'tax' => $courseTax,
        'insurance' => $courseInsurance,
        'net' => $courseNet
    ];
    
    $groupedData[$teacherKey]['terms'][$termKey]['term_total'] += $courseAmount;
    $groupedData[$teacherKey]['terms'][$termKey]['term_tax'] += $courseTax;
    $groupedData[$teacherKey]['terms'][$termKey]['term_insurance'] += $courseInsurance;
    $groupedData[$teacherKey]['terms'][$termKey]['term_net'] += $courseNet;
    
    // ===== جمع کل کلی =====
    $totalAmount += $courseAmount;
    $totalTax += $courseTax;
    $totalInsurance += $courseInsurance;
    $totalNet += $courseNet;
    
    // ===== خلاصه ترم =====
    if (!isset($termSummary[$termKey])) {
        $termSummary[$termKey] = [
            'term_name' => $row['term_name'] ?? 'بدون ترم',
            'term_code' => $row['term_code'] ?? '-',
            'total_amount' => 0,
            'total_tax' => 0,
            'total_insurance' => 0,
            'total_net' => 0,
            'teacher_count' => 0,
            'teachers' => []
        ];
    }
    
    $termSummary[$termKey]['total_amount'] += $courseAmount;
    $termSummary[$termKey]['total_tax'] += $courseTax;
    $termSummary[$termKey]['total_insurance'] += $courseInsurance;
    $termSummary[$termKey]['total_net'] += $courseNet;
    
    // ===== ثبت اساتید هر ترم (برای نمایش تعداد) =====
    if (!in_array($teacherKey, $termSummary[$termKey]['teachers'])) {
        $termSummary[$termKey]['teachers'][] = $teacherKey;
        $termSummary[$termKey]['teacher_count']++;
    }
}

// ===== ذخیره داده‌ها =====
$reportData = $groupedData;

// ============================================================
// اگر استاد خاصی انتخاب شده و درسی ندارد، اطلاعات استاد نمایش داده شود
// ============================================================
if ($teacher_id > 0 && empty($results) && $hasSearch) {
    $teacherInfo = fetchOne("SELECT id, name, family, national_code, sheba_number, degree FROM users WHERE id = ?", [$teacher_id]);
    if ($teacherInfo) {
        $reportData[$teacherInfo['id']] = [
            'teacher_id' => $teacherInfo['id'],
            'name' => $teacherInfo['name'],
            'family' => $teacherInfo['family'],
            'national_code' => $teacherInfo['national_code'],
            'sheba_number' => $teacherInfo['sheba_number'] ?? 'ثبت نشده',
            'degree' => $teacherInfo['degree'],
            'terms' => []
        ];
    }
}

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