<?php

namespace App\Http\Controllers;

use App\Mail\CreateSubDealerAccount;
use App\Models\CompanyDealer;
use App\Models\CompanyProfile;
use App\Models\Dealer;
use App\Models\EzyPOSLicense;
use App\Models\MasterDealer;
use App\Models\SubDealer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;

class SubDealerController extends Controller
{
    public function index()
    {

        if (Auth::guard('admin')->check()) {
            $masterDealerList = MasterDealer::all();

            $dealers = SubDealer::with('masterDealer')->get();

            return view('pages.admin.sub-dealer.dealer-list')->with(compact('dealers', 'masterDealerList'));
        } elseif (Auth::guard('master-dealer')->check()) {


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

            $maxLicense = $masterDealer->total_license - $masterDealer->used_license;
            $dealers = SubDealer::where('master_dealer_id', $masterDealer->master_dealer_id)->get();

            return view('pages.master-dealer.dealer-list')->with(compact('dealers', 'maxLicense'));
        }


    }

    public function addSubDealer()
    {

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

        return view('pages.master-dealer.dealer-add')->with(
            compact('dealer')
        );
    }

    public function store(Request $request)
    {
        $dealer = Auth::guard('master-dealer')->user();

        $companyName = $request->company_name;
        $contactPerson = $request->contact_person;
        $contactNumber = $request->contact_number;
        $email = $request->email;
        $state = $request->state;
        $status = $request->status == 'active' ? 'active' : 'inactive';


        $request->validate([
            'company_name' => 'required',
            'contact_person' => 'required',
            'contact_number' => 'required',
            'email' => 'required|email|unique:sub_dealers',
            'state' => 'required',
        ]);


        $password = Str::random(8);
        $hashedPassword = Hash::make($password);

        $latestSubDealer = SubDealer::latest()->first();
        if ($latestSubDealer == null) {
            $latestSubDealerId = 0;
        } else {
            $latestSubDealerId = $latestSubDealer->id;
        }
        $paddedNum = str_pad($latestSubDealerId + 1, 4, '0', STR_PAD_LEFT);

        $subDealer = SubDealer::create([
            'sub_dealer_id' => 'SD' . $paddedNum,
            'company_name' => $companyName,
            'contact_person' => $contactPerson,
            'contact_number' => $contactNumber,
            'email' => $email,
            'state' => $state,
            'status' => $status,
            'password' => $hashedPassword,
            'master_dealer_id' => $dealer->master_dealer_id,
            'total_license' => 0,
            'used_license' => 0,
        ]);

        Mail::to($email)->send(new CreateSubDealerAccount($subDealer, $password));


        return redirect()->route('master-dealer.dealers.add-view')->with('success', 'Sub Dealer created successfully');

    }

    public function transferLicense(Request $request)
    {

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

        $subDealerId = $request->input('sub_dealer_id');
        $licenseQty = $request->input('license_qty');

        $subDealer = SubDealer::where('sub_dealer_id', $subDealerId)->first();

        $previousLicenseQty = $subDealer->total_license;

        $subDealer->total_license = $subDealer->total_license + $licenseQty;

        $masterDealer->used_license = $masterDealer->used_license + $licenseQty;

        $domain = $request->getHost();

        //Generate License Key
        //EZY01-SD0001-MD0001-00001


        //Sub Dealer's License Qty
        $subDealerLicenseQty = $previousLicenseQty;

        for ($i = 0; $i < $licenseQty; $i++) {

            $paddedNum = str_pad($subDealerLicenseQty + 1, 5, '0', STR_PAD_LEFT);


            $licenseKey = 'EZY01-' . $masterDealer->master_dealer_id . '-' . $subDealer->sub_dealer_id . '-' . $paddedNum;

            EzyPOSLicense::create([
                'license_key' => $licenseKey,
                'sub_dealer_id' => $subDealer->sub_dealer_id,
                'master_dealer_id' => $masterDealer->master_dealer_id,
                'app_id' => '',
                'status' => 'active',
                'cloud_id' => '',
                'license_type' => 'standalone',
                'api_server_url' => $domain,
            ]);

            $subDealerLicenseQty++;
        }


        if ($subDealer->save() && $masterDealer->save()) {
            return response()->json(['success' => true, 'message' => 'License added successfully']);
        } else {
            return response()->json(['success' => false, 'message' => 'License not added']);
        }

    }

    public function prospectTransferToCustomer(Request $request)
    {
        $trialCompanyId = $request->input('trial_company_id');
    }


    public function showCustomerInfo($customerId)
    {

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

        $companyDealer = CompanyDealer::where('company_id', $customerId)->where('sub_dealer_id', $dealerId)->first();
        if ($companyDealer == null) {
            return redirect()->route('sub-dealer.licenses')->with('error', 'Customer not found');
        }


        $companyProfile = CompanyProfile::where('company_id', $customerId)->first();

        return view('pages.sub-dealer.customer-info')->with(compact('companyProfile'));
    }
}
