<?php

namespace Modules\Seo\Controllers;
use Modules\Seo\Models\TagConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use DateTime;
use Illuminate\Support\Facades\Redis;
use Modules\Seo\Models\Tag;

class TagConfigController extends Controller
{

    public function findTagConfig(Request $request) {
        $pageId = $request->has("page_id") ? $request->input("page_id") : 0;
        $pageSize = $request->has("page_size") ? $request->input("page_size") : 20;
        $query = TagConfig::query();
        if ($request->has('keyword')) {
            $keyword = $request->input("keyword");
            $query->where(function($query) use ($keyword) {
                $query->where("refer_name", "like", "%" . $keyword . "%")
                    ->orWhere("related_name", "like", "%" . $keyword . "%");
            });
        }
        $queryCount = clone $query;

        if ($pageSize > 0) {
            $query->offset($pageId);
            $query->limit($pageSize);
        }
        $items = $query->get();
        $count = DB::table(DB::raw("(" . $queryCount->toSql() . ") AS x"))
            ->mergeBindings($queryCount->getQuery())
            ->count();
        $pageCount = $this->recordsCountToPagesCount($count, $pageSize);
        $response = array(
            "status" => 'successful',
            'pagesCount' => $pageCount,
            'pageId' => $pageId,
            "items" => $items,
            "count" => $count,
        );
        return response()->json($response);
    }

    protected function recordsCountToPagesCount($recordsCount, $pageSize) {
        $retVal = (int) ($recordsCount / $pageSize);
        if ($recordsCount % $pageSize > 0) {
            $retVal++;
        }
        return $retVal;
    }

    public function saveTagConfig(Request $request) {
        $data = $this->buildData($request);
        if ($request->has("id")) {
            $tag = TagConfig::where("id", $request->input("id"))->first();
            $tag->fill($data);
            $tag->save();
        } else {
            $tag = new TagConfig;
            $tag->fill($data);
            $tag->save();
        }
        
        $response = [
            'status' => "successful",
            "result" => $tag,
        ];
        return response()->json($response);
    }

    private function buildData($request) {
        $result = [];
        if ($request->has("type")) {
            $result['type'] = $request->input("type");
        }
        if ($request->has("refer_id")) {
            $result['refer_id'] = $request->input("refer_id");
        }
        if ($request->has("refer_name")) {
            $result['refer_name'] = $request->input("refer_name");
        }
        if ($request->has("refer_url")) {
            $result['refer_url'] = $request->input("refer_url");
        }
        if ($request->has("related_type")) {
            $result['related_type'] = $request->input("related_type");
        }
        if ($request->has("related_id")) {
            $result['related_id'] = $request->input("related_id");
        }
        if ($request->has("related_name")) {
            $result['related_name'] = $request->input("related_name");
        }
        if ($request->has("related_url")) {
            $result['related_url'] = $request->input("related_url");
        }
        if ($request->has("image_url")) {
            $result['image_url'] = $request->input("image_url");
        }
        if ($request->has("id")) {
            $result['id'] = $request->input("id");
            $result['created_at'] = new DateTime();
        }
        $result['updated_at'] = new DateTime();

        return $result;
    }

    public function deleteTagConfig(Request $request) {
        $response = [
            "status" => "fail",
        ];
        if ($request->has("id")) {
            TagConfig::where("id", $request->input("id"))->delete();
            $response = [
                "status" => "successful",
            ];
        }

        return response()->json($response);
    }

    public function getTagHot($url) {
        $url = substr($url, 1);
        $result = [];
        $tagConfig = TagConfig::where("refer_url", "=", $url)->get();
        foreach ($tagConfig as $key => $value) {
            $data = [
                "title" => $value->related_name,
                "slug" => $value->related_url,
                "image_url" => $value->image_url,
                "type" => "config"
            ];
            $result[] = $data;
        }
        return $result;
    }

    public function buildTagImage(Request $request) {
        set_time_limit(-1);
        $totalTags = Tag::get(["id", "slug"]);
        $locale = env('APP_LOCALE', '');
        $tagSave = [];
        foreach ($totalTags as $key => $tag) {
            if (!Redis::exists("tag_image_url_" . $locale . $tag->slug)) {
                $ranNumber = rand(48, 96);
                $product = productByKeyword($tag->slug);
                if (isset($product) && isset($product["image_url"])) {
                    $image = $product["image_url"];
                    Redis::set("tag_image_url_" . $locale . $tag->slug, $image, 'EX', 60 * 60 * $ranNumber);
                    $tagSave[] = $tag->id;
                }
            }
        }
        return $tagSave;
    }

}