<?php

namespace App\Services\Admin\Financial;

use App\Http\Requests\Admin\DiscountRequest;
use App\Models\Discount;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Morilog\Jalali\Jalalian;

class DiscountService
{
    /** get discount list */
    public function getDiscounts(Request $request)
    {
        /** @var LengthAwarePaginator */
        $discounts = Discount::query()->when($request->input('search'), function ($query, $search) {
            $query->where(DB::raw('concat(`title`, `code`)'), 'like', "%{$search}%");
        })->when($request->input('active'), function ($query, $active) {
            if ($active) {
                $query->where('expire_at', '>', Carbon::now());
            }
        })->when($request->input('expired'), function ($query, $banned) {
            if ($banned) {
                $query->where('expire_at', '<', Carbon::now());
            }
        })->orderBy('created_at', 'desc')->paginate(20);

        $discounts->withQueryString();

        return $discounts;
    }

    /** get discount for */
    public function getFor(DiscountRequest $request, Discount $discount = null)
    {
        $for = $discount != null ? $discount->for : null;
        if ($request->for['type'] == 'all') {
            $for = 'all';
        } else {
            $user = User::where('phone', $request->for['phone'])->first();
            if ($user != null) {
                $for = $user->id;
            } else {
                return 'redirect_back';
            }
        }

        return $for;
    }

    /** get percent */
    public function getPercent(DiscountRequest $request, Discount $discount = null)
    {
        $percent = $discount != null ? $discount->percent : null;
        if ($request->exists('percent') && $request->percent != null) {
            if ($request->percent > 100 || $request->percent < 0) {
                return 'redirect_back';
            }
            $percent = $request->percent;
        }

        return $percent;
    }

    /** get expire at */
    public function getExpireAt(DiscountRequest $request, Discount $discount = null)
    {
        if ($request->filled('expire_at')) {
            try {
                $jalali = Jalalian::fromFormat('Y/m/d', $request->expire_at);
                $timestamp = $jalali->getTimestamp();

                if ($timestamp < 0) {
                    return null;
                }

                $carbon = $jalali->toCarbon()->setTimezone('Asia/Tehran');

                if ($carbon->year > 2040) {
                    return null;
                }

                return $carbon->format('Y-m-d H:i:s');
            } catch (\Exception $e) {
                return null;
            }
        }

        return $discount ? $discount->expire_at : null;
    }
}
