<?php

namespace Mtc\Plugins\Wisebee\Classes\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Mtc\Shop\Assessment\Assessment;
use Mtc\Shop\Category;
use Mtc\Shop\Item;
use Mtc\Shop\Item\Size;

/**
 * Accessors
 *
 * @property int $id
 * @property int $category_id
 * @property bool $consultation_required
 *
 * @property Carbon $updated_at
 * @property Carbon $created_at
 *
 */

class WisebeeCategory extends Model
{
    protected $table = 'wisebee_categories';

    protected $fillable = [
        'category_id',
        'consultation_required',
    ];

    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class, 'category_id');
    }

    /**
     * Need to redirect to the book consultation if the category requires consultation and there is none in the basket
     *
     * @param $requestData
     * @return void
     */
    public static function checkAndRedirectFromAssessment($requestData): void
    {
        if (!$assessmentURL = self::getAssessmentRedirect($requestData)) {
            return;
        }

        // Create redirect that can be picked up by assessment form
        session()->now(Assessment::ASSESSMENT_INIT_REDIRECT, route('wisebee-book', [
            'redirect' => $assessmentURL,
        ], false));
    }

    /**
     * Gets the assessment redirect URL
     *
     * @param $requestData
     * @return string|null
     */
    public static function getAssessmentRedirect($requestData): ?string
    {
        if (!WisebeeSetting::getSetting(WisebeeSetting::SETTING_APPLY_TO_CATEGORIES)) {
            return null;
        }

        $basket = new \Basket();
        $basket->Go_Basket();

        // Consultation already in basket, don't need to redirect to the booking form
        if (!empty($basket->hasConsultation)) {
            return null;
        }

        if (!empty($requestData['s'])) {
            $itemID = Size::query()
                ->find($requestData['s'])
                ->item_id;
        } elseif (!empty($requestData['p'])) {
            $itemID = $requestData['p'];
        }

        if (!empty($itemID)) {
            $categoryIds = Item::query()
                ->find($itemID)
                ->categories
                ->pluck('id');
        } else {
            $categoryIds = collect([$requestData['c']]);
        }

        // If the category doesn't require consultation, we don't redirect
        $categoryRequiresConsultation = self::query()
            ->whereIn('category_id', $categoryIds)
            ->where('consultation_required', true)
            ->exists();

        if (!$categoryRequiresConsultation) {
            return null;
        }

        if (!empty($requestData['id_param'])) {
            $requestData['form_id'] = $requestData['id_param'];
            unset($requestData['id_param']);
        }
        return route('assessment-form', $requestData, false);
    }
}