<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/tcpdf_autoload.php';

class PDFGenerator {
    private $pdf;
    private $rtl = true;

    public function __construct() {
        // إنشاء ملف PDF جديد
        $this->pdf = new KAFILO_TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        
        // إعداد معلومات الملف
        $this->pdf->SetCreator('نظام كفيلو');
        $this->pdf->SetAuthor('نظام كفيلو');
        $this->pdf->SetTitle('كشف حساب');
        
        // إعداد الهوامش
        $this->pdf->SetMargins(15, 15, 15);
        $this->pdf->SetHeaderMargin(5);
        $this->pdf->SetFooterMargin(10);
        
        // إعداد الخط
        $this->pdf->SetFont('aealarabiya', '', 12);
        
        // إعداد اتجاه الكتابة من اليمين لليسار
        $this->pdf->setRTL($this->rtl);
        
        // إزالة الهيدر والفوتر الافتراضي
        $this->pdf->setPrintHeader(false);
        $this->pdf->setPrintFooter(false);
        
        // إضافة صفحة جديدة
        $this->pdf->AddPage();
    }

    public function generateTransactionsPDF($type, $id, $startDate, $endDate) {
        global $pdo;
        
        // الحصول على معلومات الحساب
        if ($type === 'bank') {
            $stmt = $pdo->prepare("SELECT bank_name as name FROM bank_accounts WHERE id = ?");
        } else {
            $stmt = $pdo->prepare("SELECT name FROM cash_funds WHERE id = ?");
        }
        $stmt->execute([$id]);
        $result = $stmt->fetch();
        $accountName = $result ? $result['name'] : 'غير معروف';

        // إضافة عنوان الكشف
        $this->pdf->SetFont('aealarabiya', 'B', 16);
        $this->pdf->Cell(0, 10, 'كشف حساب', 0, 1, 'C');
        $this->pdf->Cell(0, 10, $accountName, 0, 1, 'C');
        $this->pdf->SetFont('aealarabiya', '', 12);
        $this->pdf->Cell(0, 10, 'الفترة: من ' . date('d/m/Y', strtotime($startDate)) . ' إلى ' . date('d/m/Y', strtotime($endDate)), 0, 1, 'C');
        $this->pdf->Ln(5);

        // حساب الرصيد الافتتاحي
        $stmt = $pdo->prepare("
            SELECT COALESCE(SUM(CASE 
                WHEN type IN ('deposit', 'transfer_in') THEN amount 
                ELSE -amount 
            END), 0) as balance
            FROM financial_transactions 
            WHERE account_type = ? 
            AND account_id = ? 
            AND transaction_date < ?
        ");
        $stmt->execute([$type, $id, $startDate]);
        $openingBalance = $stmt->fetchColumn();

        // عرض الرصيد الافتتاحي
        $this->pdf->Cell(0, 10, 'الرصيد الافتتاحي: ' . number_format($openingBalance, 2) . ' درهم', 0, 1, 'R');
        $this->pdf->Ln(5);

        // إنشاء جدول المعاملات
        $header = array('التاريخ', 'نوع العملية', 'المبلغ', 'الوصف', 'المرجع', 'تفاصيل التحويل', 'الرصيد');
        $this->pdf->SetFillColor(240, 240, 240);
        $this->pdf->SetFont('aealarabiya', 'B', 10);
        
        // عرض رأس الجدول
        $w = array(25, 25, 25, 40, 25, 30, 25);
        foreach($header as $i => $col) {
            $this->pdf->Cell($w[$i], 7, $col, 1, 0, 'C', true);
        }
        $this->pdf->Ln();

        // الحصول على المعاملات
        $stmt = $pdo->prepare("
            SELECT 
                ft.*,
                u.name as created_by,
                CASE 
                    WHEN ft.type = 'transfer_out' THEN 
                        CASE ft.transfer_to_type
                            WHEN 'bank' THEN (SELECT bank_name FROM bank_accounts WHERE id = ft.transfer_to_id)
                            WHEN 'cash' THEN (SELECT name FROM cash_funds WHERE id = ft.transfer_to_id)
                        END
                    WHEN ft.type = 'transfer_in' THEN 
                        CASE 
                            WHEN EXISTS (SELECT 1 FROM financial_transactions ft2 WHERE ft2.type = 'transfer_out' AND ft2.transfer_to_type = ft.account_type AND ft2.transfer_to_id = ft.account_id AND ft2.amount = ft.amount AND ft2.transaction_date = ft.transaction_date) THEN
                                CASE (SELECT account_type FROM financial_transactions ft2 WHERE ft2.type = 'transfer_out' AND ft2.transfer_to_type = ft.account_type AND ft2.transfer_to_id = ft.account_id AND ft2.amount = ft.amount AND ft2.transaction_date = ft.transaction_date)
                                    WHEN 'bank' THEN (SELECT bank_name FROM bank_accounts WHERE id = (SELECT account_id FROM financial_transactions ft2 WHERE ft2.type = 'transfer_out' AND ft2.transfer_to_type = ft.account_type AND ft2.transfer_to_id = ft.account_id AND ft2.amount = ft.amount AND ft2.transaction_date = ft.transaction_date))
                                    WHEN 'cash' THEN (SELECT name FROM cash_funds WHERE id = (SELECT account_id FROM financial_transactions ft2 WHERE ft2.type = 'transfer_out' AND ft2.transfer_to_type = ft.account_type AND ft2.transfer_to_id = ft.account_id AND ft2.amount = ft.amount AND ft2.transaction_date = ft.transaction_date))
                                END
                        END
                END as transfer_details
            FROM financial_transactions ft
            LEFT JOIN users u ON ft.created_by = u.id
            WHERE ft.account_type = ? 
            AND ft.account_id = ?
            AND ft.transaction_date BETWEEN ? AND ?
            ORDER BY ft.transaction_date ASC, ft.id ASC
        ");
        $stmt->execute([$type, $id, $startDate, $endDate]);
        $transactions = $stmt->fetchAll();

        // عرض المعاملات
        $this->pdf->SetFont('aealarabiya', '', 10);
        $currentBalance = $openingBalance;
        foreach($transactions as $row) {
            if (in_array($row['type'], ['deposit', 'transfer_in'])) {
                $currentBalance += $row['amount'];
                $color = array(0, 128, 0); // أخضر للإيداع
            } else {
                $currentBalance -= $row['amount'];
                $color = array(200, 0, 0); // أحمر للسحب
            }

            $this->pdf->SetTextColor(0, 0, 0);
            $this->pdf->Cell($w[0], 6, date('d/m/Y', strtotime($row['transaction_date'])), 'LR', 0, 'C');
            
            $typeText = $this->getTransactionTypeText($row['type']);
            $this->pdf->SetTextColor($color[0], $color[1], $color[2]);
            $this->pdf->Cell($w[1], 6, $typeText, 'LR', 0, 'C');
            $this->pdf->Cell($w[2], 6, number_format($row['amount'], 2), 'LR', 0, 'C');
            
            $this->pdf->SetTextColor(0, 0, 0);
            $this->pdf->Cell($w[3], 6, $row['description'], 'LR', 0, 'R');
            $this->pdf->Cell($w[4], 6, $row['reference'] ?? '', 'LR', 0, 'C');
            $this->pdf->Cell($w[5], 6, $row['transfer_details'] ?? '', 'LR', 0, 'R');
            
            $this->pdf->SetTextColor($currentBalance >= 0 ? 0 : 200, 0, 0);
            $this->pdf->Cell($w[6], 6, number_format($currentBalance, 2), 'LR', 0, 'C');
            $this->pdf->Ln();
        }
        
        // إغلاق الجدول
        $this->pdf->Cell(array_sum($w), 0, '', 'T');
        $this->pdf->Ln(5);

        // عرض الرصيد الختامي
        $this->pdf->SetFont('aealarabiya', 'B', 12);
        $this->pdf->SetTextColor($currentBalance >= 0 ? 0 : 200, 0, 0);
        $this->pdf->Cell(0, 10, 'الرصيد الختامي: ' . number_format($currentBalance, 2) . ' درهم', 0, 1, 'L');

        // إضافة تاريخ الإصدار في أسفل الصفحة
        $this->pdf->SetFont('aealarabiya', '', 8);
        $this->pdf->SetTextColor(128, 128, 128);
        $this->pdf->Cell(0, 10, 'تم إصدار هذا الكشف بتاريخ ' . date('d/m/Y H:i'), 0, 0, 'C');

        // إرجاع ملف PDF
        return $this->pdf->Output('كشف_حساب.pdf', 'S');
    }

    private function getTransactionTypeText($type) {
        switch ($type) {
            case 'deposit':
                return 'إيداع';
            case 'withdrawal':
                return 'سحب';
            case 'transfer_out':
                return 'تحويل صادر';
            case 'transfer_in':
                return 'تحويل وارد';
            default:
                return $type;
        }
    }
}
