@extends('admin.layouts.app')

@section('title', 'Uploaded Transactions Report')
@section('page-title', 'QR Code Transactions ')
@section('breadcrumb', 'Main / Banknote / Transactions')

@section('styles')
<style>
    :root {
        --brand-blue: #0071BC;
        --brand-blue-dk: #005A96;
        --brand-green: #39B54A;
        --brand-blue-lt: rgba(0, 113, 188, 0.08);
        --brand-green-lt: rgba(57, 181, 74, 0.1);
        
        --blue: #1a8fff; --blue-lt: rgba(26,143,255,.10);
        --red: #e74c3c; --red-lt: rgba(231,76,60,.10);
        --gold: #f5a623; --gold-lt: rgba(245,166,35,.10);
        --text: #2c3e50; --text-mid: #546e7a; --muted: #90a4ae;
        --border: #e0e7ef; --white: #fff; --bg: #f0f3f8;
        --sh: 0 2px 10px rgba(0,0,0,.07);
    }

    .breadcrumb-bar { display:flex; align-items:center; gap:6px; font-size:12px; color:var(--muted); margin-bottom:18px; direction: ltr; }
    .breadcrumb-bar a { color:var(--brand-blue); text-decoration:none; font-weight:600; }

    .pg-hdr { display:flex; align-items:center; justify-content:space-between; margin-bottom:20px; direction: ltr; }
    .pg-hdr-l h1 { font-size:20px; font-weight:900; color:var(--text); margin:0; }

    .stats-row { display:grid; grid-template-columns:repeat(4,1fr); gap:14px; margin-bottom:20px; direction: ltr; }
    .mini-stat { background:var(--white); border:1px solid var(--border); border-radius:12px; padding:14px 16px; display:flex; align-items:center; gap:12px; box-shadow:var(--sh); transition: transform 0.2s; }
    .mini-stat:hover { transform: translateY(-3px); }
    .ms-icon { width:42px; height:42px; border-radius:10px; display:flex; align-items:center; justify-content:center; font-size:20px; }
    .ms-val { font-size:20px; font-weight:900; color:var(--text); }
    .ms-lbl { font-size:11px; color:var(--muted); }

    .tbl-card { background:var(--white); border:1px solid var(--border); border-radius:14px; overflow:hidden; box-shadow:var(--sh); direction: ltr; }
    .tbl-toolbar { display:flex; align-items:center; justify-content:space-between; padding:16px 20px; border-bottom:1px solid var(--border); background: linear-gradient(90deg, var(--brand-blue-lt), transparent); }
    
    .data-table { width:100%; border-collapse:collapse; font-size:13px; text-align: left; }
    .data-table thead tr { background:var(--bg); }
    .data-table th { padding:12px 16px; color:var(--text-mid); font-size:11px; font-weight:700; border-bottom:1px solid var(--border); text-transform: uppercase; letter-spacing: 0.5px; }
    .data-table td { padding:13px 16px; border-bottom:1px solid #f3f6fa; vertical-align:middle; }
    
    .amount-cell { font-weight:800; color:var(--brand-blue); font-family: 'Inter', sans-serif; }
    .ref-text { font-size:11px; color:var(--brand-blue); background:var(--brand-blue-lt); padding:3px 8px; border-radius:5px; font-weight:700; border: 1px solid rgba(0, 113, 188, 0.1); }
    
    /* Search & Export Buttons */
    .header-actions { margin-left: auto; display: flex; gap: 10px; }
    .btn-search-trigger {
        background: var(--white);
        border: 1.5px solid var(--brand-blue);
        color: var(--brand-blue);
        padding: 8px 18px;
        border-radius: 10px;
        cursor: pointer;
        font-weight: 700;
        font-size: 13px;
        transition: all 0.3s;
        display: flex;
        align-items: center;
        gap: 8px;
        height: 38px;
    }
    .btn-search-trigger:hover {
        background: var(--brand-blue);
        color: #fff;
        box-shadow: 0 4px 12px rgba(0, 113, 188, 0.25);
    }
    /* Edit Button Styling */
    .btn-edit-action {
        background: var(--brand-blue-lt);
        color: var(--brand-blue);
        border: 1px solid rgba(0, 113, 188, 0.2);
        border-radius: 8px;
        padding: 6px 12px;
        font-weight: 600;
        font-size: 13px;
        cursor: pointer;
        transition: all 0.2s ease;
        display: inline-flex;
        align-items: center;
        gap: 5px;
    }
    .btn-edit-action:hover {
        background: var(--brand-blue) !important;
        color: #fff !important;
        border-color: var(--brand-blue) !important;
        box-shadow: 0 4px 10px rgba(0, 113, 188, 0.25);
    }

    .btn-export {
        border-color: var(--brand-green) !important;
        color: var(--brand-green) !important;
    }
    .btn-export:hover {
        background: var(--brand-green) !important;
        color: #fff !important;
        box-shadow: 0 4px 12px rgba(57, 181, 74, 0.25) !important;
    }

    /* Custom Pagination */
    .pagination-wrap { padding: 20px; border-top: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; background: #fff; direction: ltr; }
    .custom-pagination nav { display: flex; justify-content: center; }
    .custom-pagination .pagination { display: flex; gap: 5px; list-style: none; padding: 0; margin: 0; }
    .custom-pagination .page-item .page-link {
        display: flex; align-items: center; justify-content: center; min-width: 36px; height: 36px; padding: 0 10px;
        border-radius: 8px !important; border: 1px solid var(--border); background: var(--white); color: var(--text-mid);
        font-size: 13px; font-weight: 600; text-decoration: none; transition: all 0.2s;
    }
    .custom-pagination .page-item.active .page-link {
        background: var(--brand-blue) !important; border-color: var(--brand-blue) !important; color: #fff !important; box-shadow: 0 3px 8px rgba(0, 113, 188, 0.3);
    }
    .custom-pagination .page-item.disabled .page-link {
        color: var(--muted); background: #f8f9fa; border-color: var(--border); cursor: not-allowed;
    }
    .custom-pagination .page-item:hover:not(.active):not(.disabled) .page-link {
        background: var(--brand-blue-lt); border-color: var(--brand-blue); color: var(--brand-blue);
    }

    /* ========================================================
       تعديل جذري لزر Save Changes في SweetAlert2 لمنع الاختفاء
       ======================================================== */
    .swal2-styled.swal2-confirm.custom-save-btn {
        background-color: #39B54A !important;
        color: #ffffff !important;
        border: 2px solid #39B54A !important;
        font-weight: 700 !important;
        border-radius: 8px !important;
        padding: 10px 24px !important;
        box-shadow: 0 4px 10px rgba(57, 181, 74, 0.2) !important;
        outline: none !important;
        transition: all 0.2s ease-in-out !important;
    }

    .swal2-styled.swal2-confirm.custom-save-btn:hover {
        background-color: #2e963b !important;
        color: #ffffff !important;
        border-color: #2e963b !important;
        transform: translateY(-2px);
        box-shadow: 0 6px 15px rgba(57, 181, 74, 0.4) !important;
    }

    .swal2-styled.swal2-cancel.custom-cancel-btn {
        background-color: #f1f5f9 !important;
        color: #475569 !important;
        border: 2px solid #cbd5e1 !important;
        font-weight: 600 !important;
        border-radius: 8px !important;
        padding: 10px 20px !important;
        outline: none !important;
        transition: all 0.2s ease-in-out !important;
    }
/* Delete Data Button Hover Styling */
    .btn-delete-trigger {
        border-color: var(--red) !important;
        color: var(--red) !important;
    }
    .btn-delete-trigger:hover {
        background: var(--red) !important;
        color: #fff !important;
        box-shadow: 0 4px 12px rgba(231, 76, 60, 0.25) !important;
    }
    .swal2-styled.swal2-cancel.custom-cancel-btn:hover {
        background-color: #e2e8f0 !important;
        color: #1e293b !important;
        border-color: #94a3b8 !important;
    }
</style>@endsection

@section('content')

<div class="breadcrumb-bar">
    <div style="display: flex; align-items: center; gap: 6px;">
        <a href="{{ route('admin.dashboard') }}"><i class="las la-home"></i> Dashboard</a>
        <i class="las la-angle-right" style="font-size:10px"></i>
        <span>QR Code Transaction </span>
    </div>

    <div class="header-actions">
      
        <button type="button" onclick="showSearchPopup()" class="btn-search-trigger">
            <i class="las la-search"></i> Search
        </button>
          <button type="button" onclick="exportData()" class="btn-search-trigger btn-export">
            <i class="las la-file-excel"></i> Export Excel
        </button>
       @if(auth()->user()->role_id == 1)


       <button type="button" onclick="showDeleteModal()" class="btn-search-trigger btn-delete-trigger">
        <i class="las la-trash"></i> Delete Data
    </button>
    @endif
    </div>
</div>

<div class="pg-hdr">
    <div class="pg-hdr-l">
        <h1>QR Code Transactions</h1>
    </div>
</div>

<div class="stats-row">
    <div class="mini-stat">
        <div class="ms-icon" style="background:var(--brand-blue-lt);color:var(--brand-blue)"><i class="las la-database"></i></div>
        <div>
            <div class="ms-val">{{ number_format($totalCount) }}</div>
            <div class="ms-lbl">Total Transactions</div>
        </div>
    </div>

    <div class="mini-stat">
        <div class="ms-icon" style="background:rgba(26,143,255,.10);color:#1a8fff"><i class="las la-clock"></i></div>
        <div>
            <div class="ms-val">{{ number_format($todayCount) }}</div>
            <div class="ms-lbl">Today's Transactions</div>
        </div>
    </div>

    <div class="mini-stat">
        <div class="ms-icon" style="background:var(--brand-green-lt);color:var(--brand-green)"><i class="las la-server"></i></div>
        <div>
            <div class="ms-val">{{ $uniqueTerminals }}</div>
            <div class="ms-lbl">Active Terminals</div>
        </div>
    </div>

    <div class="mini-stat">
        <div class="ms-icon" style="background:var(--red-lt);color:var(--red)"><i class="las la-wallet"></i></div>
        <div>
            <div class="ms-val" style="font-size:16px">{{ number_format($todayAmount, 0) }}</div>
            <div class="ms-lbl">Total Amount</div>
        </div>
    </div>
</div>

<div class="tbl-card">
    <div class="tbl-toolbar">
        <div style="font-weight:800;font-size:14px;color:var(--brand-blue)"><i class="las la-list"></i> Transaction Details</div>
    </div>
    
    <div style="overflow-x:auto">
        <table class="data-table" id="transTable">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Day</th>         
                    <th>Date & Month</th> 
                    <th>Year & Time</th>        
                    <th>Terminal ID</th>
                    <th>Terminal Name</th>
                    <th>Amount</th>
                    <th>Mobile No.</th>
                    <th>System Reference</th>
                    <th>Upload Date</th>
               @if(auth()->user()->role_id == 1)

                    <th>Actions</th> 
                    @endif
                </tr>
            </thead>
            <tbody>
                @forelse($transactions as $transaction)
                @php
                    $dt = null;
                    try {
                        $dt = \Carbon\Carbon::parse($transaction->transaction_date);
                    } catch (\Exception $e) {
                        $dt = null;
                    }
                @endphp
                <tr>
                    <td><small class="text-muted">#{{ $transaction->id }}</small></td>
                    <td style="font-weight:700; color: var(--text);">{{ $transaction->day }}</td>
                    <td style="font-weight:600;">{{ $transaction->transaction_date }}</td>
                    <td class="text-muted">{{ $transaction->year_time }}</td>
                    <td>{{ $transaction->terminal_id }}</td>
                    <td style="font-weight:500;">{{ $transaction->terminal_name }}</td>
                    <td class="amount-cell">{{ number_format($transaction->amount, 2) }}</td>
                    <td>{{ $transaction->mobile }}</td>
                    <td><span class="ref-text">{{ $transaction->system_reference }}</span></td>
                    <td style="font-size:14px;color:var(--muted)">{{ $transaction->created_at->format('Y-m-d H:i') }}</td>
                @if(auth()->user()->role_id == 1)


                    <td>
                        <button type="button" class="btn-edit-action" onclick="editTransaction({{ json_encode($transaction) }})">
                            <i class="las la-edit"></i> 
                        </button>
                        <button type="button" class="btn-edit-action" style="background: var(--red-lt); color: var(--red); border-color: rgba(231,76,60,0.2);" onclick="deleteTransaction({{ $transaction->id }})">
            <i class="las la-trash"></i>
        </button>
                    </td>
                    @endif
                </tr>
                @empty
                <tr>
                    <td colspan="11" style="text-align:center;padding:50px;color:var(--muted)">
                        <i class="las la-folder-open" style="font-size:40px; display:block; margin-bottom:10px;"></i>
                        No transactions found.
                    </td>
                </tr>
                @endforelse
            </tbody>
        </table>
    </div>

    @if($transactions->hasPages())
    <div class="pagination-wrap">
        <div style="font-size:12px;color:var(--muted)">
            Showing <b>{{ $transactions->firstItem() }}</b> to <b>{{ $transactions->lastItem() }}</b> of <b>{{ $transactions->total() }}</b> entries
        </div>
        <div class="custom-pagination">
           {{ $transactions->appends(request()->query())->links('pagination::bootstrap-4') }}
        </div>
    </div>
    @endif
</div>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
function showSearchPopup() {
    Swal.fire({
        title: 'Filter Transactions',
        html: `
            <form id="searchForm" class="swal-form" style="text-align: left; direction: ltr;">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                    <div>
                        <label style="display:block; font-size:12px; margin-bottom:5px; font-weight:600; color:var(--brand-blue);">Date From</label>
                        <input type="date" id="swal_date_from" class="swal2-input" style="margin:0; width:100%" value="{{ request('date_from') }}">
                    </div>
                    <div>
                        <label style="display:block; font-size:12px; margin-bottom:5px; font-weight:600; color:var(--brand-blue);">Date To</label>
                        <input type="date" id="swal_date_to" class="swal2-input" style="margin:0; width:100%" value="{{ request('date_to') }}">
                    </div>
                    <div>
                        <label style="display:block; font-size:12px; margin-bottom:5px; font-weight:600; color:var(--brand-blue);">Terminal ID</label>
                        <input type="text" id="swal_terminal_id" class="swal2-input" style="margin:0; width:100%" placeholder="100xxx" value="{{ request('terminal_id') }}">
                    </div>
                    <div>
                        <label style="display:block; font-size:12px; margin-bottom:5px; font-weight:600; color:var(--brand-blue);">Terminal Name</label>
                        <input type="text" id="swal_terminal_name" class="swal2-input" style="margin:0; width:100%" placeholder="Search..." value="{{ request('terminal_name') }}">
                    </div>
                    <div style="grid-column: span 2;">
                        <label style="display:block; font-size:12px; margin-bottom:5px; font-weight:600; color:var(--brand-blue);">Mobile Number</label>
                        <input type="text" id="swal_mobile" class="swal2-input" style="margin:0; width:100%" placeholder="07xxxxxxxx" value="{{ request('mobile') }}">
                    </div>
                </div>
            </form>
        `,
        confirmButtonText: '<i class="las la-search"></i> Apply Filter',
        confirmButtonColor: '#0071BC',
        showCancelButton: true,
        cancelButtonText: 'Clear',
        focusConfirm: false,
        preConfirm: () => {
            const date_from = document.getElementById('swal_date_from').value;
            const date_to = document.getElementById('swal_date_to').value;
            const terminal_id = document.getElementById('swal_terminal_id').value;
            const terminal_name = document.getElementById('swal_terminal_name').value;
            const mobile = document.getElementById('swal_mobile').value;

            let url = new URL("{{ route('reports.index') }}", window.location.origin);
            if(date_from) url.searchParams.append('date_from', date_from);
            if(date_to) url.searchParams.append('date_to', date_to);
            if(terminal_id) url.searchParams.append('terminal_id', terminal_id);
            if(terminal_name) url.searchParams.append('terminal_name', terminal_name);
            if(mobile) url.searchParams.append('mobile', mobile);

            window.location.href = url.href;
        }
    });
}
// مودال حذف مجموعة بيانات بناءً على التاريخ أو خيارات أخرى
function showDeleteModal() {
    Swal.fire({
        heightAuto: false,
        title: '<span style="color: var(--red); font-size: 18px; font-weight: 800;"><i class="las la-trash"></i> Delete Transactions Data</span>',
        html: `
            <form id="deleteForm" style="text-align: left; direction: ltr; display: grid; gap: 12px; margin-top: 10px;">
                <div style="background: var(--red-lt); padding: 10px; border-radius: 8px; color: var(--red); font-size: 12px; font-weight: 600;">
                    Warning: Deleting data is permanent and cannot be undone. You can specify a date range or delete all.
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                    <div>
                        <label style="display:block; font-size:11px; margin-bottom:4px; font-weight:700; color:var(--text-mid);">Date From</label>
                        <input type="date" id="del_date_from" class="swal2-input" style="margin:0; width:100%; height:38px; font-size:13px;">
                    </div>
                    <div>
                        <label style="display:block; font-size:11px; margin-bottom:4px; font-weight:700; color:var(--text-mid);">Date To</label>
                        <input type="date" id="del_date_to" class="swal2-input" style="margin:0; width:100%; height:38px; font-size:13px;">
                    </div>
                </div>
            </form>
        `,
        width: '500px',
        showCancelButton: true,
        confirmButtonText: 'Yes, Delete Data',
        confirmButtonColor: '#e74c3c',
        cancelButtonText: 'Cancel',
        focusConfirm: false,
        preConfirm: () => {
            const date_from = document.getElementById('del_date_from').value;
            const date_to = document.getElementById('del_date_to').value;

            const formData = {
                date_from: date_from,
                date_to: date_to,
                _token: '{{ csrf_token() }}',
                _method: 'DELETE'
            };

            return fetch(`{{ route('transactions.bulk-delete') }}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(formData)
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => { throw new Error(err.message || 'حدث خطأ ما'); });
                }
                return response.json();
            })
            .catch(error => {
                Swal.showValidationMessage(`Request failed: ${error}`);
            });
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                heightAuto: false,
                icon: 'success',
                title: 'تم الحذف!',
                text: 'تم حذف البيانات المحددة بنجاح.',
                timer: 1500,
                showConfirmButton: false
            }).then(() => {
                location.reload();
            });
        }
    });
}

// دالة حذف معاملة فردية
function deleteTransaction(id) {
    Swal.fire({
        heightAuto: false,
        title: 'Are you sure?',
        text: "You won't be able to revert this transaction!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e74c3c',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch(`/transactions/${id}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    _token: '{{ csrf_token() }}',
                    _method: 'DELETE'
                })
            })
            .then(response => {
                if (response.ok) {
                    Swal.fire({
                        heightAuto: false,
                        icon: 'success',
                        title: 'Deleted!',
                        text: 'Transaction has been deleted.',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire('Error!', 'Something went wrong.', 'error');
                }
            });
        }
    });
}
function exportData() {
    let urlParams = new URLSearchParams(window.location.search);
    let exportUrl = new URL("{{ route('reports.export') }}", window.location.origin);
    urlParams.forEach((value, key) => { exportUrl.searchParams.append(key, value); });
    window.location.href = exportUrl.href;
}

function editTransaction(trans) {
    // قائمة الأيام
    const days = ['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
    const daysOptions = days.map(d => `<option value="${d}" ${trans.day === d ? 'selected' : ''}>${d}</option>`).join('');

    // قائمة الشهور
    const months = [
        {val: 'Jan', name: 'January'}, {val: 'Feb', name: 'February'}, 
        {val: 'Mar', name: 'March'}, {val: 'Apr', name: 'April'}, 
        {val: 'May', name: 'May'}, {val: 'Jun', name: 'June'}, 
        {val: 'Jul', name: 'July'}, {val: 'Aug', name: 'August'}, 
        {val: 'Sep', name: 'September'}, {val: 'Oct', name: 'October'}, 
        {val: 'Nov', name: 'November'}, {val: 'Dec', name: 'December'}
    ];
    const monthsOptions = months.map(m => `<option value="${m.val}" ${trans.transaction_date && trans.transaction_date.includes(m.val) ? 'selected' : ''}>${m.name}</option>`).join('');

    // فصل السنة عن الوقت ومعالجة أي صيغة بأمان تام
    let yearVal = '';
    let timeVal = '';
    if (trans.year_time) {
        let cleanStr = trans.year_time.trim();
        let parts = cleanStr.split(/\s+/);
        yearVal = parts[0] || '';

        let timePart = parts.find(p => p.includes(':'));
        if (timePart) {
            let timeClean = timePart.replace(/[^0-9:]/g, '');
            let timeParts = timeClean.split(':');
            let hh = (timeParts[0] || '00').padStart(2, '0');
            let mm = (timeParts[1] || '00').padStart(2, '0');
            let ss = (timeParts[2] || '00').padStart(2, '0');
            timeVal = `${hh}:${mm}:${ss}`;
        }
    }

    Swal.fire({
        heightAuto: false, // <-- هذا السطر يمنع الصفحة من الصعود لأعلى عند فتح المودال
        title: '<span style="color: var(--brand-blue); font-size: 18px; font-weight: 800;"><i class="las la-edit"></i> Edit Transaction #' + trans.id + '</span>',
        html: `
            <form id="editTransactionForm" style="text-align: left; direction: ltr; display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 10px;">
                <div>
                    <label style="display:block; font-size:11px; margin-bottom:4px; font-weight:700; color:var(--text-mid);">Day</label>
                    <select id="edit_day" class="swal2-input" style="margin:0; width:100%; height:38px; font-size:13px; padding: 0 10px;">
                        <option value="">Select Day</option>
                        ${daysOptions}
                    </select>
                </div>
                <div>
                    <label style="display:block; font-size:11px; margin-bottom:4px; font-weight:700; color:var(--text-mid);">Month</label>
                    <select id="edit_transaction_month" class="swal2-input" style="margin:0; width:100%; height:38px; font-size:13px; padding: 0 10px;">
                        <option value="">Select Month</option>
                        ${monthsOptions}
                    </select>
                </div>
                <div>
                    <label style="display:block; font-size:11px; margin-bottom:4px; font-weight:700; color:var(--text-mid);">Day Number (e.g. 25)</label>
                    <input type="number" id="edit_transaction_day_num" class="swal2-input" style="margin:0; width:100%; height:38px; font-size:13px;" value="${trans.transaction_date ? trans.transaction_date.replace(/[^0-9]/g, '') : ''}">
                </div>
                <div>
                    <label style="display:block; font-size:11px; margin-bottom:4px; font-weight:700; color:var(--text-mid);">Year (e.g. 2026)</label>
                    <input type="number" id="edit_year" class="swal2-input" style="margin:0; width:100%; height:38px; font-size:13px;" value="${yearVal}">
                </div>
                <div>
                    <label style="display:block; font-size:11px; margin-bottom:4px; font-weight:700; color:var(--text-mid);">Time (HH:MM:SS)</label>
                    <input type="time" step="1" id="edit_time" class="swal2-input" style="margin:0; width:100%; height:38px; font-size:13px; background-color: #fff;" value="${timeVal}">
                </div>
                <div>
                    <label style="display:block; font-size:11px; margin-bottom:4px; font-weight:700; color:var(--text-mid);">Terminal ID</label>
                    <input type="text" id="edit_terminal_id" class="swal2-input" style="margin:0; width:100%; height:38px; font-size:13px;" value="${trans.terminal_id || ''}">
                </div>
                <div>
                    <label style="display:block; font-size:11px; margin-bottom:4px; font-weight:700; color:var(--text-mid);">Terminal Name</label>
                    <input type="text" id="edit_terminal_name" class="swal2-input" style="margin:0; width:100%; height:38px; font-size:13px;" value="${trans.terminal_name || ''}">
                </div>
                <div>
                    <label style="display:block; font-size:11px; margin-bottom:4px; font-weight:700; color:var(--text-mid);">Amount</label>
                    <input type="number" step="0.01" id="edit_amount" class="swal2-input" style="margin:0; width:100%; height:38px; font-size:13px;" value="${trans.amount || 0}">
                </div>
                <div>
                    <label style="display:block; font-size:11px; margin-bottom:4px; font-weight:700; color:var(--text-mid);">Mobile Number</label>
                    <input type="text" id="edit_mobile" class="swal2-input" style="margin:0; width:100%; height:38px; font-size:13px;" value="${trans.mobile || ''}">
                </div>
                <div>
                    <label style="display:block; font-size:11px; margin-bottom:4px; font-weight:700; color:var(--text-mid);">System Reference</label>
                    <input type="text" id="edit_system_reference" class="swal2-input" style="margin:0; width:100%; height:38px; font-size:13px;" value="${trans.system_reference || ''}">
                </div>
            </form>
        `,
        width: '600px',
        showCancelButton: true,
        confirmButtonText: 'Save Changes',
        confirmButtonColor: '#0071BC',
        cancelButtonText: 'Cancel',
        focusConfirm: false,
        preConfirm: () => {
            const monthVal = document.getElementById('edit_transaction_month').value;
            const dayNumVal = document.getElementById('edit_transaction_day_num').value;
            const combinedDate = (monthVal && dayNumVal) ? `${monthVal} ${dayNumVal}` : (monthVal || dayNumVal || '');

          const yearInput = document.getElementById('edit_year').value;
            const timeInput = document.getElementById('edit_time').value;
            
            let formattedTime = '';
            if (timeInput) {
                let [hours, minutes, seconds] = timeInput.split(':');
                let h = parseInt(hours, 10);
                let ampm = h >= 12 ? 'PM' : 'AM';
                h = h % 12;
                h = h ? h : 12; // الساعة 0 تصبح 12
                let hh = String(h).padStart(2, '0');
                let mm = minutes || '00';
                let ss = seconds || '00';
                
                formattedTime = `${hh}:${mm}:${ss} ${ampm}`;
            }

            const combinedYearTime = (yearInput && formattedTime) ? `${yearInput} ${formattedTime}` : (yearInput || formattedTime || '');

            const formData = {
                day: document.getElementById('edit_day').value,
                transaction_date: combinedDate,
                year_time: combinedYearTime,
                terminal_id: document.getElementById('edit_terminal_id').value,
                terminal_name: document.getElementById('edit_terminal_name').value,
                amount: document.getElementById('edit_amount').value,
                mobile: document.getElementById('edit_mobile').value,
                system_reference: document.getElementById('edit_system_reference').value,
                _token: '{{ csrf_token() }}',
                _method: 'PUT'
            };

            return fetch(`/transactions/${trans.id}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(formData)
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => { throw new Error(err.message || 'حدث خطأ ما'); });
                }
                return response.json();
            })
            .catch(error => {
                Swal.showValidationMessage(`Request failed: ${error}`);
            });
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                heightAuto: false,
                icon: 'success',
                title: 'تم التحديث!',
                text: 'تم تعديل بيانات المعاملة بنجاح.',
                timer: 1500,
                showConfirmButton: false
            }).then(() => {
                location.reload();
            });
        }
    });
}</script>
@endsection