@extends('layout.app')
@section('content')
    <div class="container-fluid">
        <div class="card shadow-sm">
            <div class="card-header bg-primary text-white">
                <h4 class="mb-0">
                    <i class="fas fa-history"></i> {{ $type }} Log History
                </h4>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover mb-0" id="historyTable">
                        <thead class="thead-dark">
                            <tr>
                                <th class="text-center" style="width: 15%;">Date & Time</th>
                                <th class="text-center" style="width: 15%;">Edited By</th>
                                <th class="text-center" style="width: 35%;">Old Data</th>
                                <th class="text-center" style="width: 35%;">New Data</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse ($lists as $log)
                                @php
                                    $old = json_decode($log->old_info);
                                    $new = json_decode($log->new_info);

                                    // Handle smart devices if they exist
                                    $oldSmartDevices = [];
                                    $newSmartDevices = [];

                                    // Handle cancel reasons if they exist
                                    $oldCancelReasons = [];
                                    $newCancelReasons = [];

                                    // Handle survey cancel reasons if they exist
                                    $oldSurveyCancelReasons = [];
                                    $newSurveyCancelReasons = [];

                                    // Process cancel reasons
                                    if (isset($old->cancel_reasons) && is_array($old->cancel_reasons)) {
                                        $oldCancelReasons = array_filter($old->cancel_reasons, function($reason) {
                                            return isset($reason->cancel_reason_id);
                                        });
                                    }

                                    if (isset($new->cancel_reasons) && is_array($new->cancel_reasons)) {
                                        $newCancelReasons = array_filter($new->cancel_reasons, function($reason) {
                                            return isset($reason->cancel_reason_id);
                                        });
                                    }

                                    // Process smart devices
                                    if (isset($old->smart_devices) && is_array($old->smart_devices)) {
                                        $oldSmartDevices = array_filter($old->smart_devices, function($device) {
                                            return isset($device->status) && $device->status === 'Yes';
                                        });
                                    }

                                    if (isset($new->smart_devices) && is_array($new->smart_devices)) {
                                        $newSmartDevices = array_filter($new->smart_devices, function($device) {
                                            return isset($device->status) && $device->status === 'Yes';
                                        });
                                    }

                                    // Process survey cancel reasons
                                    if (isset($old->survey_cancel_reason) && is_array($old->survey_cancel_reason)) {
                                        $oldSurveyCancelReasons = array_filter($old->survey_cancel_reason, function($reason) {
                                            return isset($reason->cancel_reason_id);
                                        });
                                    }

                                    if (isset($new->survey_cancel_reason) && is_array($new->survey_cancel_reason)) {
                                        $newSurveyCancelReasons = array_filter($new->survey_cancel_reason, function($reason) {
                                            return isset($reason->cancel_reason_id);
                                        });
                                    }

                                    $change_old = [];
                                    $change_new = [];

                                    // Compare regular fields
                                    foreach ($old as $key => $value) {
                                        if ($old->$key != $new->$key &&
                                            $key != "smart_devices" &&
                                            $key != 'updated_at' &&
                                            $key != 'cancel_reasons' &&
                                            $key != 'survey_cancel_reason') {
                                            $change_old[$key] = $old->$key ?? 'N/A';
                                            $change_new[$key] = $new->$key ?? 'N/A';
                                        }
                                    }

                                    // Add smart devices changes if different
                                    if ($oldSmartDevices != $newSmartDevices) {
                                        $change_old['smart_devices'] = !empty($oldSmartDevices)
                                            ? implode(', ', array_column($oldSmartDevices, 'smart_device_id'))
                                            : 'None';
                                        $change_new['smart_devices'] = !empty($newSmartDevices)
                                            ? implode(', ', array_column($newSmartDevices, 'smart_device_id'))
                                            : 'None';
                                    }

                                    // Add cancel reasons changes if different
                                    if ($oldCancelReasons != $newCancelReasons) {
                                        $change_old['cancel_reasons'] = !empty($oldCancelReasons)
                                            ? implode(', ', array_column($oldCancelReasons, 'cancel_reason_id'))
                                            : 'None';
                                        $change_new['cancel_reasons'] = !empty($newCancelReasons)
                                            ? implode(', ', array_column($newCancelReasons, 'cancel_reason_id'))
                                            : 'None';
                                    }

                                    // Add survey cancel reasons changes if different (FIXED BUG)
                                    if ($oldSurveyCancelReasons != $newSurveyCancelReasons) {
                                        $change_old['survey_cancel_reason'] = !empty($oldSurveyCancelReasons)
                                            ? implode(', ', array_column($oldSurveyCancelReasons, 'cancel_reason_id'))
                                            : 'None';
                                        $change_new['survey_cancel_reason'] = !empty($newSurveyCancelReasons)
                                            ? implode(', ', array_column($newSurveyCancelReasons, 'cancel_reason_id'))
                                            : 'None';
                                    }
                                @endphp
                                <tr>
                                    <td class="text-center align-middle">
                                        <small class="text-muted">
                                            <i class="far fa-calendar-alt"></i> {{ $log->created_at->format('d-m-Y') }}<br>
                                            <i class="far fa-clock"></i> {{ $log->created_at->format('H:i:s') }}
                                        </small>
                                    </td>
                                    <td class="text-center align-middle">
                                        <span class="badge badge-info">
                                            <i class="fas fa-user"></i> {{ $log->user->name ?? 'N/A' }}
                                        </span>
                                    </td>
                                    <td class="p-2 bg-light">
                                        @if (!empty($change_old))
                                            <div class="changes-list">
                                                @foreach ($change_old as $key => $value)
                                                    <div class="mb-2">
                                                        <span class="badge badge-warning text-uppercase">
                                                            {{ str_replace('_', ' ', $key) }}
                                                        </span>
                                                        <span class="ml-1">:
                                                            <strong>{{ $value }}</strong>
                                                        </span>
                                                    </div>
                                                @endforeach
                                            </div>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    <td class="p-2 bg-light">
                                        @if (!empty($change_new))
                                            <div class="changes-list">
                                                @foreach ($change_new as $key => $value)
                                                    <div class="mb-2">
                                                        <span class="badge badge-success text-uppercase">
                                                            {{ str_replace('_', ' ', $key) }}
                                                        </span>
                                                        <span class="ml-1">:
                                                            <strong>{{ $value }}</strong>
                                                        </span>
                                                    </div>
                                                @endforeach
                                            </div>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="4" class="text-center py-4">
                                        <i class="fas fa-info-circle text-muted fa-2x"></i>
                                        <p class="mb-0 mt-2 text-muted">No history logs found.</p>
                                    </td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>

            @if(method_exists($lists, 'hasPages') && $lists->hasPages())
                <div class="card-footer">
                    {{ $lists->links() }}
                </div>
            @endif
        </div>
    </div>
@endsection

@push('styles')
    <style>
        #wrap span,
        td a,
        td span {
            white-space: normal !important;
        }

        .changes-list {
            max-height: 400px;
            overflow-y: auto;
        }

        .changes-list::-webkit-scrollbar {
            width: 6px;
        }

        .changes-list::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }

        .changes-list::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 10px;
        }

        .changes-list::-webkit-scrollbar-thumb:hover {
            background: #555;
        }

        #historyTable tbody tr:hover {
            background-color: #f8f9fa;
        }

        .badge {
            font-size: 0.75rem;
            padding: 0.35em 0.65em;
        }

        .align-middle {
            vertical-align: middle !important;
        }
    </style>
@endpush

@section('ajax')
    <script>
        $(document).ready(function() {
            // Initialize DataTable for better sorting/filtering
            if ($.fn.DataTable && $('#historyTable').length) {
                $('#historyTable').DataTable({
                    order: [[0, 'desc']], // Sort by date descending
                    pageLength: 25,
                    responsive: true,
                    language: {
                        emptyTable: "No history logs found"
                    }
                });
            }
        });
    </script>
@endsection
