<?php

namespace Modules\Subscription\Repositories\Subscription;

use Modules\LMS\Repositories\BaseRepository;
use Modules\Subscription\Models\Subscription\Subscription;
use Modules\Subscription\Models\Subscription\SubscriptionUse;

class SubscriptionRepository extends BaseRepository
{
    protected static $model = Subscription::class;

    protected static $exactSearchFields = [];

    protected static $excludedFields = [
        'save' => [
            'image',
            '_token',
            'locale'
        ],
        'update' => ['image', '_token', '_method', 'locale'],
    ];

    protected static $rules = [
        'save' => [
            'title' => 'required|string',
            'description' => 'required|string',
            'usable_count' => 'required',
            'days' => 'required',
            'price' => 'required',
        ],
        'update' => [
            'title' => 'required|string',
            'description' => 'required|string',
            'usable_count' => 'required|string',
            'days' => 'required',
            'price' => 'required',
        ],
    ];

    /**
     * @param  mixed  $request
     */
    public static function save($request): array
    {
        if ($request->hasFile('image')) {
            static::$rules['save']['image'] = 'required|image|mimes:jpg,jpeg,png,svg,webp';
            $iconImg = parent::upload($request, fieldname: 'image', file: '', folder: 'lms/subscriptions');
            $request->merge(['icon_img' => $iconImg]);
        }
        $request->merge([
            'is_popular' => $request->is_popular == 'on' ? 1 : 0
        ]);
        $response = parent::save($request->all());
        $subscription = $response['data'] ?? null;
        if ($response['status'] === 'success' && $subscription) {
            $data = self::translateData($request->all());
            self::translate($subscription, $data, locale: $request->locale ?? app()->getLocale());
        }
        return $response;
    }

    /**
     * @param  int  $id
     * @param  array  $data
     */
    public static function update($id, $request): array
    {

        $response = parent::first(value: $id);
        $subscription = $response['data'] ?? null;

        if (! $subscription) {
            return [
                'status' => 'error',
                'data' => 'The model not found.',
            ];
        }

        $data = self::translateData($request->all());
        $defaultLanguage = app()->getLocale();
        self::translate(subscription: $subscription,  data: $data, locale: $request->locale);

        if ($request->locale &&  $defaultLanguage !== $request->locale) {
            return [
                'status' => 'success',
                'data' => $subscription,
            ];
        }

        if ($request->hasFile('image')) {
            static::$rules['update']['image'] = 'required|image|mimes:jpg,jpeg,png,svg,webp';
            $iconImg = parent::upload($request, fieldname: 'image', file: $subscription?->icon_img, folder: 'lms/subscriptions');
            $request->merge([
                'icon_img' => $iconImg,
            ]);
        }

        $request->merge([
            'is_popular' => $request->is_popular == 'on' ? 1 : 0
        ]);
        $response = parent::update($id, $request->all());
        return $response;
    }

    /**
     *  delete
     *
     * @param  $id  $id
     */
    public static function delete($id, $data = [], $options = [], $relations = []): array
    {
        $response = parent::first($id, withTrashed: true);
        $testimonial = $response['data'] ?? null;
        if ($response['status'] == 'success' && $testimonial) {

            $isDeleteAble = true;
            if (static::isSoftDeleteEnable() && ! $testimonial->trashed()) {
                $isDeleteAble = false;
            }

            if ($isDeleteAble) {
                parent::fileDelete(folder: 'lms/subscriptions', file: $testimonial->profile_image);
            }
            return parent::delete($id, $data);
        }
        return $response;
    }

    /**
     *  statusChange
     */
    public static function statusChange($id): array
    {
        $response = parent::first($id);
        $subscription = $response['data'];
        $subscription->status = ! $subscription->status;
        $subscription->update();

        return [
            'status' => 'success',
            'message' => translate('Status Change Successfully')
        ];
    }
    public static function translateData(array $data)
    {
        $data = [
            'title' => $data['title'],
        ];
        return $data;
    }

    public static function translate($subscription, $data, $locale)
    {
        $subscription->translations()->updateOrCreate(['locale' => $locale], [
            'locale' => $locale,
            'data' => $data
        ]);
    }


    public static function useSubscription($subscriptionId, $itemId, $saleId, $type = "course")
    {
        SubscriptionUse::create([
            'user_id' => authCheck()->id,
            'subscription_id' => $subscriptionId,
            'course_id' =>   $type == 'course' ? $itemId : null,
            'bundle_id' =>   $type == 'bundle' ? $itemId : null,
            'sale_id' => $saleId
        ]);
    }
}
