<?php

namespace App\Http\Controllers;

use App\Mail\PurchaseAccountEmail;
use App\Models\CompanyDealer;
use App\Models\CompanyProfile;
use App\Models\EzyPOS;
use App\Models\EzyPOSAppId;
use App\Models\EzyPOSLicense;
use App\Models\TrialCompanyDealer;
use App\Models\TrialCompanyProfile;
use App\Models\TrialEzyPOS;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;

class EzyPOSLicenseController extends Controller
{
    public function subDealerLicense()
    {

        $dealer = Auth::guard('sub-dealer')->user();
        $licenses = EzyPOSLicense::with('app.company')->where('sub_dealer_id', $dealer->sub_dealer_id)->get();

//        return response($licenses->toJson());

        return view('pages.sub-dealer.license-list')->with(
            compact('dealer', 'licenses')
        );
    }


    public function assignLicenseView(Request $request){

        return view('pages.sub-dealer.assign-license');
    }

    public function assignLicense(Request $request)
    {
        $this->validate($request, [
            'license_key' => 'required|string',
            'ezypos_appid' => 'required|string'
        ]);

        $licenseKey = $request->input('license_key');
        $dealer = Auth::guard('sub-dealer')->user();

        $ezyposAppId = $request->input('ezypos_appid');


        $ezyposAppIdExist = EzyPOSAppId::where('app_id', $ezyposAppId)->where('license_type', 'trial')->first();
        if ($ezyposAppIdExist == null) {
            return response()->json([
                'status' => 'error',
                'message' => 'EzyPOS App ID Not Found'
            ], 202);
        }


        try {

            $trialEzypos = TrialEzyPOS::where('app_id', $ezyposAppId)->first();
            $trialCompanyProfile = TrialCompanyProfile::where('company_id', $trialEzypos->company_id)->first();
            $trialCompanyDealer = TrialCompanyDealer::where('trial_company_id', $trialEzypos->company_id)->first();

            //Check email exist or not
            $tempCompanyEmail = $trialCompanyProfile->email;
            $checkEmailExist = CompanyProfile::where('email', $tempCompanyEmail)->first();
            if ($checkEmailExist != null) {
                return response()->json([
                    'status' => 'error',
                    'message' => "Customer's Email Already Exist, Please Contact Customer change to Another Email"
                ], 202);
            }



            $ezyposLicense = EzyPOSLicense::where('sub_dealer_id', $dealer->sub_dealer_id)
                ->where('master_dealer_id', $dealer->master_dealer_id)
                ->where('license_key', $licenseKey)->first();

            $latestCompanyProfile = CompanyProfile::latest()->first();
            if ($latestCompanyProfile == null) {
                $latestCompanyId = 0;
            } else {
                $latestCompanyId = $latestCompanyProfile->id;
            }
            $paddedNum = str_pad($latestCompanyId + 1, 7, '0', STR_PAD_LEFT);

            $companyProfile = CompanyProfile::create([
                'company_id' => 'Paid-' . $paddedNum,
                'company_name' => $trialCompanyProfile->company_name,
                'contact_name' => $trialCompanyProfile->contact_name,
                'contact_number' => $trialCompanyProfile->contact_number,
                'roc' => $trialCompanyProfile->roc,
                'address1' => $trialCompanyProfile->address1,
                'address2' => $trialCompanyProfile->address2,
                'address3' => $trialCompanyProfile->address3,
                'address4' => $trialCompanyProfile->address4,
                'state' => $trialCompanyProfile->state,
                'postcode' => $trialCompanyProfile->postcode,
                'email' => $trialCompanyProfile->email,
                'raw_password' => $trialCompanyProfile->raw_password,
                'password' => $trialCompanyProfile->password,
                'geo_location' => $trialCompanyProfile->geo_location,
            ]);

            $companyDealer = CompanyDealer::create([
                'company_id' => $companyProfile->company_id,
                'master_dealer_id' => $trialCompanyDealer->master_dealer_id,
                'sub_dealer_id' => $dealer->sub_dealer_id,
            ]);

            $ezypos = EzyPOS::create([
                'company_id' => $companyProfile->company_id,
                'app_id' => $ezyposAppId,
                'pin' => $trialEzypos->pin,
                'last_login' => null,
                'last_modified' => null,
                'registered_date' => Carbon::now(),
                'expiry_date' => Carbon::now()->addCenturies(),
            ]);

            $ezyposAppIdExist->update([
                'license_type' => 'paid',
            ]);

            $ezyposLicense->update([
                'app_id' => $ezyposAppId,
                'registered_date' => Carbon::now(),
            ]);

            $dealer->update([
                'used_license' => $dealer->used_license + 1,
            ]);




            if ($companyProfile->save() && $companyDealer->save() && $ezypos->save()) {

                $trialEzypos->delete();
                $trialCompanyProfile->delete();
                $trialCompanyDealer->delete();
                
                Mail::to($companyProfile->email)->send(new PurchaseAccountEmail($companyProfile, $ezypos));


                return response()->json([
                    'status' => 'success',
                    'message' => 'EzyPOS License Assigned Successfully',

                ]);
            } else {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Something went wrong'
                ], 202);
            }


        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Something went wrong',
                'error' => $e->getMessage()
            ], 202);
        }

    }

    public function updateLicenseStatus(Request $request)
    {

        $this->validate($request, [
            'license_key' => 'required|string',
        ]);


        try {
            $licenseKey = $request->input('license_key');

            $dealer = Auth::guard('sub-dealer')->user();

            $ezyposLicense = EzyPOSLicense::where('sub_dealer_id', $dealer->sub_dealer_id)
                ->where('master_dealer_id', $dealer->master_dealer_id)
                ->where('license_key', $licenseKey)->first();

            if ($ezyposLicense->status == 'active') {
                $ezyposLicense->update([
                    'status' => 'inactive',
                ]);
                return response()->json([
                    'status' => 'success',
                    'message' => 'EzyPOS License Deactivated Successfully',
                ]);
            } else {
                $ezyposLicense->update([
                    'status' => 'active',
                ]);
                return response()->json([
                    'status' => 'success',
                    'message' => 'EzyPOS License Activated Successfully',
                ]);
            }


        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Something went wrong',
                'error' => $e->getMessage()
            ], 202);
        }


    }

    public function transferLicense(Request $request){
        $this->validate($request, [
            'license_key' => 'required|string',
            'ezypos_appid' => 'required|string'
        ]);


        try {
            $newAppId = $request->input('ezypos_appid');
            $licenseKey = $request->input('license_key');
            $dealer = Auth::guard('sub-dealer')->user();

            $newAppIdExist = EzyPOSAppId::where('app_id', $newAppId)->first();
            if ($newAppIdExist) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'EzyPOS App ID invalid',
                ], 202);
            }

            $ezyposLicense = EzyPOSLicense::where('sub_dealer_id', $dealer->sub_dealer_id)
                ->where('master_dealer_id', $dealer->master_dealer_id)
                ->where('license_key', $licenseKey)->first();

            $oldAppId = $ezyposLicense->app_id;

            $ezypos = EzyPOS::where('app_id', $oldAppId)->first();
            $ezyposAppId = EzyPOSAppId::where('app_id', $oldAppId)->first();


            $ezyposLicense->update([
                'app_id' => $newAppId,
                'change_license_count' => $ezyposLicense->change_license_count + 1,
            ]);

            $ezypos->update([
                'app_id' => $newAppId,
            ]);

            $ezyposAppId->update([
                'app_id' => $newAppId,
            ]);


            return response()->json([
                'status' => 'success',
                'message' => 'EzyPOS License Transferred Successfully',
            ]);

        }catch (Exception $e){
            return response()->json([
                'status' => 'error',
                'message' => 'Something went wrong',
                'error' => $e->getMessage()
            ], 202);
        }
    }


    public function transferLicenseType(Request $request){
        $this->validate($request, [
            'license_key' => 'required|string',
            'license_type' => 'required|string'
        ]);


        try {
            $licenseKey = $request->input('license_key');
            $licenseType = $request->input('license_type');
            $dealer = Auth::guard('sub-dealer')->user();

            $ezyposLicense = EzyPOSLicense::where('sub_dealer_id', $dealer->sub_dealer_id)
                ->where('master_dealer_id', $dealer->master_dealer_id)
                ->where('license_key', $licenseKey)->first();

            $ezyposLicense->update([
                'license_type' => $licenseType,
            ]);

            return response()->json([
                'status' => 'success',
                'message' => 'EzyPOS License Type Changed Successfully',
            ]);
        }catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Something went wrong',
                'error' => $e->getMessage()
            ], 202);


        }
    }
}
