<?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 '../includes/settings.php';

// ===== بررسی وجود TCPDF =====
$tcpdfPath = __DIR__ . '/../tcpdf/tcpdf.php';
if (!file_exists($tcpdfPath)) {
    die('❌ فایل TCPDF یافت نشد. مسیر: ' . $tcpdfPath);
}
require_once $tcpdfPath;

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;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

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

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

// ===== شرط‌های جستجو =====
$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);

// ===== کوئری اصلی =====
$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);

// ============================================================
// کلاس PDF سفارشی
// ============================================================
class MYPDF extends TCPDF {
    private $siteName;
    private $institutionName;
    private $developerName;
    
    public function __construct($siteName, $institutionName, $developerName) {
        parent::__construct('L', 'mm', 'A4', true, 'UTF-8', false);
        $this->siteName = $siteName;
        $this->institutionName = $institutionName;
        $this->developerName = $developerName;
        $this->setPrintHeader(false);
        $this->setPrintFooter(false);
        $this->SetFont('dejavusans', '', 9);
    }
    
    public function Footer() {
        $this->SetY(-12);
        $this->SetFont('dejavusans', '', 8);
        $this->SetTextColor(150, 150, 150);
        $this->Cell(0, 5, $this->siteName . ' | ' . $this->institutionName . ' | توسعه: ' . $this->developerName, 0, 0, 'C');
        $this->Cell(0, 5, 'صفحه ' . $this->getAliasNumPage() . ' از ' . $this->getAliasNbPages(), 0, 0, 'L');
    }
}

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

foreach ($results as $row) {
    if (!in_array($row['teacher_id'], $teacherIds)) {
        $teacherIds[] = $row['teacher_id'];
    }
    
    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;
    
    $totalAmount += $courseAmount;
    $totalTax += $courseTax;
    $totalInsurance += $courseInsurance;
    $totalNet += $courseNet;
    $totalCourses++;
}
$totalTeachers = count($teacherIds);

// ============================================================
// ایجاد PDF
// ============================================================
$pdf = new MYPDF($siteName, $institutionName, $developerName);
$pdf->SetMargins(10, 10, 10);
$pdf->SetAutoPageBreak(true, 20);
$pdf->AddPage();

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

// ============================================================
// هدر گزارش (وسط چین)
// ============================================================
$pdf->SetFont('dejavusans', 'B', 16);
$pdf->Cell(0, 8, 'گزارش پرداخت اساتید', 0, 1, 'C');
$pdf->SetFont('dejavusans', '', 10);
$pdf->Cell(0, 5, $siteName . ' | ' . $institutionName, 0, 1, 'C');
$pdf->SetFont('dejavusans', '', 9);
$pdf->Cell(0, 5, 'تاریخ چاپ: ' . jalaliDate(date('Y-m-d H:i:s')), 0, 1, 'C');
$pdf->Ln(5);

// ============================================================
// خلاصه آمار (راست‌چین کامل)
// ============================================================
$pdf->SetFont('dejavusans', 'B', 9);

// ردیف اول: تعداد اساتید و دروس (وسط چین)
$pdf->Cell(0, 6, 'تعداد اساتید: ' . $totalTeachers . '  |  تعداد دروس: ' . $totalCourses, 0, 1, 'C');
$pdf->Ln(2);

// ردیف دوم: آمار مالی (راست‌چین در یک خط)
$pdf->SetFont('dejavusans', '', 9);

// محاسبه عرض برای 4 آیتم در یک خط
$pageWidth = $pdf->GetPageWidth() - 20; // حاشیه‌ها
$itemWidth = $pageWidth / 4;

$pdf->Cell($itemWidth, 6, 'جمع حق التدریس: ' . pNum($totalAmount) . ' ریال', 0, 0, 'R');
$pdf->Cell($itemWidth, 6, 'جمع مالیات: ' . pNum($totalTax) . ' ریال', 0, 0, 'R');
$pdf->Cell($itemWidth, 6, 'جمع بیمه: ' . pNum($totalInsurance) . ' ریال', 0, 0, 'R');
$pdf->Cell($itemWidth, 6, 'جمع قابل پرداخت: ' . pNum($totalNet) . ' ریال', 0, 1, 'R');
$pdf->Ln(4);

// ============================================================
// جدول گزارش با مرج کامل
// ============================================================
$pdf->SetFont('dejavusans', 'B', 7);

// عرض ستون‌ها (از راست به چپ)
$w = array(10, 30, 22, 32, 22, 18, 14, 14, 18, 22, 22, 22, 28);

// ===== هدر جدول (راست به چپ) =====
$pdf->SetFillColor(241, 245, 249);
$pdf->SetTextColor(0, 0, 0);

$pdf->Cell($w[12], 6, 'مبلغ نهایی', 1, 0, 'C', 1);
$pdf->Cell($w[11], 6, 'بیمه', 1, 0, 'C', 1);
$pdf->Cell($w[10], 6, 'مالیات', 1, 0, 'C', 1);
$pdf->Cell($w[9], 6, 'مبلغ کل', 1, 0, 'C', 1);
$pdf->Cell($w[8], 6, 'مبلغ واحد', 1, 0, 'C', 1);
$pdf->Cell($w[7], 6, 'دانشجو', 1, 0, 'C', 1);
$pdf->Cell($w[6], 6, 'جلسات', 1, 0, 'C', 1);
$pdf->Cell($w[5], 6, 'نوع', 1, 0, 'C', 1);
$pdf->Cell($w[4], 6, 'ترم', 1, 0, 'C', 1);
$pdf->Cell($w[3], 6, 'نام درس', 1, 0, 'C', 1);
$pdf->Cell($w[2], 6, 'کد ملی', 1, 0, 'C', 1);
$pdf->Cell($w[1], 6, 'نام استاد', 1, 0, 'C', 1);
$pdf->Cell($w[0], 6, '#', 1, 1, 'C', 1);

$pdf->SetFont('dejavusans', '', 6);
$pdf->SetTextColor(0, 0, 0);

$rowNum = 1;
$teacherCourses = [];

// ===== گروه‌بندی دروس هر استاد =====
foreach ($results as $row) {
    $teacherCourses[$row['teacher_id']][] = $row;
}

foreach ($teacherCourses as $teacherId => $courses) {
    $teacher = $courses[0];
    $firstRow = true;
    
    foreach ($courses as $index => $course) {
        if ($course['course_type'] == 'theoretical') {
            $courseAmount = ($course['sessions_count'] ?? 0) * ($course['hours'] ?? 1) * ($course['amount_per_hour'] ?? 0);
            $unitPrice = $course['amount_per_hour'] ?? 0;
        } else {
            $courseAmount = ($course['student_count'] ?? 0) * ($course['amount_per_student'] ?? 0);
            $unitPrice = $course['amount_per_student'] ?? 0;
        }
        
        $courseTax = $courseAmount * ($taxPercent / 100);
        $courseInsurance = $courseAmount * ($insurancePercent / 100);
        $courseNet = $courseAmount - $courseTax - $courseInsurance;
        
        if ($firstRow) {
            // ===== ردیف اول با نام استاد و شماره =====
            $pdf->Cell($w[12], 5, pNum($courseNet), 1, 0, 'C');
            $pdf->Cell($w[11], 5, pNum($courseInsurance), 1, 0, 'C');
            $pdf->Cell($w[10], 5, pNum($courseTax), 1, 0, 'C');
            $pdf->Cell($w[9], 5, pNum($courseAmount), 1, 0, 'C');
            $pdf->Cell($w[8], 5, pNum($unitPrice), 1, 0, 'C');
            $pdf->Cell($w[7], 5, $course['student_count'], 1, 0, 'C');
            $pdf->Cell($w[6], 5, $course['sessions_count'], 1, 0, 'C');
            $pdf->Cell($w[5], 5, getCourseTypeName($course['course_type']), 1, 0, 'C');
            $pdf->Cell($w[4], 5, $course['term_name'] ?? '-', 1, 0, 'C');
            $pdf->Cell($w[3], 5, $course['course_name'], 1, 0, 'C');
            $pdf->Cell($w[2], 5, $course['national_code'], 1, 0, 'C');
            $pdf->Cell($w[1], 5, $course['name'] . ' ' . $course['family'], 1, 0, 'C');
            $pdf->Cell($w[0], 5, $rowNum, 1, 1, 'C');
            
            $firstRow = false;
        } else {
            // ===== ردیف‌های بعدی بدون نام استاد و شماره =====
            $pdf->Cell($w[12], 5, pNum($courseNet), 1, 0, 'C');
            $pdf->Cell($w[11], 5, pNum($courseInsurance), 1, 0, 'C');
            $pdf->Cell($w[10], 5, pNum($courseTax), 1, 0, 'C');
            $pdf->Cell($w[9], 5, pNum($courseAmount), 1, 0, 'C');
            $pdf->Cell($w[8], 5, pNum($unitPrice), 1, 0, 'C');
            $pdf->Cell($w[7], 5, $course['student_count'], 1, 0, 'C');
            $pdf->Cell($w[6], 5, $course['sessions_count'], 1, 0, 'C');
            $pdf->Cell($w[5], 5, getCourseTypeName($course['course_type']), 1, 0, 'C');
            $pdf->Cell($w[4], 5, $course['term_name'] ?? '-', 1, 0, 'C');
            $pdf->Cell($w[3], 5, $course['course_name'], 1, 0, 'C');
            $pdf->Cell($w[2], 5, $course['national_code'], 1, 0, 'C');
            $pdf->Cell($w[1], 5, '', 1, 0, 'C'); // خالی
            $pdf->Cell($w[0], 5, '', 1, 1, 'C'); // خالی
        }
        
        // ===== صفحه جدید =====
        if ($pdf->GetY() > 180) {
            $pdf->AddPage();
            $pdf->SetFont('dejavusans', 'B', 7);
            $pdf->SetFillColor(241, 245, 249);
            $pdf->Cell($w[12], 6, 'مبلغ نهایی', 1, 0, 'C', 1);
            $pdf->Cell($w[11], 6, 'بیمه', 1, 0, 'C', 1);
            $pdf->Cell($w[10], 6, 'مالیات', 1, 0, 'C', 1);
            $pdf->Cell($w[9], 6, 'مبلغ کل', 1, 0, 'C', 1);
            $pdf->Cell($w[8], 6, 'مبلغ واحد', 1, 0, 'C', 1);
            $pdf->Cell($w[7], 6, 'دانشجو', 1, 0, 'C', 1);
            $pdf->Cell($w[6], 6, 'جلسات', 1, 0, 'C', 1);
            $pdf->Cell($w[5], 6, 'نوع', 1, 0, 'C', 1);
            $pdf->Cell($w[4], 6, 'ترم', 1, 0, 'C', 1);
            $pdf->Cell($w[3], 6, 'نام درس', 1, 0, 'C', 1);
            $pdf->Cell($w[2], 6, 'کد ملی', 1, 0, 'C', 1);
            $pdf->Cell($w[1], 6, 'نام استاد', 1, 0, 'C', 1);
            $pdf->Cell($w[0], 6, '#', 1, 1, 'C', 1);
            $pdf->SetFont('dejavusans', '', 6);
        }
    }
    
    $rowNum++;
}

// ============================================================
// جمع کل (راست به چپ)
// ============================================================
$pdf->SetFont('dejavusans', 'B', 7);
$pdf->SetFillColor(241, 245, 249);

$pdf->Cell($w[12], 6, pNum($totalNet), 1, 0, 'C', 1);
$pdf->Cell($w[11], 6, pNum($totalInsurance), 1, 0, 'C', 1);
$pdf->Cell($w[10], 6, pNum($totalTax), 1, 0, 'C', 1);
$pdf->Cell($w[9], 6, pNum($totalAmount), 1, 0, 'C', 1);
$pdf->Cell($w[8], 6, '', 1, 0, 'C', 1);
$pdf->Cell($w[7], 6, '', 1, 0, 'C', 1);
$pdf->Cell($w[6], 6, '', 1, 0, 'C', 1);
$pdf->Cell($w[5], 6, '', 1, 0, 'C', 1);
$pdf->Cell($w[4], 6, '', 1, 0, 'C', 1);
$pdf->Cell($w[3], 6, '', 1, 0, 'C', 1);
$pdf->Cell($w[2], 6, '', 1, 0, 'C', 1);
$pdf->Cell($w[1], 6, 'جمع کل', 1, 0, 'C', 1);
$pdf->Cell($w[0], 6, '', 1, 1, 'C', 1);

// ============================================================
// خروجی
// ============================================================
$filename = 'گزارش_پرداخت_' . date('Ymd_His') . '.pdf';
$pdf->Output($filename, 'I');
exit;
?>