<?php
// admin/payment-calculate.php - محاسبه فیش پرداخت با جستجوی Ajax

session_start();
require_once '../config/database.php';
require_once '../includes/db.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';
require_once '../includes/settings.php';

if (!isLoggedIn() || !in_array($_SESSION['role_level'], [1,2,3,5])) {
    header('Location: dashboard.php');
    exit;
}

$pageTitle = 'محاسبه فیش پرداخت';
$pageSubtitle = 'مشاهده فیش پرداخت اساتید';

$message = '';
$paymentData = [];
$selectedTeacher = null;
$selectedTerm = null;
$teacherTerms = [];
$totalAmount = 0;
$taxAmount = 0;
$insuranceAmount = 0;
$netAmount = 0;

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

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

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

// ===== دریافت تنظیمات سامانه =====
$settings = getSettings();
$siteName = $settings['site_name'] ?? 'سامانه مدیریت اساتید';
$institutionName = $settings['institution_name'] ?? 'دانشگاه علوم و فناوری';
$logoPath = !empty($settings['logo']) ? '../' . $settings['logo'] : '';
$footerDeveloper = $settings['footer_developer'] ?? '';

// ===== دریافت اطلاعات استاد =====
if ($teacher_id > 0) {
    $selectedTeacher = fetchOne("SELECT * FROM users WHERE id = ?", [$teacher_id]);
}

// ===== دریافت لیست ترم‌هایی که استاد در آنها درس دارد =====
if ($teacher_id > 0) {
    $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",
        [$teacher_id]
    );
}

// ===== محاسبه برای استاد و ترم انتخاب شده =====
if ($teacher_id > 0 && $term_id > 0) {
    $selectedTerm = fetchOne("SELECT * FROM terms WHERE id = ?", [$term_id]);
    
    if ($selectedTeacher && $selectedTerm) {
        $courses = fetchAll(
            "SELECT c.*, 
                    cs.sessions_count, cs.student_count,
                    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
             WHERE c.teacher_id = ? AND c.term_id = ?",
            [$teacher_id, $term_id]
        );
        
        $degree = $selectedTeacher['degree'] ?? 1;
        
        foreach ($courses as $course) {
            $courseType = $course['course_type'] ?? 'theoretical';
            $salarySetting = getSalaryAmount($degree, $courseType);
            
            if ($salarySetting) {
                if ($courseType == 'theoretical') {
                    $sessions = $course['sessions_count'] ?? 0;
                    $hoursPerSession = $course['hours'] ?? 1;
                    $amountPerHour = $salarySetting['amount_per_hour'] ?? 0;
                    $courseTotal = $sessions * $hoursPerSession * $amountPerHour;
                    $unitPrice = $amountPerHour;
                    $unitLabel = 'ساعتی';
                } else {
                    $students = $course['student_count'] ?? 0;
                    $amountPerStudent = $salarySetting['amount_per_student'] ?? 0;
                    $courseTotal = $students * $amountPerStudent;
                    $unitPrice = $amountPerStudent;
                    $unitLabel = 'دانشجویی';
                }
                
                $paymentData[] = [
                    'course_name' => $course['name'],
                    'course_type' => $courseType,
                    'sessions' => $course['sessions_count'] ?? 0,
                    'students' => $course['student_count'] ?? 0,
                    'hours' => $course['hours'] ?? 1,
                    'unit_price' => $unitPrice,
                    'unit_label' => $unitLabel,
                    'total' => $courseTotal
                ];
                
                $totalAmount += $courseTotal;
            }
        }
        
        $taxAmount = $totalAmount * ($taxPercent / 100);
        $insuranceAmount = $totalAmount * ($insurancePercent / 100);
        $netAmount = $totalAmount - $taxAmount - $insuranceAmount;
    }
}

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