<?php
// admin/export-payment-pdf.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', '', 16);
        $this->Cell(0, 10, 'گزارش پرداخت اساتید', 0, 1, 'C');
        $this->SetFont('freeserif', '', 10);
        $this->Cell(0, 6, 'تاریخ چاپ: ' . jalaliDate(date('Y-m-d H:i:s')), 0, 1, 'C');
        $this->Ln(5);
    }
    
    public function Footer() {
        $this->SetY(-15);
        $this->SetFont('freeserif', 'I', 8);
        $this->Cell(0, 10, 'صفحه ' . $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(15, 40, 15);
$pdf->SetAutoPageBreak(true, 25);
$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;
}

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

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

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

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