<?php
session_start();
if (!isset($_SESSION['user'])) {
    header("Location: ../auth/login.php");
    exit;
}
require_once('../config/db.php');

// استدعاء الهيدر لتعريف دالة الترجمة والمتغيرات الأساسية
include('../includes/header.php'); 

if (!isset($_GET['student_id'])) {
    die(__('error_student_id_missing'));
}

$student_id = (int)$_GET['student_id'];

// جلب بيانات الطالب
$stmt = $conn->prepare("SELECT full_name, phone FROM students WHERE id = ?");
$stmt->execute([$student_id]);
$student = $stmt->fetch();
if (!$student) {
    die(__('error_student_not_found'));
}

// جلب المدفوعات
$stmt = $conn->prepare("SELECT id, 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;
$total_discount = 0;
foreach($payments as $p) { 
    $total_paid += $p['amount_paid']; 
    $total_discount += $p['discount'];
}
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" />
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">

<style>
    body { font-family: 'Cairo', sans-serif; background-color: #f8fafc; overflow-x: hidden; }
    
    /* متجاوب مع الجوال */
    .table-responsive { 
        width: 100%; 
        overflow-x: auto; 
        -webkit-overflow-scrolling: touch; 
        background: white; 
        border-radius: 15px;
    }

    #paymentsTable { min-width: 800px; width: 100% !important; border-collapse: collapse !important; }
    #paymentsTable th, #paymentsTable td { text-align: <?= $dir == 'rtl' ? 'right' : 'left' ?> !important; padding: 15px !important; white-space: nowrap; }
    
    .table-header { background-color: #4f46e5; color: white; }

    /* ستايل الترقيم */
    .dataTables_wrapper .dataTables_paginate { display: flex !important; justify-content: center; gap: 8px; margin-top: 25px; }
    .dataTables_wrapper .dataTables_paginate .paginate_button { 
        background: #fff !important; border: 1px solid #e2e8f0 !important; border-radius: 10px !important; 
        padding: 6px 14px !important; color: #4f46e5 !important; font-weight: 700 !important; cursor: pointer; 
    }
    .dataTables_wrapper .dataTables_paginate .paginate_button.current { background: #4f46e5 !important; color: white !important; }
    .dataTables_filter { display: none; }

    @media print { 
        .no-print, nav, footer { display: none !important; } 
        body { background: white !important; }
        .max-w-7xl { max-width: 100% !important; }
        .table-responsive { overflow: visible !important; }
        #paymentsTable { min-width: 100% !important; }
    }
</style>

<?php include('../includes/navbar.php'); ?>

<div class="min-h-screen pb-16" dir="<?= $dir ?>">
    <div class="max-w-7xl mx-auto py-10 px-4 sm:px-6 lg:px-8">

        <div class="bg-white shadow-xl rounded-2xl p-6 mb-8 border-b-8 border-indigo-600/50">
            <div class="flex flex-col md:flex-row md:justify-between md:items-center gap-6">
                <div>
                    <h2 class="text-3xl font-extrabold text-gray-800">
                        <i class="fas fa-file-invoice-dollar text-indigo-500 <?= $dir == 'rtl' ? 'ml-3' : 'mr-3' ?>"></i> <?= __('payments_log_title') ?>
                    </h2>
                    <div class="flex items-center mt-2">
                        <span class="bg-indigo-100 text-indigo-700 px-3 py-1 rounded-full text-sm font-bold">
                             <?= __('student_label') ?>: <?= htmlspecialchars($student['full_name']) ?>
                        </span>
                        <span class="<?= $dir == 'rtl' ? 'mr-3' : 'ml-3' ?> text-xs text-gray-400 font-bold italic no-print">
                            <?= __('payment_date_label') ?>: <?php echo date('Y-m-d'); ?>
                        </span>
                    </div>
                </div>
                
                <div class="flex flex-wrap gap-4">
                    <div class="bg-emerald-50 px-6 py-3 rounded-2xl border border-emerald-100 text-center flex-1 md:flex-none">
                        <p class="text-xs text-emerald-500 font-bold mb-1"><?= __('total_paid') ?></p>
                        <p class="text-xl font-black text-emerald-700"><?= number_format($total_paid, 2) ?> <span class="text-xs font-normal"><?= __('currency_symbol') ?></span></p>
                    </div>
                    <div class="bg-orange-50 px-6 py-3 rounded-2xl border border-orange-100 text-center flex-1 md:flex-none">
                        <p class="text-xs text-orange-500 font-bold mb-1"><?= __('total_discount') ?></p>
                        <p class="text-xl font-black text-orange-700"><?= number_format($total_discount, 2) ?> <span class="text-xs font-normal"><?= __('currency_symbol') ?></span></p>
                    </div>
                </div>
            </div>
        </div>

        <div class="bg-white shadow-xl rounded-xl p-6 mb-8 border-t-4 border-indigo-400 no-print">
            <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div class="relative flex-1">
                    <span class="absolute inset-y-0 <?= $dir == 'rtl' ? 'right-0 pr-3' : 'left-0 pl-3' ?> flex items-center text-gray-400">
                        <i class="fas fa-search"></i>
                    </span>
                    <input type="text" id="paymentSearch" placeholder="<?= __('search_payments_placeholder') ?>" class="w-full border-gray-200 rounded-xl text-sm py-3 <?= $dir == 'rtl' ? 'pr-10' : 'pl-10' ?> focus:ring-2 focus:ring-indigo-500 outline-none shadow-sm transition">
                </div>
                
                <div class="flex gap-2 w-full md:w-auto">
                    <button onclick="printReceipt()" class="flex-1 md:flex-none bg-indigo-600 hover:bg-indigo-700 text-white py-3 px-6 rounded-xl text-sm font-bold shadow-md transition">
                        <i class="fas fa-print <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('print_statement') ?>
                    </button>
                    <a href="report.php" class="flex-1 md:flex-none bg-gray-200 hover:bg-gray-300 text-gray-800 py-3 px-6 rounded-xl text-sm font-bold transition text-center">
                         <?= __('back_btn') ?>
                    </a>
                </div>
            </div>
        </div>

        <div class="table-responsive shadow-xl">
            <table id="paymentsTable" class="w-full">
                <thead class="table-header">
                    <tr>
                        <th class="<?= $dir == 'rtl' ? 'rounded-tr-xl' : 'rounded-tl-xl' ?>"><?= __('payment_date_label') ?></th>
                        <th class="text-center"><?= __('amount_label') ?></th>
                        <th class="text-center"><?= __('discount_label_table') ?></th>
                        <th class="text-center"><?= __('payment_method_label') ?></th>
                        <th class="<?= $dir == 'rtl' ? 'rounded-tl-xl' : 'rounded-tr-xl' ?> text-center no-print"><?= __('actions_label') ?></th>
						
						
						
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100 text-sm">
                    <?php foreach ($payments as $payment): ?>
                        <tr class="hover:bg-indigo-50/50 transition">
                            <td class="font-bold text-gray-700">
                                <i class="far fa-calendar-alt <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?> text-indigo-400"></i>
                                <?= htmlspecialchars($payment['payment_date']) ?>
                            </td>
                            <td class="text-center text-emerald-600 font-black text-lg"><?= number_format($payment['amount_paid'], 2) ?></td>
                            <td class="text-center text-orange-500 font-bold"><?= number_format($payment['discount'], 2) ?></td>
                           <td class="text-center align-middle">
    <?php 
        $method = $payment['payment_method'];
        
        // جلب الترجمة باستخدام الدالة التي تستخدمها في مشروعك
        // سنفترض أن الدالة __ تتعامل مع المفاتيح (Cash, Visa, etc.)
        $translated_method = __($method);

        // نظام الألوان الديناميكي لإعطاء "روح" للجدول
        $method_styles = [
            'Cash'          => 'bg-emerald-50 text-emerald-700 border-emerald-200 hover:bg-emerald-600',
            'Visa'          => 'bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-600',
            'CliQ'          => 'bg-purple-50 text-purple-700 border-purple-200 hover:bg-purple-600',
            'Bank Transfer' => 'bg-amber-50 text-amber-700 border-amber-200 hover:bg-amber-600'
        ];
        
        $current_style = $method_styles[$method] ?? 'bg-gray-50 text-gray-700 border-gray-200 hover:bg-gray-600';
    ?>
    
    <span class="inline-flex items-center justify-center px-3 py-1.5 rounded-full text-[10px] font-black border transition-all duration-300 cursor-default shadow-sm hover:text-white <?= $current_style ?>">
        <i class="fas fa-wallet <?= $dir == 'rtl' ? 'ml-1.5' : 'mr-1.5' ?> text-[11px]"></i> 
        <?= htmlspecialchars($translated_method) ?>
    </span>
</td>
                            <td class="no-print">
                                <div class="flex justify-center gap-1">
                                    <a href="edit_payment.php?payment_id=<?= $payment['id'] ?>&student_id=<?= $student_id ?>" 
                                       title="<?= __('edit_btn') ?>" class="bg-blue-500 text-white w-9 h-9 flex items-center justify-center rounded-xl hover:bg-blue-600 transition shadow-sm">
                                         <i class="fas fa-edit text-xs"></i>
                                    </a>
                                    
                                    <button onclick="printSingleReceipt(<?= $payment['id'] ?>)" 
                                            title="<?= __('print_receipt_btn') ?>" class="bg-emerald-500 text-white w-9 h-9 flex items-center justify-center rounded-xl hover:bg-emerald-600 transition shadow-sm">
                                         <i class="fas fa-receipt text-xs"></i>
                                    </button>

                                    <a href="generate_single_receipt_pdf.php?payment_id=<?= $payment['id'] ?>" target="_blank"
                                       title="<?= __('whatsapp_btn') ?>" class="bg-green-500 text-white w-9 h-9 flex items-center justify-center rounded-xl hover:bg-green-600 transition shadow-sm">
                                         <i class="fab fa-whatsapp text-sm"></i>
                                    </a>

                                    <form action="delete_payment.php" method="POST" onsubmit="return confirm('<?= __('confirm_delete_msg') ?>');" class="inline">
                                        <input type="hidden" name="payment_id" value="<?= $payment['id'] ?>">
                                        <input type="hidden" name="student_id" value="<?= $student_id ?>">
                                        <button type="submit" title="<?= __('delete_btn') ?>" class="bg-red-500 text-white w-9 h-9 flex items-center justify-center rounded-xl hover:bg-red-600 transition shadow-sm">
                                            <i class="fas fa-trash text-xs"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <p class="md:hidden text-center text-[10px] text-gray-400 mt-4"><?= __('scroll_hint') ?></p>
    </div>
</div>

<div id="receipt-content" class="hidden">
    <div dir="<?= $dir ?>" style="font-family: 'Cairo', sans-serif; padding: 40px;">
        <div style="text-align: center; border-bottom: 2px solid #4f46e5; padding-bottom: 20px; margin-bottom: 20px;">
            <h2 style="color: #1e40af; margin: 0; font-size: 28px;"><?= __('institute_name') ?></h2>
            <p style="color: #64748b;"><?= __('account_statement_for') ?>: <?= htmlspecialchars($student['full_name']) ?></p>
            <p style="font-size: 12px; color: #94a3b8;"><?= __('report_date_label') ?>: <?= date('Y-m-d') ?></p>
        </div>
        <table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
            <thead>
                <tr style="background-color: #f8fafc;">
                    <th style="border: 1px solid #e2e8f0; padding: 12px; text-align: <?= $dir == 'rtl' ? 'right' : 'left' ?>;"><?= __('payment_date_label') ?></th>
                    <th style="border: 1px solid #e2e8f0; padding: 12px; text-align: center;"><?= __('amount_paid_label') ?></th>
                    <th style="border: 1px solid #e2e8f0; padding: 12px; text-align: center;"><?= __('discount_label_table') ?></th>
                    <th style="border: 1px solid #e2e8f0; padding: 12px; text-align: <?= $dir == 'rtl' ? 'right' : 'left' ?>;"><?= __('payment_method_label') ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($payments as $p): ?>
                <tr>
                    <td style="border: 1px solid #e2e8f0; padding: 10px; text-align: <?= $dir == 'rtl' ? 'right' : 'left' ?>;"><?= $p['payment_date'] ?></td>
                    <td style="border: 1px solid #e2e8f0; padding: 10px; text-align: center; font-weight: bold;"><?= number_format($p['amount_paid'], 2) ?> <?= __('currency_symbol') ?></td>
                    <td style="border: 1px solid #e2e8f0; padding: 10px; text-align: center; color: orange;"><?= number_format($p['discount'], 2) ?></td>
<td style="border: 1px solid #e2e8f0; padding: 10px; text-align: <?= $dir == 'rtl' ? 'right' : 'left' ?>;">
    <span style="font-weight: bold; color: #475569;">
        <?php 
            // استخدام الدالة __ لترجمة وسيلة الدفع (Cash -> نقداً / Nakit)
            echo __($p['payment_method']); 
        ?>
    </span>
</td>                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <div style="margin-top: 30px; text-align: <?= $dir == 'rtl' ? 'left' : 'right' ?>; padding: 15px; background: #f8fafc; border-radius: 10px;">
            <p style="margin: 5px 0;"><?= __('total_paid') ?>: <strong><?= number_format($total_paid, 2) ?> <?= __('currency_symbol') ?></strong></p>
            <p style="margin: 5px 0;"><?= __('total_discount') ?>: <strong><?= number_format($total_discount, 2) ?> <?= __('currency_symbol') ?></strong></p>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

<script>
$(document).ready(function() {
    var table = $('#paymentsTable').DataTable({
        autoWidth: false,
        language: {
            "sInfo": "<?= __('dt_info_payments') ?>",
            "oPaginate": { 
                "sNext": "<?= $dir == 'rtl' ? '<i class=\'fas fa-chevron-left\'></i>' : '<i class=\'fas fa-chevron-right\'></i>' ?>", 
                "sPrevious": "<?= $dir == 'rtl' ? '<i class=\'fas fa-chevron-right\'></i>' : '<i class=\'fas fa-chevron-left\'></i>' ?>" 
            }
        },
        pageLength: 10,
        dom: 'rt<"bottom-info"i><"bottom-pagination"p>'
    });
    
    $('#paymentSearch').on('keyup', function() { table.search(this.value).draw(); });
});

function printReceipt() {
    const content = document.getElementById('receipt-content').innerHTML;
    const win = window.open('', '', 'height=800,width=900');
    win.document.write('<html><head><title><?= __('account_statement') ?></title>');
    win.document.write('<link href="https://fonts.googleapis.com/css2?family=Cairo&display=swap" rel="stylesheet">');
    win.document.write('<style>body{font-family:"Cairo",sans-serif;direction:<?= $dir ?>;padding:20px;}</style>');
    win.document.write('</head><body>' + content + '</body></html>');
    win.document.close();
    setTimeout(() => { win.print(); }, 700);
}

function printSingleReceipt(paymentId) {
    const url = `print_single_receipt.php?payment_id=${paymentId}`;
    const win = window.open(url, '_blank', 'height=800,width=900');
    if (!win) alert("<?= __('allow_popups_msg') ?>");
}
</script>

<?php include('../includes/footer.php'); ?>