@extends('layouts.admin')

@section('content_admin')
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">Activities Management</h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="{{ route('packages.index') }}">Packages</a></li>
                            <li class="breadcrumb-item"><a
                                    href="{{ route('packages.itineraries', $package->id) }}">Itineraries</a></li>
                            <li class="breadcrumb-item active">Activities</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h3 class="card-title">
                                    Activities for: {{ $itinerary->title }} (Day {{ $itinerary->day_number }})
                                </h3>
                                <button type="button" class="btn btn-primary" data-toggle="modal"
                                    data-target="#createActivityModal">
                                    <i class="fas fa-plus"></i> Add Activity
                                </button>
                            </div>

                            <div class="card-body">
                                @if (session('success'))
                                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                                        {{ session('success') }}
                                        <button type="button" class="close" data-dismiss="alert">
                                            <span>&times;</span>
                                        </button>
                                    </div>
                                @endif

                                @if (session('error'))
                                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                        {{ session('error') }}
                                        <button type="button" class="close" data-dismiss="alert">
                                            <span>&times;</span>
                                        </button>
                                    </div>
                                @endif

                                @if ($activities->count() > 0)
                                    <div class="table-responsive">
                                        <table id="activitiesTable" class="table table-bordered table-striped">
                                            <thead>
                                                <tr>
                                                    <th>Image</th>
                                                    <th>Name</th>
                                                    <th>Description</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody id="sortable-activities">
                                                @foreach ($activities as $activity)
                                                    <tr data-id="{{ $activity->id }}">
                                                        <td>
                                                            @if ($activity->image_path)
                                                                <img src="{{ asset($activity->image_path) }}"
                                                                    alt="{{ $activity->name }}" class="img-thumbnail"
                                                                    style="width: 80px; height: 60px; object-fit: cover;">
                                                            @else
                                                                <div class="bg-light d-flex align-items-center justify-content-center"
                                                                    style="width: 80px; height: 60px;">
                                                                    <i class="fas fa-image text-muted"></i>
                                                                </div>
                                                            @endif
                                                        </td>
                                                        <td>{{ $activity->name }}</td>
                                                        <td>{{ Str::limit($activity->description, 100) }}</td>
                                                        <td>
                                                            <div class="btn-group" role="group">
                                                                <button type="button" class="btn btn-info btn-sm"
                                                                    onclick="viewActivity({{ $activity->id }})"
                                                                    title="View">
                                                                    <i class="fas fa-eye"></i>
                                                                </button>
                                                                <button type="button" class="btn btn-warning btn-sm"
                                                                    onclick="editActivity({{ $activity->id }})"
                                                                    title="Edit">
                                                                    <i class="fas fa-edit"></i>
                                                                </button>
                                                                <form
                                                                    action="{{ route('packages.itineraries.activities.destroy', [$package->id, $itinerary->id, $activity->id]) }}"
                                                                    method="POST" style="display: inline-block;">
                                                                    @csrf
                                                                    @method('DELETE')
                                                                    <button type="submit" class="btn btn-danger btn-sm delete-btn"
                                                                        title="Delete">
                                                                        <i class="fas fa-trash"></i>
                                                                    </button>
                                                                </form>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                @else
                                    <div class="text-center py-5">
                                        <i class="fas fa-hiking fa-5x text-muted mb-3"></i>
                                        <h5 class="text-muted">No Activities Found</h5>
                                        <p class="text-muted">Start by adding your first activity for this itinerary.</p>
                                    </div>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <!-- Create Activity Modal -->
    <div class="modal fade" id="createActivityModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <form action="{{ route('packages.itineraries.activities.store', [$package->id, $itinerary->id]) }}"
                    method="POST" enctype="multipart/form-data">
                    @csrf
                    <div class="modal-header">
                        <h5 class="modal-title">Add New Activity</h5>
                        <button type="button" class="close" data-dismiss="modal">
                            <span>&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="name">Activity Name *</label>
                            <input type="text" class="form-control" id="name" name="name" required>
                        </div>

                        <div class="form-group">
                            <label for="description">Description *</label>
                            <textarea class="form-control" id="description" name="description" rows="4" required></textarea>
                        </div>

                        <div class="form-group">
                            <label for="image">Activity Image</label>
                            <input type="file" class="form-control-file" id="image" name="image"
                                accept="image/*">
                            <small class="form-text text-muted">Upload an image for this activity (optional)</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Create Activity</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Activity Modal -->
    <div class="modal fade" id="editActivityModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <form id="editActivityForm" method="POST" enctype="multipart/form-data">
                    @csrf
                    @method('PUT')
                    <div class="modal-header">
                        <h5 class="modal-title">Edit Activity</h5>
                        <button type="button" class="close" data-dismiss="modal">
                            <span>&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="edit_name">Activity Name *</label>
                            <input type="text" class="form-control" id="edit_name" name="name" required>
                        </div>

                        <div class="form-group">
                            <label for="edit_description">Description *</label>
                            <textarea class="form-control" id="edit_description" name="description" rows="4" required></textarea>
                        </div>

                        <div class="form-group">
                            <label for="edit_image">Activity Image</label>
                            <div id="current_image_container" class="mb-2"></div>
                            <input type="file" class="form-control-file" id="edit_image" name="image"
                                accept="image/*">
                            <small class="form-text text-muted">Upload a new image to replace the current one
                                (optional)</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Activity</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Activity Modal -->
    <div class="modal fade" id="viewActivityModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="view_activity_name">Activity Details</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="view_activity_image" class="text-center mb-3"></div>
                    <div id="view_activity_description"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        // Edit activity function
        function editActivity(activityId) {
            // You would typically fetch activity data via AJAX
            // For now, I'll show how to populate the form
            $.get(`/admin/activities/${activityId}`, function(activity) {
                $('#edit_name').val(activity.name);
                $('#edit_description').val(activity.description);

                if (activity.image_path) {
                    $('#current_image_container').html(`
                <img src="${activity.image_path}" alt="${activity.name}"
                     class="img-thumbnail" style="max-width: 200px;">
            `);
                } else {
                    $('#current_image_container').html('');
                }

                $('#editActivityForm').attr('action',
                    `{{ route('packages.itineraries.activities.update', [$package->id, $itinerary->id, ':id']) }}`
                    .replace(':id', activityId)
                );

                $('#editActivityModal').modal('show');
            }).fail(function() {
                alert('Error loading activity data');
            });
        }

        // View activity function
        function viewActivity(activityId) {
            $.get(`/admin/activities/${activityId}`, function(activity) {
                $('#view_activity_name').text(activity.name);
                $('#view_activity_description').html(`<p>${activity.description}</p>`);

                if (activity.image_path) {
                    $('#view_activity_image').html(`
                <img src="${activity.image_path}" alt="${activity.name}"
                     class="img-fluid" style="max-height: 300px;">
            `);
                } else {
                    $('#view_activity_image').html('<p class="text-muted">No image available</p>');
                }

                $('#viewActivityModal').modal('show');
            }).fail(function() {
                alert('Error loading activity data');
            });
        }

        // Initialize DataTable and make rows sortable for reorder (preserve AJAX reorder)
        $(function() {
            // Initialize DataTable (layout's assets already include DataTables)
            var table = $('#activitiesTable').DataTable({
                responsive: true,
                lengthChange: false,
                autoWidth: false,
                language: {
                    emptyTable: "No activities found."
                },
                // Disable ordering on image and actions columns (indexes 0 and 3)
                columnDefs: [
                    { orderable: false, targets: [0, 3] }
                ]
            });

            // SweetAlert2 delete confirmation for delete buttons
            $(document).on('click', '.delete-btn', function(e) {
                e.preventDefault();
                var form = $(this).closest('form');

                Swal.fire({
                    title: 'Are you sure?',
                    text: "This action cannot be undone!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#6c757d',
                    confirmButtonText: 'Yes, delete it!',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        form.submit();
                    }
                });
            });

            // Use jQuery UI sortable on the tbody to allow drag-reorder while keeping DataTable features.
            // Keep a simple helper so column widths don't collapse during drag.
            $('#activitiesTable tbody#sortable-activities').sortable({
                helper: function(e, ui) {
                    ui.children().each(function() {
                        $(this).width($(this).width());
                    });
                    return ui;
                },
                update: function(event, ui) {
                    var order = [];
                    $('#activitiesTable tbody#sortable-activities tr').each(function() {
                        order.push($(this).data('id'));
                    });

                    $.ajax({
                        url: '{{ route('packages.itineraries.activities.reorder', [$package->id, $itinerary->id]) }}',
                        method: 'POST',
                        data: {
                            _token: '{{ csrf_token() }}',
                            order: order
                        },
                        success: function(response) {
                            if (response.success) {
                                toastr.success('Activities reordered successfully');
                            }
                        },
                        error: function() {
                            toastr.error('Error reordering activities');
                        }
                    });
                }
            }).disableSelection();
        });
    </script>

@endsection
