<?php

namespace App\Console\Commands;

use App\Models\Logs;
use App\Models\OpProduct;
use App\Models\OpProductRelated;
use App\Models\ProjectSettings;
use Cron\CronExpression;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str;
use Config;
use DB;

class OpencartFeaturedProduct extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'nebim:featured {projectId}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $projectId = $this->argument('projectId');
        $project = ProjectSettings::where('id', $projectId)->first();

        Logs::createLog($project->id, "Önerilen ürünler güncelleniyor", 0);
        $databaseConfigName = Str::slug($project->project_name);
        Config::set('database.default', $databaseConfigName);

        $opProducts = OpProduct::all();

        $featured = [];
        foreach ($opProducts as $opProduct) {

            $split = explode('-', $opProduct->model);

            if (count($split) < 2) {
                continue;
            }
            $root = $split[0];


            $featured[$root][] = $opProduct->product_id;
        }


        foreach ($featured as $key => $value) {
            if (count($value) < 2) {
                unset($featured[$key]);
            }
        }

        foreach ($featured as $key => $value) {
            foreach ($value as $pid) {
                echo $pid . ":";
                $second = $value;
                foreach ($second as $pid2) {
                    if ($pid == $pid2)
                        continue;


                    $check = OpProductRelated::where('product_id', $pid)->where('related_id', $pid2)->first();
                    if (!$check) {
                        $newOpProductRelated = new OpProductRelated();
                        $newOpProductRelated->product_id = $pid;
                        $newOpProductRelated->related_id = $pid2;
                        $newOpProductRelated->save();
                    }
                    echo $pid2 . " ";
                }
                echo "<br>";
            }

            echo "<hr>";
        }

        return 0;
    }
}
