@extends('layouts.app')

@section('page_title', 'Fuel Price Update Logs')

@section('content')
    @php
        $fuelPriceUpdateLogs = [
            [
                'id' => 1,
                'schedule' => 'On-demand',
                'isCompleted' => 'Yes',
                'isSuccess' => 'Yes',
                'updatedBy' => 'Graxia Montino',
                'createdAt' => '2024-04-18 10:39 am'
            ],
            [
                'id' => 2,
                'schedule' => '2023-11-17 09:24 am',
                'isCompleted' => 'Yes',
                'isSuccess' => 'No',
                'updatedBy' => 'Graxia Montino',
                'createdAt' => '2023-11-17 09:23 am',
                'errorMessage' => 'Please recheck the CSV file, some fuels doesn\'t exist.'
            ],
            [
                'id' => 3,
                'schedule' => '2023-10-05 14:15 pm',
                'isCompleted' => 'Yes',
                'isSuccess' => 'Yes',
                'updatedBy' => 'John Doe',
                'createdAt' => '2023-10-05 14:10 pm'
            ],
            [
                'id' => 4,
                'schedule' => '2023-09-20 08:30 am',
                'isCompleted' => 'No',
                'isSuccess' => 'No',
                'updatedBy' => 'Jane Smith',
                'createdAt' => '2023-09-20 08:25 am',
                'errorMessage' => 'Invalid CSV format.'
            ],
            [
                'id' => 5,
                'schedule' => 'On-demand',
                'isCompleted' => 'Yes',
                'isSuccess' => 'Yes',
                'updatedBy' => 'Graxia Montino',
                'createdAt' => '2023-08-15 11:45 am'
            ],
            [
                'id' => 6,
                'schedule' => '2023-07-10 16:20 pm',
                'isCompleted' => 'Yes',
                'isSuccess' => 'No',
                'updatedBy' => 'Alex Brown',
                'createdAt' => '2023-07-10 16:15 pm',
                'errorMessage' => 'Server error during update.'
            ],
        ];
    @endphp

    <div class="mb-3">
        <h5 class="mb-0 fw-bold text-dark" style="font-size: 1.25rem;">Fuel Price Update Logs</h5>
    </div>
    <div class="row justify-content-center">
        <div class="card-body p-3">
            <!-- Filters -->
            <div class="d-flex justify-content-between mb-3 flex-wrap gap-2">
                <div class="d-flex align-items-center gap-2">
                    <div class="d-flex flex-column">
                        <label for="startDate" class="form-label mb-1">Start Date</label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-calendar-alt"></i></span>
                            <input type="date" class="form-control" id="startDate">
                        </div>
                    </div>
                    <div class="d-flex flex-column">
                        <label for="endDate" class="form-label mb-1">End Date</label>
                        <div class="input-group">
                            <input type="date" class="form-control" id="endDate">
                        </div>
                    </div>
                </div>
                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-export-csv" id="exportCsv" style="margin:20px">Export CSV</button>
                </div>
            </div>

            <!-- Table -->
            @include('components.table-component', [
                'data' => $fuelPriceUpdateLogs,
                'columns' => [
                    ['name' => 'Schedule', 'key' => 'schedule', 'sortable' => true],
                    ['name' => 'Is Completed', 'key' => 'isCompleted', 'sortable' => true],
                    [
                        'name' => 'Is Success',
                        'key' => 'isSuccess',
                        'sortable' => true,
                        'render' => function($item) {
                            return $item['isSuccess'] === 'Yes' ? 'Yes' : ($item['errorMessage'] ?? 'No');
                        }
                    ],
                    [
                        'name' => 'Description',
                        'key' => 'errorMessage',
                        'sortable' => true,
                        'render' => function($item) {
                            return $item['errorMessage'] ?? '-';
                        }
                    ],
                    ['name' => 'Updated By', 'key' => 'updatedBy', 'sortable' => true],
                    ['name' => 'Created At', 'key' => 'createdAt', 'sortable' => true]
                ],
                'allFields' => [],
                'actions' => [],
                'showAddButton' => false,
                'showCheckboxes' => false,
                'showBatchDelete' => false,
                'showEditModal' => false,
                'showViewModal' => false,
                'showSearch' => false
            ])
        </div>
    </div>

    <style>
        .card {
            border-radius: 5px;
            border: 1px solid #dee2e6;
        }
        .form-control {
            font-size: 0.9rem;
        }
        .btn-outline-secondary {
            border-color: #6c757d;
            color: #6c757d;
        }
        .btn-outline-secondary:hover {
            background-color: #f8f9fa;
        }
        .btn-export-csv {
            background-color: #ff6200;
            color: white;
            border: none;
        }
        .btn-export-csv:hover {
            background-color: #e65a00;
        }
        .input-group-text {
            background-color: #f8f9fa;
        }
    </style>

    <script>
        let originalData = [...tableConfig.data];
        const storedData = JSON.parse(sessionStorage.getItem('fuelPriceUpdateLogs') || '[]');
        if (storedData.length > 0) {
            tableConfig.data = [...tableConfig.data, ...storedData];
            originalData = [...tableConfig.data];
        }

        const startDateInput = document.getElementById('startDate');
        const endDateInput = document.getElementById('endDate');
        const exportCsvBtn = document.getElementById('exportCsv');

        function filterData() {
            const startDate = startDateInput.value ? new Date(startDateInput.value) : null;
            const endDate = endDateInput.value ? new Date(endDateInput.value) : null;

            tableConfig.data = originalData.filter(item => {
                // Parse the createdAt date (format: "YYYY-MM-DD hh:mm am/pm")
                const dateParts = item.createdAt.split(' ');
                const dateStr = dateParts[0]; // "YYYY-MM-DD"
                const timeStr = dateParts[1] + ' ' + dateParts[2]; // "hh:mm am/pm"
                const itemDate = new Date(`${dateStr} ${timeStr}`);

                if (startDate && itemDate < startDate) return false;
                if (endDate) {
                    const endDateAdjusted = new Date(endDate);
                    endDateAdjusted.setHours(23, 59, 59, 999);
                    if (itemDate > endDateAdjusted) return false;
                }
                return true;
            });

            currentPage = 1;
            renderTable();
            renderPagination();
        }

        startDateInput.addEventListener('change', filterData);
        endDateInput.addEventListener('change', filterData);

        exportCsvBtn.addEventListener('click', () => {
            const headers = tableConfig.columns.map(col => col.name).join(',');
            const rows = tableConfig.data.map(item => {
                return [
                    item.schedule,
                    item.isCompleted,
                    item.isSuccess === 'Yes' ? 'Yes' : (item.errorMessage || 'No'),
                    item.errorMessage || '-',
                    item.updatedBy,
                    item.createdAt
                ].join(',');
            });
            const csvContent = [headers, ...rows].join('\n');
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', 'fuel-price-update-logs.csv');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });

        // Initial render
        renderTable();
        renderPagination();
    </script>
@endsection