<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use App\Models\Country;
use App\Models\Company;
use App\Models\AccountTitle;
use App\Models\CompanyAddress;
use App\Models\Account;
use App\Models\AccountAddress;
use App\Models\AccountContact;
use App\Models\AccountingGroup;
use App\Models\StorageSetting;
use App\Models\LicenseAuthentication;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use App\Models\MasterType;
use Illuminate\Support\Facades\Http;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name'     => $data['name'],
            'email'    => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }

    public function registerPatient()
    {
        $country         = Country::select(['id','name'])->get();
        $account_title   = AccountTitle::select(['id','name','value'])->where('status', '1')->get();
        $company_id      = \Auth::user()->company_id ?? '';
        $company_address = CompanyAddress::select([
                                'companies_addresses.country_id',
                                'companies_addresses.state_id',
                                'companies_addresses.city_id',
                            ])
                            ->where('companies.is_default', '1')
                            ->leftjoin('companies', 'companies.id', 'companies_addresses.company_id')
                            ->first();

        $country_id = $company_address->country_id ?? '';
        $state_id   = $company_address->state_id ?? '';
        $city_id    = $company_address->city_id ?? '';
        $country_code = '';
        if($country_id)
        {
            $country_code    = Country::select(['code'])->find($country_id);
        }
        


        return view('auth.register-patient',compact(
            'state_id',
            'city_id',
            'country_id',
            'country',
            'account_title',
            'country_code'
        ));
    }

    public function registerPatientStore(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name'       => 'required',
            'country_id' => 'required',
            'phone_no'   => 'required|unique:account_contacts',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $account_title = AccountTitle::select(['name'])->find($request->account_title_id);

        $account = Account::create([
            'name'             => $request->name,
            'account_title_id' => $request->account_title_id,
            'account_type_id'  => 1,
            'created_by'       => \Auth::user()->id ?? ''
        ]);

        $account_type = MasterType::find(1);
        $count  = 1;
        $prefix = "AC";

        if($account_type) {
            $count  = $account_type->count != '' ? $account_type->count + 1 : 1;
            $prefix = $account_type->prefix != '' ? $account_type->prefix : "AC";

            $account_type->update(['count' => $count]);
        }

        $code = $this->generateCode($count, $prefix);

        $account->update(['code' => $code]);

        $address = AccountAddress::create([
            'account_id'    => $account->id,
            'country_id'    => $request->country_id,
            'state_id'      => $request->state_id,
            'city_id'       => $request->city_id,
            'address_line1' => $request->address,
            'post_code'     => $request->postal_code,
            'is_default'    => '1'
        ]);

        $contact = AccountContact::create([
            'account_id'        => $account->id,
            'phone_no'          => $request->phone_no,
            'email'             => $request->email ?? '',
            'name'              => $request->name ?? '',
            'date_of_birth'     => $request->date_of_birth != '' ? date('Y-m-d', strtotime($request->date_of_birth)) : '',
            'country_id'        => $request->country_id,
            'state_id'          => $request->state_id,
            'city_id'           => $request->city_id,
            'postal_code'       => $request->postal_code,
            'account_gender_id' => $account_title->gender_id ?? '',
        ]);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Account has been created successfully. Your patient Id is: ' . $code,
                'code'    => $code
            ]);
        }

        return redirect()->route('accounts.index')
            ->with('success','Account has been created successfully.');
    }
    public function clientRegister()
    {
        $country         = Country::select(['id','name'])->get();
        $account_title   = AccountTitle::select(['id','name','value'])->where('status', '1')->get();
        $company_id      = \Auth::user()->company_id ?? '';
        $company_address = CompanyAddress::select([
                                'companies_addresses.country_id',
                                'companies_addresses.state_id',
                                'companies_addresses.city_id',
                            ])
                            ->where('companies.is_default', '1')
                            ->leftjoin('companies', 'companies.id', 'companies_addresses.company_id')
                            ->first();

        $country_id = $company_address->country_id ?? '';
        $state_id   = $company_address->state_id ?? '';
        $city_id    = $company_address->city_id ?? '';
        $companyData = Company::select('id', 'name', 'logo')->where('office_type','head_office')->first();
        $country_code = '';
        if($country_id)
        {
            $country_code    = Country::select(['code'])->find($country_id);
        }

        return view('auth.register',compact(
            'state_id',
            'city_id',
            'country_id',
            'country',
            'companyData',
            'account_title',
            'country_code'
        ));
    }

    public function clientRegisterStore(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name'       => 'required',
            'country_id' => 'required',
            'phone_no'   => 'required|unique:account_contacts',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $account_title = AccountTitle::select(['name'])->find($request->account_title_id);
        $account_type = MasterType::where('type_name', 'Customer')->first();

        $account = Account::create([
            'name'             => $request->name,
            'account_title_id' => $request->account_title_id,
            'account_type_id'  => $account_type->id,
            'created_by'       => \Auth::user()->id ?? ''
        ]);

        $account_type = MasterType::where('id', $account_type->id)->first(); // Use ->first() to get the actual model instance

        $count = 1;
        $prefix = "AC";

        if ($account_type) {
            $count = $account_type->count != '' ? $account_type->count + 1 : 1;
            $prefix = $account_type->prefix != '' ? $account_type->prefix : "AC";

            $account_type->update(['count' => $count]);
        }

        $code = $this->generateCode($count, $prefix);

        $account->update(['code' => $code]);

        $address = AccountAddress::create([
            'account_id'    => $account->id,
            'country_id'    => $request->country_id,
            'state_id'      => $request->state_id,
            'city_id'       => $request->city_id,
            'address_line1' => $request->address,
            'post_code'     => $request->postal_code,
            'is_default'    => '1'
        ]);

        $contact = AccountContact::create([
            'account_id'        => $account->id,
            'phone_no'          => $request->phone_no,
            'email'             => $request->email ?? '',
            'name'              => $request->name ?? '',
            'date_of_birth'     => $request->date_of_birth != '' ? date('Y-m-d', strtotime($request->date_of_birth)) : '',
            'country_id'        => $request->country_id,
            'state_id'          => $request->state_id,
            'city_id'           => $request->city_id,
            'postal_code'       => $request->postal_code,
            'account_gender_id' => $account_title->gender_id ?? '',
        ]);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Account has been created successfully. Your patient Id is: ' . $code,
                'code'    => $code
            ]);
        }

        return redirect()->route('accounts.index')
            ->with('success','Account has been created successfully.');
    }

    public function clientLicenseRegister()
    {
        $license = LicenseAuthentication::first();

        if ($license) {
            return redirect('login')->with('warning', "License already stored. Please contact Meta Mint Pvt Ltd.");
        }

        return view('auth.register-license');
    }

    public function clientLicenseRegisterStore(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'license_key'    => 'required|max:16',
            'license_secret' => 'required|max:64',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }
        $response = Http::asForm()->post(config('app.api_endpoint'), [
            'license_key'    => $request->license_key,
            'license_secret' => $request->license_secret,
        ]);

        $response = $response->body();

        $response = json_decode($response, true);

        if (isset($response['success']) & $response['success'] == true) {
            $data = $request->except(['_token', '_method']);
            $data['is_default'] = '1';
            $data['api_endpoint']      = config('app.api_endpoint');
            $data['api_endpoint_ip']   = config('app.api_endpoint_ip');
            $data['api_endpoint_port'] = config('app.api_endpoint_port');

            $data = LicenseAuthentication::firstOrCreate($data);

            $client = strtolower(str_replace('.','_',str_replace(' ','_',$_SERVER['HTTP_HOST'])));
            $checkMainFolder = StorageSetting::where('storage_type', 's3_bucket')->first();
            if(isset($checkMainFolder) && $checkMainFolder->main_folder==''){
                StorageSetting::where('storage_type', 's3_bucket')->update(['main_folder' => $client]);
            }
            if ($data) {
                return redirect('login')->with('success', "License validated successfully. Please login.");
            } else {
                return redirect()->back()->with('error', "License validation failed! Please contact Meta Mint Pvt Ltd.");
            }
        } else {
            return redirect()->back()->with('error', "License validation failed! Please contact Meta Mint Pvt Ltd.");
        }
    }
}
