<?php
// البدء بجلب ملفات اللغة والترجمة (تأكد من وجود المسار الصحيح)
require_once('../config/db.php');
require_once('../includes/header.php'); // أو الملف الذي يحتوي على دالة __()
require_once('../vendor/autoload.php'); 

use Dompdf\Dompdf;
use Dompdf\Options;

if (!isset($_GET['student_id'])) {
    die(__('error_student_id_missing'));
}

$student_id = (int) $_GET['student_id'];

// جلب بيانات الطالب
$stmt = $conn->prepare("SELECT full_name, phone, address FROM students WHERE id = ?");
$stmt->execute([$student_id]);
$student = $stmt->fetch();

if (!$student) {
    die(__('error_student_not_found'));
}

// جلب المدفوعات
$stmt = $conn->prepare("SELECT amount_paid, discount, payment_date, payment_method FROM payments WHERE student_id = ? ORDER BY payment_date DESC");
$stmt->execute([$student_id]);
$payments = $stmt->fetchAll();

// حساب الإجماليات للعرض في السند
$total_paid = 0;
foreach($payments as $p) { $total_paid += $p['amount_paid']; }

ob_start();
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <style>
        body { font-family: 'dejavu sans', sans-serif; direction: rtl; color: #333; line-height: 1.6; }
        .receipt-box { border: 2px solid #1e40af; padding: 20px; border-radius: 10px; }
        .header { text-align: center; border-bottom: 2px solid #1e40af; padding-bottom: 15px; margin-bottom: 20px; }
        .header h1 { color: #1e40af; margin: 5px 0; font-size: 22px; }
        .header p { margin: 0; color: #666; font-size: 12px; }
        
        .info-table { width: 100%; margin-bottom: 20px; border: none; }
        .info-table td { border: none; text-align: right; padding: 5px; font-size: 14px; }
        
        .main-table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        .main-table th { background-color: #1e40af; color: white; padding: 10px; font-size: 13px; border: 1px solid #1e40af; }
        .main-table td { border: 1px solid #ddd; padding: 10px; text-align: center; font-size: 12px; }
        .main-table tr:nth-child(even) { background-color: #f9fafb; }
        
        .summary { margin-top: 20px; text-align: left; }
        .summary-box { display: inline-block; background: #f0f7ff; border: 1px solid #1e40af; padding: 10px 20px; border-radius: 5px; }
        .summary-box b { color: #1e40af; font-size: 16px; }

        .footer { margin-top: 50px; }
        .sig-section { width: 100%; }
        .sig-section td { width: 50%; text-align: center; vertical-align: bottom; }
        .sig-line { width: 150px; border-bottom: 1px solid #000; margin: 10px auto; height: 30px; }
    </style>
</head>
<body>

    <div class="receipt-box">
        <div class="header">
            <h1><?= __('institute_name') ?></h1>
            <p><?= __('pdf_statement_subtitle') ?></p>
        </div>

        <table class="info-table">
            <tr>
                <td><?= __('student_label') ?>: <strong><?= htmlspecialchars($student['full_name']) ?></strong></td>
                <td style="text-align: left;"><?= __('issue_date_label') ?>: <?= date('Y-m-d') ?></td>
            </tr>
            <tr>
                <td><?= __('address_label') ?>: <?= htmlspecialchars($student['address'] ?? __('default_city')) ?></td>
                <td style="text-align: left;"><?= __('phone_label') ?>: <?= htmlspecialchars($student['phone']) ?></td>
            </tr>
        </table>

        <table class="main-table">
            <thead>
                <tr>
                    <th width="10%">#</th>
                    <th width="30%"><?= __('amount_paid_label') ?></th>
                    <th width="20%"><?= __('discount_label_table') ?></th>
                    <th width="20%"><?= __('date_label') ?></th>
                    <th width="20%"><?= __('payment_method_label') ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($payments as $i => $p): ?>
                <tr>
                    <td><?= $i + 1 ?></td>
                    <td style="font-weight: bold; color: #1e40af;"><?= number_format($p['amount_paid'], 2) ?> <?= __('currency_symbol') ?></td>
                    <td style="color: #b45309;"><?= number_format($p['discount'], 2) ?> <?= __('currency_symbol') ?></td>
                    <td><?= htmlspecialchars($p['payment_date']) ?></td>
                    <td><?= htmlspecialchars($p['payment_method']) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="summary">
            <div class="summary-box">
                <?= __('total_paid_label') ?>: <b><?= number_format($total_paid, 2) ?> <?= __('currency_symbol') ?></b>
            </div>
        </div>

        <div class="footer">
            <table class="sig-section">
                <tr>
                    <td>
                        <p><?= __('accountant_signature_label') ?></p>
                        <div class="sig-line"></div>
                    </td>
                    <td>
                        <p><?= __('official_stamp_label') ?></p>
                        <div class="sig-line"></div>
                    </td>
                </tr>
            </table>
        </div>
    </div>

</body>
</html>

<?php
$html = ob_get_clean();

// إعدادات Dompdf
$options = new Options();
$options->set('isRemoteEnabled', true);
$options->set('defaultFont', 'dejavu sans'); 
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

// حفظ الملف
$pdfFileName = "Statement_{$student_id}_" . time() . ".pdf";
$pdfPath = __DIR__ . "/../receipts/{$pdfFileName}";
file_put_contents($pdfPath, $dompdf->output());

// إعداد الرابط
$domain = (isset($_SERVER['HTTPS']) ? "https://" : "http://") . $_SERVER['HTTP_HOST']; 
$pdfUrl = "{$domain}/receipts/{$pdfFileName}";

// تجهيز رسالة الواتساب
$rawPhone = preg_replace('/[^0-9]/', '', $student['phone']);
$phone = ltrim($rawPhone, '0'); 
if (strlen($phone) == 9) $phone = "962" . $phone; 

// استخدام القوالب المترجمة لرسالة الواتساب
$wa_message = str_replace(
    ['{name}', '{url}'],
    [$student['full_name'], $pdfUrl],
    __('whatsapp_statement_msg_template')
);

$wa_link = "https://wa.me/{$phone}?text={$wa_message}";

header("Location: $wa_link");
exit;