<?php

namespace App\Policies\Tour;

use App\Models\Tour\Tour;
use App\Models\Tour\TourItinerary;
use App\Models\User;

class TourItineraryPolicy
{
    /**
     * Determine whether the user can view any tour itineraries.
     */
    public function viewAny(User $user, Tour $tour): bool
    {
        return $user->can('view', $tour);
    }

    /**
     * Determine whether the user can view the tour itinerary.
     */
    public function view(User $user, Tour $tour, TourItinerary $itinerary): bool
    {
        return $user->can('view', $tour) && $itinerary->tour_id === $tour->id;
    }

    /**
     * Determine whether the user can create tour itineraries.
     */
    public function create(User $user, Tour $tour): bool
    {
        return $user->can('update', $tour);
    }

    /**
     * Determine whether the user can update the tour itinerary.
     */
    public function update(User $user, Tour $tour, TourItinerary $itinerary): bool
    {
        if ($itinerary->tour_id !== $tour->id) {
            return false;
        }

        return $user->can('update', $tour);
    }

    /**
     * Determine whether the user can delete the tour itinerary.
     */
    public function delete(User $user, Tour $tour, TourItinerary $itinerary): bool
    {
        if ($itinerary->tour_id !== $tour->id) {
            return false;
        }

        // Cannot delete if tour has active bookings
        if ($tour->tourDates()->where('sold_count', '>', 0)->exists()) {
            return false;
        }

        return $user->can('update', $tour);
    }

    /**
     * Determine whether the user can reorder tour itineraries.
     */
    public function reorder(User $user, Tour $tour): bool
    {
        return $user->can('update', $tour);
    }
}
