<?php

namespace Modules\Seo\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use App\Utils\SlugManager;
use Maatwebsite\Excel\Facades\Excel;
use Modules\Seo\Models\Category;
use Modules\Seo\Models\OptionLink;

class OptionLinkController extends Controller
{
    public function __construct()
    {

    }

    public function import(Request $request)
    {
        $file = $request->file('file');
        $type = $request->file('type', 'option_filter_link');

        $returnValue = [
            'status' => 'fail',
            'result' => []
        ];

        if ($file) {
            $baseName = $file->getClientOriginalName();
            $filename = date("Y-m-d_H-i-s", time()) . '_' . $baseName;
            $uploadFolder = public_path('files/import');

            if (!is_dir($uploadFolder)) {
                mkdir($uploadFolder, 0777, true);
            }

            $path = $file->move(public_path('files/import'), $filename);
            if ($path) {

                Excel::selectSheetsByIndex(0)->load($path, function ($reader) use ($type, &$returnValue) {

                    $categories = Category::query()->where('type', Category::TYPE_PRODUCT)
                        ->select(['id', 'slug'])
                        ->get()
                        ->toArray();

                    $insertData = [];
                    $results = $reader->get();
                    foreach ($results as $row) {

                        $categorySlug = $row->category_slug;

                        $category = array_filter($categories, function($category) use ($categorySlug) {
                            return $category['slug'] == $categorySlug;
                        });

                        if ($category) {
                            $category = array_first($category);
                        } else continue;

                        $insertData[] = [
                            'keyword' => $row->keyword,
                            'title' => $row->title,
                            'url' => $row->url,
                            'target_id' => $category['id'],
                            'type' => $type
                        ];

                    }

                    OptionLink::query()->insert($insertData);

                    $returnValue['status'] = 'successful';
                    $returnValue['result'] = $insertData;

                });
            }
        }

        return $returnValue;
    }

    public static function getMostSearchProductLinks($targetId, $limit = 5)
    {
        $links = OptionLink::query()->inRandomOrder()
            ->where('type', 'option_filter_link')
            ->where('target_id', $targetId)
            ->limit($limit)
            ->get();

        return $links->toArray();
    }
}