<?php

namespace App\Policies\Tour;

use App\Models\Tour\Tour;
use App\Models\Tour\TourPricing;
use App\Models\User;

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

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

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

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

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

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

        // Cannot delete if it's the default pricing and there are other pricings
        if ($pricing->is_default && $tour->pricings()->count() > 1) {
            return false;
        }

        // Cannot delete if pricing is used in tour dates
        if ($tour->tourDates()->where('tour_pricing_id', $pricing->id)->exists()) {
            return false;
        }

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

    /**
     * Determine whether the user can set pricing as default.
     */
    public function setDefault(User $user, Tour $tour, TourPricing $pricing): bool
    {
        if ($pricing->tour_id !== $tour->id) {
            return false;
        }

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

    /**
     * Determine whether the user can view pricing analytics.
     */
    public function viewAnalytics(User $user, Tour $tour): bool
    {
        return $user->can('viewAnalytics', $tour);
    }
}
