<?php

namespace App\Http\Controllers;

use App\Mail\CreateMasterDealerAccount;
use App\Models\MasterDealer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;


class MasterDealerController extends Controller
{
    public function index()
    {

        $dealers = MasterDealer::all();


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


    public function addDealer()
    {
        return view('pages.admin.master-dealer.dealer-add');
    }


    public function store(Request $request)
    {
        $companyName = $request->input('company_name');
        $contactPerson = $request->input('contact_person');
        $contactNumber = $request->input('contact_number');
        $email = $request->input('email');
        $state = $request->input('state');
        $status = $request->input('status') == 'active' ? 'active' : 'inactive';


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

        $dealer = MasterDealer::create([
            'master_dealer_id' => 'MD' . $paddedNum,
            'company_name' => $companyName,
            'contact_person' => $contactPerson,
            'contact_number' => $contactNumber,
            'email' => $email,
            'state' => $state,
            'status' => $status,
            'password' => Hash::make($contactNumber),
        ]);

        if ($dealer) {
            Mail::to($email)->send(new CreateMasterDealerAccount($dealer, $contactNumber));

            
            return redirect()->route('admin.dealers')->with('success', 'Dealer added successfully');
        } else {
            return back()->with('error', 'Dealer not added');
        }
    }

    public function transferLicense(Request $request)
    {
        $masterDealerId = $request->input('master_dealer_id');
        $licenseQty = $request->input('license_qty');

        $masterDealer = MasterDealer::where('master_dealer_id', $masterDealerId)->first();

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

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


    }


}
