<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;


class ContactController extends Controller
{
    public function contact()
    {
        return view('contact');
    }

    public function ContactFormSubmit(Request $request)
    {
         //dd($request->all());
            $validator = Validator::make($request->all(), [
            'subject' => 'required|max:20',
            'phone' => 'required|numeric|digits:10',
            'email' => 'required|email|max:100',
            'message' => 'required|string|max:500',
        ]);
        // dd($validator);

        if ($validator->fails()) {
            return response()->json([
                        'error' => $validator->errors()->all()
                    ]);
        }

        $ContactFormSubmitResponse = Http::post('https://wip.tezcommerce.com:3304/api/v1/contact/saveContact', [
            "data" => [
                "storeId" => 69,
                "phone" => $request->phone,
                "email" => $request->email,
                "message" => $request->message,
                "subject" => $request->subject
            ]
        ]);
        $data = array();
        $contactFormSave = $ContactFormSubmitResponse->json(); 
         //dd($contactFormSave['data']['message']);
        if (isset($contactFormSave['errorNode']['errorCode']) && $contactFormSave['errorNode']['errorCode'] == 0) {
            $data = $contactFormSave['data']['message'];
        }
        
        return response()->json($data);

    }

    public function subscribe(Request $request)
	{


        $validator = Validator::make($request->all(), [
            'email' => 'required|regex:/(.+)@(.+)\.(.+)/i|not_in:*.xyz,*.XYZ'
        ]);
        
        if ($validator->fails()) {
            return response()->json([
                'error'=> $validator->errors()->all()
            ]);
        }

        $email=$request->email;
        // dd($email);
        $response = Http::post('https://wip.tezcommerce.com:3304/api/v1/save-subscriber',[
            "data" => [
                "storeId" => 69,
                "email" => $email
            ]
        ]);
        $subscribeSave = $response->json(); 
        // dd($subscribeSave);
        $data = array();
        if (isset($subscribeSave['errorNode']['errorCode']) && $subscribeSave['errorNode']['errorCode'] == 0) {
            $data = $subscribeSave['data']['message'];

        }else{
            if (isset($subscribeSave['errorNode']['errorCode']) && $subscribeSave['errorNode']['errorMsg'] == "No Error") {
                $data = $subscribeSave['data']['message'];
            }
           
        }
        // dd($data);
        return response()->json($data);
        
	}
}
