<?php

namespace App\Http\Controllers;

use App\Jobs\WhatsappUnsoldCommodityNotification;
use App\Jobs\WhatsappUnsoldCommodityScanner;
use App\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class SettingController extends Controller
{
    public function getUnsoldCommodityNotifications()
    {
        $settings = Setting::where('group', 'unsold_commodity_notifications')->get();

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

    public function updateUnsoldCommodityNotifications(Request $request)
    {
        $request_array = $request->input();

        $general_inputs = array_filter(
            $request_array,
            function ($value, $key) {
                return strpos($key, 'pic_') === false;
            },
            ARRAY_FILTER_USE_BOTH
        );

        foreach ($general_inputs as $key => $value) {
            Setting::where([
                ['group', 'unsold_commodity_notifications'],
                ['key', $key]
            ])
                ->first()
                ->update(['value' => $value]);
        }

        $pic_inputs = array_filter(
            $request_array,
            function ($value, $key) {
                return Str::startsWith($key, 'pic_');
            },
            ARRAY_FILTER_USE_BOTH
        );

        $unique_pic_input = array_map(function ($array, $key) {
            return $this->filterUniqueById($array, $key);
        }, $pic_inputs, array_keys($pic_inputs));

        $transformed_unique_pic_input = [];

        array_walk($unique_pic_input, function ($item) use (&$transformed_unique_pic_input) {
            foreach ($item as $key => $value) {

                if(count($value) === 0){
                    $value = [new \stdClass()];
                }

                $transformed_unique_pic_input[$key] = $value;
            }
        });


        foreach ($transformed_unique_pic_input as $key => $value) {
            Setting::where([
                ['group', 'unsold_commodity_notifications'],
                ['key', $key]
            ])
                ->first()
                ->update(['value' => json_encode($value)]);
        }

        $this->cancelPreviousCommodityNotificationsJobs();

        dispatch((new WhatsappUnsoldCommodityScanner()));

        return response()->json('success');
    }


    public function filterUniqueById($array, $key)
    {
        $uniqueIds = [];
        $filteredArray = [];

        if ($array !== []) {
            foreach ($array as $item) {
                if (!in_array($item['id'], $uniqueIds)) {
                    $uniqueIds[] = $item['id'];
                    $filteredArray[] = $item;
                }
            }
        }

        return [
            $key => $filteredArray
        ];
    }


    public function cancelPreviousCommodityNotificationsJobs()
    {
        // flushed the fail job in queueu
        Artisan::call('queue:flush');

        $getClassNameString = function ($className) {
            $name =  explode("\\", $className);
            return end($name);
        };

        $commodityNotificationClasses = [
            WhatsappUnsoldCommodityNotification::class,
            WhatsappUnsoldCommodityScanner::class,
        ];


        foreach ($commodityNotificationClasses as $class) {
            DB::connection('mysql7')
                ->table('jobs')
                ->where('payload', 'like', '%' . $getClassNameString($class) . '%')
                ->delete();
        }
    }
}
