<?php

namespace App\Http\Controllers\Assets\Settings;

use App\Events\BulkUpdates;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Manufacturer;
use App\Models\AssetHistory;
use Facades\App\Services\Settings\Manufacturer as ManufacturerService;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class ManufacturerController extends Controller
{
    public function __construct(ManufacturerService $manufacturerService)
    {
        $this->manufacturerService = $manufacturerService;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $manufacturers = Manufacturer::orderBy('slug')->get();
        return view('settings.manufacturer.manufacturer', compact('manufacturers'));
    }


    public function store()
    {
        $this->validate(request(), [
            'manufacturer' => 'required',
        ]);

        $manufacturer = request('manufacturer');
        $manufacturerSlug = str_slug($manufacturer, '_');

        $manufacturerData = Manufacturer::where('slug', $manufacturerSlug)->first();
        if (!$manufacturerData) {

            $manufacturerObj = new Manufacturer();

            $manufacturerObj->name = $manufacturer;
            $manufacturerObj->slug = $manufacturerSlug;
            $manufacturerObj->save();

            $description = __('history.ManufacturerCreated', [
                'manufacturer' => $manufacturer,
            ]);
            $assetHistory = [
                'user_id' => Auth::id(),
                'action' => 'manufacturer_created',
                'description' => $description,
                'created_at'  => Carbon::now()->format('Y-m-d H:i:s'),
                'updated_at'  => Carbon::now()->format('Y-m-d H:i:s'),
            ];
            event(new BulkUpdates($assetHistory));

            return redirect('/manufacturer');
        } else {
            return redirect('/manufacturer')->withErrors(['Manufacturer already exists']);
        }
    }

    public function ajax()
    {
        if (request('action') == 'edit') {
            return $this->update();
        } elseif (request('action') == 'delete') {
            return $this->destroy();
        }

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

    public function update()
    {
        $manufacturer = Manufacturer::findOrFail(request('manufacturer_id'));
        $oldManufacturer = $manufacturer->name;
        $manufacturer->update(['name' => request('name'), 'slug' => str_slug(request('name'), '_')]);

        $description = __('history.ManufacturerUpdated', [
            'oldManufacturer' => $oldManufacturer,
            'newManufacturer' => request('name')
        ]);
        $assetHistory = [
            'user_id' => Auth::id(),
            'action' => 'manufacturer_updated',
            'description' => $description,
            'created_at'  => Carbon::now()->format('Y-m-d H:i:s'),
            'updated_at'  => Carbon::now()->format('Y-m-d H:i:s'),
        ];
        event(new BulkUpdates($assetHistory));

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

    public function destroy()
    {
        $manufacturer = Manufacturer::findOrFail(request('manufacturer_id'));
        $manufactureData = Manufacturer::where('id', request('manufacturer_id'))->with('makeAndModel')->first();
        $manufacturerValue = $manufacturer->name;
        if (is_countable($manufactureData->makeAndModel) && optional($manufactureData->makeAndModel)->count()) {
            return response()->json('error');
        }
        $manufacturer->delete();

        $description = __('history.ManufacturerDeleted', [
            'manufacturer' => $manufacturerValue
        ]);
        $assetHistory = [
            'user_id' => Auth::id(),
            'action' => 'manufacturer_deleted',
            'description' => $description,
            'created_at'  => Carbon::now()->format('Y-m-d H:i:s'),
            'updated_at'  => Carbon::now()->format('Y-m-d H:i:s'),
        ];
        event(new BulkUpdates($assetHistory));
        return response()->json("Deleted Successfully");
    }


    /**
     * Manufacturer Export
     */
    public function export()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        
        $data = [];
        $datas = collect();
        $manufacturer = Manufacturer::orderBy('slug');
        $manufacturer->chunk(5000, function ($manufacturerChunks) use ($data, $datas) {
            $datas->push($this->manufacturerService::getManufacturerData($manufacturerChunks, 0, $data));
        });
        return $this->manufacturerService::export($datas->toArray());
    }
}
