<?php
// 1. تفعيل التخزين المؤقت للمخرجات لمنع خطأ Headers Already Sent
ob_start(); 

require_once('../config/db.php');

// 2. جلب دالة الترجمة واللغة - ملاحظة: الهيدر سيقوم بإنتاج HTML خلف الكواليس ولكن ob_start ستخزنه ولن ترسل للمتصفح
require_once('../includes/header.php'); 
require_once('../vendor/autoload.php');

use Mpdf\Mpdf;

if (!isset($_GET['payment_id'])) {
    ob_end_clean();
    die(__('error_payment_id_missing'));
}

$payment_id = (int) $_GET['payment_id'];

// 3. جلب بيانات الدفعة الحالية وبيانات الطالب
$stmt = $conn->prepare("SELECT 
    p.amount_paid, p.discount, p.payment_date, p.payment_method, p.student_id,
    s.full_name, s.phone, s.address
    FROM payments p
    JOIN students s ON p.student_id = s.id
    WHERE p.id = ?");
$stmt->execute([$payment_id]);
$data = $stmt->fetch();

if (!$data) {
    ob_end_clean();
    die(__('error_payment_not_found'));
}

$student_id = $data['student_id'];

// 4. حساب إجمالي سعر الدورات المسجل بها الطالب
$stmtPrice = $conn->prepare("SELECT SUM(c.price) as total_required FROM enrollments e JOIN courses c ON e.course_id = c.id WHERE e.student_id = ?");
$stmtPrice->execute([$student_id]);
$totalRequired = $stmtPrice->fetch()['total_required'] ?? 0;

// 5. حساب إجمالي ما تم دفعه + الخصومات السابقة والحالية
$stmtPaid = $conn->prepare("SELECT (SUM(amount_paid) + SUM(discount)) as total_processed FROM payments WHERE student_id = ?");
$stmtPaid->execute([$student_id]);
$totalProcessed = $stmtPaid->fetch()['total_processed'] ?? 0;

// 6. حساب المتبقي النهائي
$remainingAmount = $totalRequired - $totalProcessed;
if ($remainingAmount < 0) $remainingAmount = 0;

// تصميم الـ HTML - نستخدم دالة __() داخل النصوص
$html = '
<html lang="' . $lang . '" dir="' . $dir . '">
<head>
<meta charset="UTF-8">
<style>
    body { font-family: "dejavusans", sans-serif; direction: ' . $dir . '; color: #333; margin: 0; padding: 0; }
    .receipt-container { 
        border: 2px solid #1e40af; 
        padding: 20px; 
        border-radius: 10px;
        position: relative;
    }
    .header-table { width: 100%; border-bottom: 2px solid #1e40af; padding-bottom: 10px; }
    .header-info h2 { color: #1e40af; margin: 0; font-size: 22px; }
    
    .details-table { width: 100%; margin: 15px 0; border: none; }
    .details-table td { padding: 5px; font-size: 14px; border: none; }
    .label { color: #1e40af; font-weight: bold; width: 100px; }

    .payment-table { width: 100%; border-collapse: collapse; }
    .payment-table th { background-color: #1e40af; color: white; padding: 10px; font-size: 13px; }
    .payment-table td { border: 1px solid #e2e8f0; padding: 10px; text-align: center; font-size: 14px; }
    
    .amount-row { background-color: #f8fafc; font-weight: bold; }
    .remaining-row { background-color: #fef2f2; color: #b91c1c; font-weight: bold; font-size: 16px; }
    
    .footer { margin-top: 30px; width: 100%; }
    .sig-box { text-align: center; font-size: 12px; }
    .sig-line { border-top: 1px solid #333; width: 120px; margin: 10px auto; padding-top: 5px; }
</style>
</head>
<body>
<div class="receipt-container">
    <table class="header-table">
        <tr>
            <td>
                <h2>' . __('institute_name') . '</h2>
                <p style="margin: 0; font-size: 12px;">' . __('receipt_voucher_no') . ': <b>#' . $payment_id . '</b> | ' . __('date_label') . ': ' . date('Y-m-d', strtotime($data['payment_date'])) . '</p>
            </td>
            <td style="text-align: left;">
                <img src="../assets/logo.png" style="height: 70px; border-radius: 50%;">
            </td>
        </tr>
    </table>

    <table class="details-table">
        <tr>
            <td class="label">' . __('student_name_label') . ':</td>
            <td colspan="3"><b>' . htmlspecialchars($data['full_name']) . '</b></td>
        </tr>
        <tr>
            <td class="label">' . __('payment_method_label') . ':</td>
            <td>' . __($data['payment_method']) . '</td>
            <td class="label">' . __('branch_label') . ':</td>
            <td>' . __($data['address'] ?: 'default_city') . '</td>
        </tr>
    </table>

    <table class="payment-table">
        <thead>
            <tr>
                <th>' . __('statement_label_table') . '</th>
                <th>' . __('value_label') . ' (' . __('currency_symbol') . ')</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td style="text-align: right;">' . __('current_paid_amount') . '</td>
                <td>' . number_format($data['amount_paid'], 2) . '</td>
            </tr>
            <tr>
                <td style="text-align: right;">' . __('granted_discount') . '</td>
                <td>' . number_format($data['discount'], 2) . '</td>
            </tr>
            <tr class="remaining-row">
                <td style="text-align: right;">' . __('remaining_balance_on_student') . '</td>
                <td>' . number_format($remainingAmount, 2) . '</td>
            </tr>
        </tbody>
    </table>

    <div class="footer">
        <table style="width: 100%;">
            <tr>
                <td class="sig-box"><div class="sig-line">' . __('accountant_signature_label') . '</div></td>
                <td class="sig-box" style="font-size: 10px; color: #666;">' . __('printed_at') . ': ' . date('Y-m-d H:i') . '</td>
                <td class="sig-box"><div class="sig-line">' . __('academy_stamp_label') . '</div></td>
            </tr>
        </table>
    </div>
</div>
</body>
</html>
';

$mpdf = new Mpdf([
    'mode' => 'utf-8',
    'format' => 'A5-L', 
    'default_font' => 'dejavusans',
    'margin_left' => 5,
    'margin_right' => 5,
    'margin_top' => 5,
    'margin_bottom' => 5,
]);

$mpdf->SetDirectionality($dir);
$mpdf->WriteHTML($html);

$pdfFileName = "Receipt_" . $payment_id . ".pdf";
$pdfPath = __DIR__ . "/../receipts/{$pdfFileName}";

// إنشاء المجلد إذا لم يكن موجوداً
if (!file_exists(__DIR__ . "/../receipts/")) {
    mkdir(__DIR__ . "/../receipts/", 0777, true);
}

$mpdf->Output($pdfPath, \Mpdf\Output\Destination::FILE);

$domain = (isset($_SERVER['HTTPS']) ? "https://" : "http://") . $_SERVER['HTTP_HOST']; 
$pdfUrl = "{$domain}/receipts/{$pdfFileName}";

// معالجة رقم الهاتف
$rawPhone = preg_replace('/[^0-9]/', '', $data['phone']);
$phone = ltrim($rawPhone, '0');
if (strlen($phone) == 9) $phone = "962" . $phone;

// استخدام قالب رسالة واتساب مترجم
$wa_message = str_replace(
    ['{name}', '{remaining}', '{url}'],
    [$data['full_name'], number_format($remainingAmount, 2), $pdfUrl],
    __('whatsapp_receipt_msg_template')
);

$wa_link = "https://wa.me/{$phone}?text=" . urlencode($wa_message);

// 7. تنظيف الذاكرة المؤقتة تماماً لضمان عدم وجود أي مخرجات نصية
ob_end_clean(); 

// 8. التوجه الآن للواتساب بدون أخطاء
header("Location: $wa_link");
exit;