<?php

namespace App\Livewire;

use App\Models\Kyc;
use App\Models\User;
use App\Rules\StrongPassword;
use App\Services\OTPService;
use App\Utils\Roles;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Livewire\Component;
use Illuminate\Support\Str;
use Livewire\WithFileUploads; // Import trait for file uploads
use Illuminate\Validation\Rules;


class Register extends Component
{
    use WithFileUploads;

    // Step Tracker
    public $currentStep = 1;

    // Step 1: User Info (Existing)
    public $first_name, $last_name, $email, $phone, $password, $password_confirmation;

    // Step 2: Company Info (New)
    public $company_name, $website_link, $business_type;
    public $nin_image, $cac_image, $utility_bill_image; 


    public $settlement_account_name, $bank, $settlement_account_number;


    public function mount()
    {
        
        if (request()->has('referral')) {
            $nextSevenDays = 7 * 24 * 60;
            cookie()->queue('referral', request()->referral, $nextSevenDays);
        }
    }

    private function generateUniqueMerchantId(): string
    {
        do {
            
            $merchantId = 'M' . Str::random(8);
        } while (User::where('merchant_id', $merchantId)->exists());

        return $merchantId;
    }



    public function render()
    {
        
        return view('livewire.register')->extends('layouts.auth');
    }



    private function stepOneRules()
    {
        return [
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:' . User::class],
            'phone' => ['nullable', 'string', 'digits_between:10,12', 'unique:' . User::class],
            'password' => ['required', 'confirmed', new StrongPassword],
        ];
    }

    private function stepTwoRules()
    {
        return [
            'company_name' => ['required', 'string', 'max:255'],
            'website_link' => ['nullable', 'url', 'max:255'],
            'business_type' => ['required', 'string', 'max:255'],
            'nin_image' => ['required', 'image', 'max:1024'], // 1MB Max
            'cac_image' => ['required', 'image', 'max:1024'],
            'utility_bill_image' => ['required', 'image', 'max:1024'],
        ];
    }

    private function stepThreeRules()
    {
        return [
            'settlement_account_name' => ['required', 'string', 'max:255'],
            'bank' => ['required', 'string', 'max:255'],
            'settlement_account_number' => ['required', 'string', 'digits:10'], 
        ];
    }


    

    public function firstStepSubmit()
    {
        $this->validate($this->stepOneRules());
        $this->currentStep = 2;
    }

    public function secondStepSubmit()
    {
        $this->validate($this->stepTwoRules());
        $this->currentStep = 3;
    }

    public function back($step)
    {
        $this->currentStep = $step;
    }


  
    public function store()
    {
       
        $this->validate(array_merge(
            $this->stepOneRules(),
            $this->stepTwoRules(),
            $this->stepThreeRules()
        ));

        
        $ninPath = $this->nin_image->store('business_docs', 'public');
        $cacPath = $this->cac_image->store('business_docs', 'public');
        $utilityPath = $this->utility_bill_image->store('business_docs', 'public');

        $merchantId = $this->generateUniqueMerchantId();

        
        $user = User::create([
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'email' => $this->email,
            'phone' => $this->phone,
            'password' => Hash::make($this->password),
            'wallet_balance' => 0.00,
            'merchant_id' => $merchantId,
            
            'company_name' => $this->company_name,
            'website_link' => $this->website_link,
            'business_type' => $this->business_type,
            'nin_image_path' => $ninPath,
            'cac_image_path' => $cacPath,
            'utility_bill_path' => $utilityPath,

          
            'kyc_status' => Kyc::STATUS_UNVERIFIED,
            'platform' => User::PLATFORM_WEB,
        ]);
        
        
        $user->bankAccounts()->create([ 
            'account_name' => $this->settlement_account_name,
            'bank_name' => $this->bank,
            'account_number' => $this->settlement_account_number,
            'is_default' => true,
        ]);


        
        $otp_service = new OTPService();
        $response = $otp_service->generateOTP($user->email);

        if ($response['status'] == 'error') {
            
            $user->delete(); 
            return redirect()->route('register')->with('error', $response['message']);
        }

        // 5. Login and Redirect
        // $user->assignRole(Roles::CUSTOMER);
        Auth::login($user);
        session()->put('login_verified', true);

        return redirect()->route('verification');
    }
}