<?php
session_start();
if (!isset($_SESSION['user'])) {
    header("Location: ../auth/login.php");
    exit;
}

require_once('../config/db.php');
// جلب ملفات اللغة والترجمة - تم إبقاء الهيدر لتعمل دالة __()
require_once('../includes/header.php'); 
require_once('../libs/phpqrcode/qrlib.php');

if (!isset($_GET['payment_id'])) {
    die(__('error_payment_id_missing'));
}

$payment_id = (int)$_GET['payment_id'];

// جلب بيانات الدفع والطالب
$stmt = $conn->prepare("
    SELECT 
        p.amount_paid, 
        p.discount AS payment_discount, 
        p.payment_date, 
        p.payment_method,
        s.full_name,
        s.address,
        s.id AS student_id
    FROM payments p
    JOIN students s ON p.student_id = s.id
    WHERE p.id = ?
    LIMIT 1
");
$stmt->execute([$payment_id]);
$payment = $stmt->fetch();

if (!$payment) {
    die(__('error_payment_not_found'));
}

// حساب الإجمالي والمتبقي
$totalCoursePriceStmt = $conn->prepare("SELECT SUM(c.price) AS total FROM enrollments e JOIN courses c ON e.course_id = c.id WHERE e.student_id = ?");
$totalCoursePriceStmt->execute([$payment['student_id']]);
$totalCoursesPrice = $totalCoursePriceStmt->fetch()['total'] ?? 0;

$totalPaidStmt = $conn->prepare("SELECT SUM(amount_paid) AS total_paid, SUM(discount) AS total_discount FROM payments WHERE student_id = ?");
$totalPaidStmt->execute([$payment['student_id']]);
$paidData = $totalPaidStmt->fetch();
$totalPaid = $paidData['total_paid'] ?? 0;
$totalDiscount = $paidData['total_discount'] ?? 0;

$totalRemaining = $totalCoursesPrice - ($totalPaid + $totalDiscount);
if ($totalRemaining < 0) $totalRemaining = 0;

$courses_stmt = $conn->prepare("SELECT c.course_name, c.price, e.attendance_type FROM enrollments e JOIN courses c ON e.course_id = c.id WHERE e.student_id = ?");
$courses_stmt->execute([$payment['student_id']]);
$enrolled_courses = $courses_stmt->fetchAll();

// توليد QR
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$full_url = "$protocol://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
ob_start();
QRcode::png($full_url, null, QR_ECLEVEL_L, 4);
$imageString = base64_encode(ob_get_contents());
ob_end_clean();
?>

<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
    <meta charset="UTF-8" />
    <title><?= __('receipt_voucher_no') ?> #<?= $payment_id ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet" />
    <style>
        /* كود إضافي لإخفاء عناصر الهيدر العام لضمان نظافة السند */
        header, .navbar, .language-switcher, .top-nav { display: none !important; }

        body {
            font-family: 'Cairo', sans-serif;
            background-color: #f3f4f6;
            margin: 0;
            padding: 40px 20px;
        }
        .receipt-container {
            background: #fff;
            max-width: 800px;
            margin: auto;
            border: 1px solid #e5e7eb;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
            position: relative;
            overflow: hidden;
            border-radius: 8px;
        }
        .receipt-container::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 8px;
            background: linear-gradient(to right, #1e40af, #3b82f6);
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 30px;
            border-bottom: 2px dashed #e5e7eb;
        }
        .header-info h1 {
            margin: 0;
            font-size: 24px;
            color: #1e40af;
            font-weight: 700;
        }
        .header-info p {
            margin: 5px 0 0;
            color: #64748b;
            font-size: 14px;
        }
        .logo img {
            height: 80px;
            width: 80px;
            object-fit: cover;
            border-radius: 50%;
            border: 2px solid #1e40af;
        }
        .content {
            padding: 30px;
        }
        .top-meta {
            display: flex;
            justify-content: space-between;
            margin-bottom: 25px;
            background: #f8fafc;
            padding: 15px;
            border-radius: 8px;
            border: 1px solid #f1f5f9;
        }
        .meta-item b { color: #1e40af; }

        .details-section {
            margin-bottom: 20px;
        }
        .section-title {
            font-size: 16px;
            font-weight: 700;
            color: #334155;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
        }
        .section-title::after {
            content: "";
            flex: 1;
            height: 1px;
            background: #e2e8f0;
            margin-<?= $dir == 'rtl' ? 'right' : 'left' ?>: 15px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        th, td {
            padding: 12px;
            text-align: <?= $dir == 'rtl' ? 'right' : 'left' ?>;
            border-bottom: 1px solid #f1f5f9;
            font-size: 14px;
        }
        th {
            background-color: #f8fafc;
            color: #475569;
            font-weight: 600;
        }
        .highlight-row {
            background-color: #eff6ff;
            font-weight: 700;
        }
        .highlight-row td {
            color: #1e40af;
            border-top: 2px solid #dbeafe;
        }

        .footer-receipt {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            padding: 0 30px 40px;
        }
        .signatures {
            flex: 1;
            display: flex;
            justify-content: space-around;
        }
        .sig-box {
            text-align: center;
            width: 150px;
        }
        .sig-line {
            margin-top: 40px;
            border-top: 1px solid #94a3b8;
            padding-top: 5px;
            font-size: 13px;
            color: #64748b;
        }
        .qr-section {
            text-align: center;
        }
        .qr-section img {
            width: 100px;
            height: 100px;
        }
        .qr-text {
            font-size: 10px;
            color: #94a3b8;
            margin-top: 5px;
        }

        @media print {
            body { background: white; padding: 0; }
            .receipt-container { border: none; box-shadow: none; width: 100%; max-width: 100%; }
            .receipt-container::before { height: 12px; }
            header, .navbar, .language-switcher { display: none !important; }
        }
    </style>
</head>
<body>

<div class="receipt-container">
    <div class="header">
        <div class="header-info">
            <h1><?= __('institute_name') ?></h1>
            <p><?= __('receipt_voucher_no') ?>: <span style="color: #b45309;">#<?= $payment_id ?></span></p>
        </div>
        <div class="logo">
            <img src="../assets/logo.png" alt="Logo" />
        </div>
    </div>

    <div class="content">
        <div class="top-meta">
            <div class="meta-item"><b><?= __('voucher_date_label') ?>:</b> <?= date('Y-m-d', strtotime($payment['payment_date'])) ?></div>
            <div class="meta-item"><b><?= __('student_name_label') ?>:</b> <?= htmlspecialchars($payment['full_name']) ?></div>
            <div class="meta-item"><b><?= __('branch_label') ?>:</b> <?= __($payment['address'] ?: 'default_city') ?></div>
        </div>

        <div class="details-section">
            <div class="section-title"><?= __('enrolled_courses_statement') ?></div>
            <table>
                <thead>
                    <tr>
                        <th><?= __('course_name_label') ?></th>
                        <th><?= __('attendance_type_label') ?></th>
                        <th style="text-align: <?= $dir == 'rtl' ? 'left' : 'right' ?>;"><?= __('price_label') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($enrolled_courses as $course): ?>
                    <tr>
                        <td><?= htmlspecialchars($course['course_name']) ?></td>
                        <td><?= __($course['attendance_type']) ?></td>
                        <td style="text-align: <?= $dir == 'rtl' ? 'left' : 'right' ?>;"><?= number_format($course['price'], 2) ?> <?= __('currency_symbol') ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="details-section">
            <div class="section-title"><?= __('payment_details_title') ?></div>
            <table>
                <tbody>
                    <tr>
                        <td><?= __('payment_method_label') ?>: <b><?= __($payment['payment_method'] ?: 'Cash') ?></b></td>
                        <td style="text-align: <?= $dir == 'rtl' ? 'left' : 'right' ?>; color: #64748b;"><?= __('amount_paid_label') ?>:</td>
                        <td style="text-align: <?= $dir == 'rtl' ? 'left' : 'right' ?>; width: 120px; font-weight: bold;"><?= number_format($payment['amount_paid'], 2) ?> <?= __('currency_symbol') ?></td>
                    </tr>
                    <tr>
                        <td><?= __('total_granted_discounts') ?>:</td>
                        <td style="text-align: <?= $dir == 'rtl' ? 'left' : 'right' ?>; color: #64748b;"><?= __('discount_value_label') ?>:</td>
                        <td style="text-align: <?= $dir == 'rtl' ? 'left' : 'right' ?>; font-weight: bold; color: #b45309;"><?= number_format($payment['payment_discount'], 2) ?> <?= __('currency_symbol') ?></td>
                    </tr>
                    <tr class="highlight-row">
                        <td colspan="2" style="text-align: <?= $dir == 'rtl' ? 'left' : 'right' ?>;"><?= __('remaining_balance_on_student') ?>:</td>
                        <td style="text-align: <?= $dir == 'rtl' ? 'left' : 'right' ?>; font-size: 16px;"><?= number_format($totalRemaining, 2) ?> <?= __('currency_symbol') ?></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <div class="footer-receipt">
        <div class="qr-section">
            <img src="data:image/png;base64,<?= $imageString ?>" alt="QR Code">
            <div class="qr-text"><?= __('verified_electronic_receipt') ?></div>
        </div>
        <div class="signatures">
            <div class="sig-box">
                <div class="sig-line"><?= __('receiving_employee_signature') ?></div>
            </div>
            <div class="sig-box">
                <div class="sig-line"><?= __('management_signature_stamp') ?></div>
            </div>
        </div>
    </div>
</div>

<script>
    window.onload = function() {
        window.print();
        window.onafterprint = function() {
            window.close();
        }
    }
</script>

</body>
</html>