<?php
// admin/export-payment-pdf-new.php - خروجی PDF گزارش پرداخت (نسخه نهایی با اعداد فارسی)

error_reporting(0);
ini_set('display_errors', 0);

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

if (!isLoggedIn()) {
    die('ابتدا وارد شوید.');
}

$user = getCurrentUser();
if (!in_array($user['role_level'], [1, 2, 3, 5])) {
    die('دسترسی غیرمجاز.');
}

// ===== دریافت فیلترها =====
$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;

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

// ===== شرط‌های جستجو =====
$whereConditions = ["1=1"];
$params = [];

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

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

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

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

// ===== کوئری اصلی =====
$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 u.role_id = (SELECT id FROM roles WHERE level = 6)
    AND u.is_active = 1
    AND $whereSQL
    ORDER BY u.family ASC, u.name ASC, t.id DESC, c.name ASC
";

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

// ===== کلاس PDF =====
class MYPDF extends TCPDF {
    public function Header() {
        $this->SetY(10);
        $this->SetFont('freeserif', '', 14);
        $this->Cell(0, 8, 'گزارش پرداخت اساتید', 0, 1, 'C');
        $this->SetFont('freeserif', '', 9);
        $this->Cell(0, 5, 'تاریخ چاپ: ' . jalaliDate(date('Y-m-d H:i:s')), 0, 1, 'C');
        $this->Ln(3);
    }
    
    public function Footer() {
        $this->SetY(-15);
        $this->SetFont('freeserif', 'I', 7);
        $this->Cell(0, 8, 'صفحه ' . $this->getAliasNumPage() . ' از ' . $this->getAliasNbPages(), 0, 0, 'C');
    }
}

// ===== ایجاد PDF =====
$pdf = new MYPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator('سامانه مدیریت اساتید');
$pdf->SetAuthor('مدیریت');
$pdf->SetTitle('گزارش پرداخت اساتید');
$pdf->setPrintHeader(true);
$pdf->setPrintFooter(true);
$pdf->SetMargins(10, 35, 10);
$pdf->SetAutoPageBreak(true, 20);
$pdf->AddPage();

// ===== محاسبه مجموع =====
$totalAmount = 0;
$totalTax = 0;
$totalInsurance = 0;
$totalNet = 0;

// ===== گروه‌بندی داده‌ها =====
$groupedData = [];
foreach ($results as $row) {
    $teacherKey = $row['teacher_id'];
    $termKey = $row['term_id'] ?? 0;
    
    if (!isset($groupedData[$teacherKey])) {
        $groupedData[$teacherKey] = [
            '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_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);
        $unitPrice = $row['amount_per_hour'] ?? 0;
    } else {
        $courseAmount = ($row['student_count'] ?? 0) * ($row['amount_per_student'] ?? 0);
        $unitPrice = $row['amount_per_student'] ?? 0;
    }
    
    $courseTax = $courseAmount * ($taxPercent / 100);
    $courseInsurance = $courseAmount * ($insurancePercent / 100);
    $courseNet = $courseAmount - $courseTax - $courseInsurance;
    
    $groupedData[$teacherKey]['terms'][$termKey]['courses'][] = [
        'course_name' => $row['course_name'],
        'course_type' => $row['course_type'],
        'sessions_count' => $row['sessions_count'],
        'student_count' => $row['student_count'],
        'unitPrice' => $unitPrice,
        '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;
}

// ===== تابع کمکی برای نمایش اعداد فارسی =====
function pNum($number) {
    return persianNumber(number_format($number));
}

// ===== نوشتن مستقیم با استفاده از Cell =====
$pdf->SetFont('freeserif', '', 10);

foreach ($groupedData as $teacherId => $teacher) {
    $teacherTotal = 0;
    foreach ($teacher['terms'] as $term) {
        $teacherTotal += $term['term_net'];
    }
    
    // ===== نام استاد =====
    $pdf->SetFont('freeserif', 'B', 12);
    $pdf->Cell(0, 8, $teacher['name'] . ' ' . $teacher['family'], 0, 1, 'R');
    $pdf->SetFont('freeserif', '', 8);
    $pdf->Cell(0, 5, 'کد ملی: ' . $teacher['national_code'] . ' | مدرک: ' . getDegreeName($teacher['degree']) . ' | شماره شبا: ' . $teacher['sheba_number'] . ' | جمع کل: ' . pNum($teacherTotal) . ' ریال', 0, 1, 'R');
    $pdf->Ln(2);
    
    foreach ($teacher['terms'] as $termId => $term) {
        $pdf->SetFont('freeserif', 'B', 10);
        $pdf->Cell(0, 6, $term['term_name'] . ' (' . $term['term_code'] . ') - جمع: ' . pNum($term['term_net']) . ' ریال', 0, 1, 'R');
        $pdf->Ln(1);
        
        // ===== هدر جدول =====
        $pdf->SetFont('freeserif', 'B', 6);
        $pdf->Cell(22, 5, 'مبلغ نهایی', 1, 0, 'C');
        $pdf->Cell(16, 5, 'بیمه', 1, 0, 'C');
        $pdf->Cell(16, 5, 'مالیات', 1, 0, 'C');
        $pdf->Cell(22, 5, 'مبلغ کل', 1, 0, 'C');
        $pdf->Cell(18, 5, 'مبلغ واحد', 1, 0, 'C');
        $pdf->Cell(12, 5, 'دانشجو', 1, 0, 'C');
        $pdf->Cell(12, 5, 'جلسات', 1, 0, 'C');
        $pdf->Cell(20, 5, 'نوع', 1, 0, 'C');
        $pdf->Cell(30, 5, 'نام درس', 1, 0, 'C');
        $pdf->Cell(8, 5, '#', 1, 1, 'C');
        
        // ===== ردیف‌های درس =====
        $pdf->SetFont('freeserif', '', 6);
        $i = 1;
        foreach ($term['courses'] as $course) {
            $pdf->Cell(22, 5, pNum($course['net']), 1, 0, 'C');
            $pdf->Cell(16, 5, pNum($course['insurance']), 1, 0, 'C');
            $pdf->Cell(16, 5, pNum($course['tax']), 1, 0, 'C');
            $pdf->Cell(22, 5, pNum($course['amount']), 1, 0, 'C');
            $pdf->Cell(18, 5, pNum($course['unitPrice']), 1, 0, 'C');
            $pdf->Cell(12, 5, $course['student_count'], 1, 0, 'C');
            $pdf->Cell(12, 5, $course['sessions_count'], 1, 0, 'C');
            $pdf->Cell(20, 5, getCourseTypeName($course['course_type']), 1, 0, 'C');
            $pdf->Cell(30, 5, $course['course_name'], 1, 0, 'C');
            $pdf->Cell(8, 5, $i++, 1, 1, 'C');
        }
        
        // ===== جمع ترم =====
        $pdf->SetFont('freeserif', 'B', 6);
        $pdf->Cell(22, 5, pNum($term['term_net']), 1, 0, 'C');
        $pdf->Cell(16, 5, pNum($term['term_insurance']), 1, 0, 'C');
        $pdf->Cell(16, 5, pNum($term['term_tax']), 1, 0, 'C');
        $pdf->Cell(22, 5, pNum($term['term_total']), 1, 0, 'C');
        $pdf->Cell(100, 5, 'جمع ترم', 1, 1, 'C');
        
        $pdf->Ln(3);
    }
    
    $pdf->Ln(2);
}

// ===== جمع کل نهایی =====
$pdf->Ln(3);
$pdf->SetFont('freeserif', 'B', 11);
$pdf->Cell(0, 8, 'جمع کل نهایی:', 0, 1, 'R');
$pdf->SetFont('freeserif', '', 9);
$pdf->Cell(0, 6, 'حق التدریس: ' . pNum($totalAmount) . ' ریال', 0, 1, 'R');
$pdf->Cell(0, 6, 'مالیات: ' . pNum($totalTax) . ' ریال', 0, 1, 'R');
$pdf->Cell(0, 6, 'بیمه: ' . pNum($totalInsurance) . ' ریال', 0, 1, 'R');
$pdf->SetFont('freeserif', 'B', 12);
$pdf->Cell(0, 8, 'قابل پرداخت: ' . pNum($totalNet) . ' ریال', 0, 1, 'R');

// ===== خروجی =====
$pdf->Output('ghesavat_teachers_' . date('Ymd_His') . '.pdf', 'I');
exit;
?>