@extends('dashboard.includes.master')
@section('title', 'Home Page')

@section('css')
<style>
.delete-btn,
.send-btn,
.download-btn,
.download {
    padding: .2rem .7rem;
    font-size: 1.2rem !important;
    width: fit-content !important;
}

.dw-p {
    color: red;
    font-size: 30px;
}

.head-email {
    color: #035076;
    font-weight: 600;
}

.body-email {
    color: #0ca4cc;
    font-weight: 600;
}

.sort-icon {
    cursor: pointer;
    margin-left: 5px;
}

.sort-asc::after {
    content: '↑';
}

.sort-desc::after {
    content: '↓';
}

.sort-none::after {
    content: '↕';
}

th.sortable {
    cursor: pointer;
    user-select: none;
}

#searchForm {
    max-width: 350px;
    margin: 2rem 2rem 1rem auto !important;
    box-shadow: 0 1px 1px #eee7ee99, 0 -1px 1px #eee7ee99;
}
</style>
@endsection

@section('content')
<div class="col-xl-12">
    <div class="row">
        <div class="col-xl-12">
            <div class="card custom-card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <div class="d-flex">
                        <a href="{{ route('excel.upload.view') }}" class="btn btn-primary btn-sm me-2">
                            <i class="ri-add-line"></i> Upload Data
                        </a>
                    </div>
                </div>
                @if(session('showDownloadButton'))
                <p class="dw-p">there are invalid data,Download</p>
                <a href="{{ route('downloadInvalidDataReport') }}" class="btn btn-warning download">Download Invalid
                    Data Report</a>
                @endif

                @if (session('showInvalidHeadersButton'))
                <div class="alert alert-warning">
                    Some files have invalid headers.
                    <a href="{{ route('download.invalid.headers') }}" class="btn btn-primary">Download Invalid Headers
                        Report</a>
                </div>
                @endif

                <form action="{{ route('home.index') }}" method="GET" id="searchForm">
                    <div class="input-group">
                        <input type="text" id="searchInput" name="search" class="form-control" placeholder="Search..."
                            value="{{ request('search') }}">
                        <button type="submit" class="btn btn-outline-secondary">
                            <i class="fa fa-search"></i>
                        </button>
                        <button type="button" class="btn btn-outline-secondary" id="clearSearch">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                </form>

                @if(session('success'))
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    {{ session('success') }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                @endif

                @if(session('error'))
                @foreach ($error->all() as $errors)
                <div>{{ $errors }}</div>
                @endforeach
                @endif

                <div class="filter-container">
                    <form id="filterForm" action="{{ route('home.index') }}" method="GET"
                        class="d-flex flex-wrap align-items-end gap-3">
                        <div class="form-group">
                            <label for="categories">Categories</label>
                            <select id="categories" name="categories[]" class="form-select select2-multi"
                                multiple="multiple">
                                @foreach($categories as $category)
                                <option value="{{ $category->id }}"
                                    {{ (is_array(request('categories')) && in_array($category->id, request('categories'))) ? 'selected' : '' }}>
                                    {{ $category->name }}
                                </option>
                                @endforeach
                            </select>
                        </div>

                        <div class="form-group subcategory-container" id="subcategory_container">
                            <label for="subcategories">Subcategories</label>
                            <select id="subcategories" name="subcategories[]" class="form-select select2-multi"
                                multiple="multiple">
                                <option value="all">All Subcategories</option>
                                @foreach($subcategories as $subcategory)
                                <option value="{{ $subcategory->id }}"
                                    {{ (is_array(request('subcategories')) && in_array($subcategory->id, request('subcategories'))) ? 'selected' : '' }}
                                    data-category="{{ $subcategory->category_id }}">
                                    {{ $subcategory->name }}
                                </option>
                                @endforeach
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="countries">Countries</label>
                            <select id="countries" name="countries[]" class="form-select select2-multi"
                                multiple="multiple">
                                @foreach($countries as $country)
                                <option value="{{ $country }}"
                                    {{ (is_array(request('countries')) && in_array($country, request('countries'))) ? 'selected' : '' }}>
                                    {{ $country }}
                                </option>
                                @endforeach
                            </select>
                        </div>

                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">Apply Filters</button>
                            @if(request('categories') || request('subcategories') || request('countries') ||
                            request('search'))
                            <a href="{{ route('home.index') }}" class="btn btn-secondary ms-2">Clear All</a>
                            @endif
                        </div>
                    </form>
                </div>

                @if(request('categories') || request('subcategories') || request('countries') || request('search'))
                <div class="filters-applied">
                    <strong>Active Filters:</strong>
                    @if(request('search'))
                    <div class="filter-badge">
                        Search: "{{ request('search') }}"
                    </div>
                    @endif

                    @if(is_array(request('categories')))
                    @foreach(request('categories') as $categoryId)
                    @php
                    $categoryName = $categories->where('id', $categoryId)->first()->name ?? 'Unknown';
                    @endphp
                    <div class="filter-badge">
                        Category: {{ $categoryName }}
                    </div>
                    @endforeach
                    @endif

                    @if(is_array(request('subcategories')))
                    @foreach(request('subcategories') as $subcategoryId)
                    @php
                    $subcategoryName = $subcategories->where('id', $subcategoryId)->first()->name ?? 'Unknown';
                    @endphp
                    <div class="filter-badge">
                        Subcategory: {{ $subcategoryName }}
                    </div>
                    @endforeach
                    @endif

                    @if(is_array(request('countries')))
                    @foreach(request('countries') as $country)
                    <div class="filter-badge">
                        Country: {{ $country }}
                    </div>
                    @endforeach
                    @endif
                </div>
                @endif

                @if(request('categories') || request('subcategories') || request('countries') || request('search'))
                @if($datas->isNotEmpty())
                <div class="action-buttons">
                    <a href="{{ route('export.filtered', request()->query()) }}" class="btn btn-success">
                        <i class="fa fa-download"></i> Download Filtered Data
                    </a>
                </div>
                @else
                <div class="alert alert-warning text-center mt-3">
                    <div class="no-data-message" style="display">
                        <p>No data found for the selected filters.</p>
                    </div>
                    <div class="download-button" style="display:none;">
                        <form action="{{ route('export.filtered') }}" method="get">
                            <button type="submit" class="btn btn-primary">Download Filtered Data</button>
                        </form>
                    </div>
                </div>
                @endif
                @endif

                <div class="d-flex my-3 px-2 gap-2 fs-4">
                    <button type="button" class="btn btn-danger delete-btn" id="btn_delete_all" data-bs-toggle="modal"
                        disabled>
                        <i class="ri-delete-bin-line"></i>
                    </button>
                    <button type="button" class="btn btn-primary send-btn" title="Send Email" id="btn_send_all"
                        data-bs-toggle="modal" disabled>
                        <i class="fa-solid fa-envelope"></i>
                    </button>
                    <button type="button" class="btn btn-primary download-btn" title="Download_All" id="download_all"
                        data-bs-toggle="modal" disabled>
                        <i class="fa-solid fa-download"></i>
                    </button>
                    <span class="badge bg-primary">
                        Total Emails Count - {{ $emails }}
                    </span>

                    <span class="badge bg-success">
                        Total Data Count - {{ $allData }}
                    </span>
                </div>

                <div id="js-no-results" class="alert alert-warning text-center mt-3" style="display: none;">
                    No matching records found.
                </div>

                <table id="file-export" class="table table-bordered text-nowrap w-100">
                    <thead class="table-dark">
                        <tr>
                            <th>#</th>
                            <th><input name="select_all" id="example-select-all" type="checkbox"
                                    onclick="CheckAll('box1', this)" /></th>
                            <th class="sortable" data-sort="destination_name">Destination Name <span
                                    class="sort-icon sort-none"></span></th>
                            <th class="sortable" data-sort="address">Address <span class="sort-icon sort-none"></span>
                            </th>
                            <th class="sortable" data-sort="phone">Phone <span class="sort-icon sort-none"></span></th>
                            <th class="sortable" data-sort="phone2">Phone2 <span class="sort-icon sort-none"></span>
                            </th>
                            <th class="sortable" data-sort="email">Email <span class="sort-icon sort-none"></span></th>
                            <th class="sortable" data-sort="category_name">CategoryName <span
                                    class="sort-icon sort-none"></span></th>
                            <th class="sortable" data-sort="subcategory_name">SubcategoryName <span
                                    class="sort-icon sort-none"></span></th>
                            <th class="sortable" data-sort="country">Country <span class="sort-icon sort-none"></span>
                            </th>
                            <th>Operations</th>
                        </tr>
                    </thead>
                    <tbody id="table-body">
                        @foreach($datas as $data)
                        <tr class="product-list">
                            <td>{{ ($datas->currentPage() - 1) * $datas->perPage() + $loop->index + 1 }}</td>
                            <td><input type="checkbox" value="{{ $data->id }}" class="box1"></td>
                            <td>{{ $data->destination_name }}</td>
                            <td>{{ $data->address }}</td>
                            <td>{{ $data->phone }}</td>
                            <td>{{ $data->phone2 }}</td>
                            <td>{{ $data->email }}</td>
                            <td>{{ $data->category->name }}</td>
                            <td>{{ $data->subcategory->name }}</td>
                            <td>{{ $data->country }}</td>
                            <td>
                                <div class="d-flex gap-3 align-items-center">
                                    <button type="button" class="btn btn-icon btn-sm btn-danger delete-button"
                                        data-bs-toggle="modal" data-bs-target="#deleteModal{{ $data->id }}"
                                        data-id="{{ $data->id }}">
                                        <i class="ri-delete-bin-line"></i>
                                    </button>
                                    <form action="{{ route('home.edit',$data->id) }}" method="Get">
                                        @csrf
                                        <input type="hidden" name="id" value="{{ $data->id }}">
                                        <button type="submit" class="btn btn-icon btn-sm btn-info-light"
                                            title="Edit Date">
                                            <i class="ri-edit-line"></i>
                                        </button>
                                    </form>
                                    <a class="btn btn-success btn-sm" href="{{ route('home.show', $data->id) }}">
                                        <i class="fa fa-eye"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>

                        <div class="modal fade" id="deleteModal{{ $data->id }}" tabindex="-1"
                            aria-labelledby="deleteModalLabel" aria-hidden="true">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="deleteModalLabel">Confirm Deletion</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"
                                            aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body">
                                        Are you sure you want to delete this item?
                                    </div>
                                    <div class="modal-footer">
                                        <form id="deleteForm{{ $data->id }}" method="Post"
                                            action="{{route('home.destroy',$data->id)}}">
                                            @csrf
                                            @method('DELETE')
                                            <input type="hidden" name="id" id="id" value="{{$data->id}}">
                                            <button type="button" class="btn btn-secondary"
                                                data-bs-dismiss="modal">Cancel</button>
                                            <button type="submit" class="btn btn-danger">Delete</button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                        @endforeach
                    </tbody>
                </table>
                <div class="d-flex justify-content-center mt-3">
                    {{ $datas->appends(['search' => request('search')])->links('vendor.pagination.bootstrap-4') }}
                </div>
            </div>
        </div>

        <div class="modal fade" id="delete_all" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 style="font-family: 'Cairo', sans-serif;" class="modal-title" id="exampleModalLabel">
                            {{ trans('Delete All Rows of Data') }}
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form action="{{ route('delete_all') }}" method="POST">
                            {{ csrf_field() }}
                            <div class="modal-body">
                                {{ trans('Are you Sure for deletion more than one row') }}
                                <input class="text" type="hidden" id="delete_all_id" name="delete_all_id" value=''>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-danger">Delete</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" id="download_data_all" tabindex="-1" aria-labelledby="exampleModalLabel"
            aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 style="font-family: 'Cairo', sans-serif;" class="modal-title" id="exampleModalLabel">
                            {{ trans('Download All Rows of Data') }}
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form action="{{ route('download_all') }}" method="POST">
                            {{ csrf_field() }}
                            <div class="modal-body">
                                {{ trans('Are you Sure for Downloading !') }}
                                <input class="text" type="hidden" id="download_all_data" name="download_all_data"
                                    value=''>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-danger">Download</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" id="send_email" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 style="font-family: 'Cairo', sans-serif;" class="modal-title" id="exampleModalLabel">
                            {{ trans('Send Data') }}
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form action="{{ route('message.create') }}" method="GET">
                            {{ csrf_field() }}
                            <div class="modal-body">
                                {{ trans('Are you Sure That you want to send Email!!') }}
                                <input class="text" type="hidden" id="send_email_ids" name="send_email_ids" value=''>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-secondary">Send</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('js')
<script>
document.getElementById('download-invalid-data-btn')?.addEventListener('click', function() {
    this.style.display = 'none';
});
</script>

<script>
document.addEventListener("DOMContentLoaded", function() {
    let searchInput = document.querySelector("input[name='search']");
    let clearSearch = document.getElementById("clearSearch");
    const tableBody = document.getElementById('table-body');
    let currentSortColumn = null;
    let currentSortOrder = 'asc';

    // Existing search functionality
    searchInput.addEventListener("keyup", function() {
        let searchText = searchInput.value.toLowerCase().trim();
        let hasResults = false;

        tableBody.querySelectorAll('tr').forEach(row => {
            let match = row.textContent.toLowerCase().includes(searchText);
            row.style.display = match ? '' : 'none';
            if (match) hasResults = true;
        });

        document.getElementById('js-no-results').style.display = hasResults ? 'none' : 'block';
    });

    clearSearch.addEventListener("click", function() {
        searchInput.value = '';
        tableBody.querySelectorAll('tr').forEach(row => row.style.display = '');
        document.getElementById('js-no-results').style.display = 'none';
    });

    // Sort table function
    function sortTable(column, order) {
        const rows = Array.from(tableBody.querySelectorAll('tr'));

        rows.sort((a, b) => {
            let aValue, bValue;

            switch (column) {
                case 'destination_name':
                    aValue = a.cells[2].textContent.trim();
                    bValue = b.cells[2].textContent.trim();
                    break;
                case 'address':
                    aValue = a.cells[3].textContent.trim();
                    bValue = b.cells[3].textContent.trim();
                    break;
                case 'phone':
                    aValue = a.cells[4].textContent.trim();
                    bValue = b.cells[4].textContent.trim();
                    break;
                case 'phone2':
                    aValue = a.cells[5].textContent.trim();
                    bValue = b.cells[5].textContent.trim();
                    break;
                case 'email':
                    aValue = a.cells[6].textContent.trim();
                    bValue = b.cells[6].textContent.trim();
                    break;
                case 'category_name':
                    aValue = a.cells[7].textContent.trim();
                    bValue = b.cells[7].textContent.trim();
                    break;
                case 'subcategory_name':
                    aValue = a.cells[8].textContent.trim();
                    bValue = b.cells[8].textContent.trim();
                    break;
                case 'country':
                    aValue = a.cells[9].textContent.trim();
                    bValue = b.cells[9].textContent.trim();
                    break;
            }

            return order === 'asc' ?
                aValue.localeCompare(bValue) :
                bValue.localeCompare(aValue);
        });

        tableBody.innerHTML = '';
        rows.forEach(row => tableBody.appendChild(row));
    }

    // Update sort icons
    function updateSortIcons(column, order) {
        document.querySelectorAll('.sort-icon').forEach(icon => {
            icon.classList.remove('sort-asc', 'sort-desc');
            icon.classList.add('sort-none');
        });

        const currentIcon = document.querySelector(`th[data-sort="${column}"] .sort-icon`);
        if (currentIcon) {
            currentIcon.classList.remove('sort-none');
            currentIcon.classList.add(order === 'asc' ? 'sort-asc' : 'sort-desc');
        }
    }

    // Handle column header clicks
    document.querySelectorAll('.sortable').forEach(header => {
        header.addEventListener('click', function() {
            const column = this.getAttribute('data-sort');

            if (currentSortColumn === column) {
                currentSortOrder = currentSortOrder === 'asc' ? 'desc' : 'asc';
            } else {
                currentSortOrder = 'asc';
            }

            currentSortColumn = column;

            sortTable(column, currentSortOrder);
            updateSortIcons(column, currentSortOrder);
        });
    });
});
</script>
@endsection