<?php

namespace App\Http\Controllers\Admin;

use App\Enums\ContactTypeEnum;
use App\Enums\DbStatusFieldEnum;
use App\Http\Controllers\Controller;
use App\Models\Contact;
use App\Rules\PhoneRule;
use App\Services\ContactService;
use App\Traits\JsonApiCustomFunctionTraits;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use LaravelJsonApi\Core\Document\Error;
use LaravelJsonApi\Core\Document\ErrorList;
use LaravelJsonApi\Core\Document\ErrorSource;
use LaravelJsonApi\Core\Document\JsonApi;
use Log;
use Validator;

class ContactController extends Controller
{
    use JsonApiCustomFunctionTraits;

    protected ContactService $service;

    public function __construct(ContactService $service)
    {
        $this->service = $service;
    }

    /**
     * Display a listing of the resource.
     */
    public function index(): Response|JsonResponse|ErrorList|JsonApi
    {

        Log::channel('chromePHP')->critical('BrowserConsole', ['basename' => basename(__FILE__), 'line' => __LINE__]);

        /*
                return csrf_token();
        */
        /*
                $error=Error::make();
                $error->setStatus('201');
                $error->setId(12);
                $error->setSource( ['pointer'=>'pointer','parameter'=>'parameter2']);
                return $error;
                return JsonApi::make();
        */

        $error = Error::fromArray([
            'status' => 201,
            'id' => 99,
            // 'soucre'=>$errorSource
            'source' => ['pointer' => 'pointer', 'parameter' => 'parameter4'],
        ]);
        $error2 = Error::fromArray([
            // 'soucre'=>$errorSource
            'source' => ['pointer' => 'pointer', 'parameter' => 'parameter2'],
        ]);
        // dd(Error::make()->setSource($errorSource));
        // return $error;

        $errorList = ErrorList::fromArray([
            $error, $error2,
        ]);

        return $errorList;

        $error = Error::make()->setStatus(202);
        /*
        ['code'=>202,
            'detail'=>'ez a hiba leirasa',
            'status'=>202,
            'title'=>'van baj'
        ]

        $error=Error::fromArray(['code'=>999,
            'detail'=>'ez a hiba leirasa',
            'status'=>202,
            'title'=>'van baj2',
            'code'=>'400',
            'soucre'=>'xax'
            //'soucre'=>['pointer'=>'pointer','parameter'=>'parameter']
        ]);

        */
        $errorSource = ErrorSource::fromArray(
            ['pointer' => 'pointer', 'parameter' => 'parameter']
        );
        $error = Error::make();
        $error->setStatus('201');
        $error->setId(12);
        $error->setSource(['pointer' => 'pointer', 'parameter' => 'parameter2']);

        $error = Error::fromArray([
            'status' => 201,
            'id' => 99,
            // 'soucre'=>$errorSource
            'source' => ['pointer' => 'pointer', 'parameter' => 'parameter4'],
        ]);
        $error2 = Error::fromArray([
            'status' => 202,
            'id' => 92,
            // 'soucre'=>$errorSource
            'source' => ['pointer' => 'pointer', 'parameter' => 'parameter2'],
        ]);
        // dd(Error::make()->setSource($errorSource));
        // return $error;

        $errorList = ErrorList::fromArray([
            $error, $error2,
        ]);

        $errorList = JsonApi::make('1');
        $errorList->data = ['id' => 12];
        $errorList->setMeta(['total' => 200]);

        return $errorList;
        // return JsonApi::make();

    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): Response|JsonResponse
    {
        return response('create');
    }

    /**
     * Store a newly created resource in storage.
     *
     *
     * @throws ValidationException
     */
    public function store(Request $request): Response|JsonResponse|ErrorList
    {
        $validated = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'email|nullable',
            // 'phone'=>'regex:"^[\/+][0-9]{1,2}[(][0-9]{1,2}[)][0-9]{3}[ ][0-9]{3,4}$"|nullable',
            'phone' => ['nullable', new PhoneRule],
            'note' => 'string|nullable|max:65000',
            // 'type'=>'string|nullable|enum:'.ContactTypeEnum::class
            'type.*' => ['nullable', Rule::in(ContactTypeEnum::getKeys())],
        ]);

        if ($validated->fails()) {
            return $this->convertMessageBagToJSONAPIError($validated->getMessageBag());
        }
        $fillData = $validated->validated();

        if (isset($fillData['type']) && is_array($fillData['type'])) {
            $fillData['type'] = implode(',', $fillData['type']);
        } else {
            $fillData['type'] = null;
        }
        $contact = new Contact;

        $contact->fill($fillData);
        $contact->status = DbStatusFieldEnum::active;
        $contact->save();

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

    /**
     * Display the specified resource.
     */
    public function show(int $ContactId): Response|JsonResponse
    {

        return response()->json(Contact::findOrFail($ContactId));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(int $ContactId): Response|JsonResponse
    {
        return response()->noContent();
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, int $ContactId): Response|JsonResponse|ErrorList
    {
        /*dd(var_export(ContactTypeEnum::getKeys(),true),[
            'name'=>'required',
            'email'=>'email',
            //'phone'=>'regex:"^[\/+][0-9]{1,2}[(][0-9]{1,2}[)][0-9]{3}[ ][0-9]{3,4}$"|nullable',
            'phone'=>['nullable',new PhoneRule()],
            'note'=>'string|nullable|max:65000',
            'type'=>'nullable|enum:'
        ]);*/

        $validated = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'email|nullable',
            // 'phone'=>'regex:"^[\/+][0-9]{1,2}[(][0-9]{1,2}[)][0-9]{3}[ ][0-9]{3,4}$"|nullable',
            'phone' => ['nullable', new PhoneRule],
            'note' => 'string|nullable|max:65000',
            'type.*' => ['nullable', Rule::in(ContactTypeEnum::getKeys())],
        ]);

        if ($validated->fails()) {
            return $this->convertMessageBagToJSONAPIError($validated->getMessageBag());
        }
        // dd($validated->validated());
        $fillData = $validated->validated();

        if (isset($fillData['type']) && is_array($fillData['type'])) {
            $fillData['type'] = implode(',', $fillData['type']);
        } else {
            $fillData['type'] = null;
        }
        $contact = Contact::findOrFail($ContactId);
        $contact->fill($fillData);

        $contact->save();

        return response()->json($contact->toArray());

    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(int $ContactId): Response|JsonResponse
    {
        $contact = Contact::findOrFail($ContactId);
        $contact->delete();

        return response()->json(['success' => true]);
    }
}
