<?php

namespace App\Livewire\User;

use Livewire\Component;
use App\Models\Lead;
use Livewire\Attributes\Layout;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Mail;
use App\Mail\AdminWholesaleNotification;
use App\Mail\CustomerConfirmation;
use Illuminate\Support\Facades\Log;

#[Layout('components.user-layout')]

class ApplyWholesale extends Component
{
    use WithFileUploads;

    // Form fields
    public $firstname;
    public $lastname;
    public $companyname;
    public $address_primary;
    public $address_secondary;
    public $country;
    public $state;
    public $city;
    public $email;
    public $phone;
    public $employeeid;
    public $seller_permit;
    public $period;
    public $location;
    public $reference;
    public $permit_doc;
    public $source;

    protected $rules = [
        'firstname' => 'required|string|max:255',
        'lastname' => 'required|string|max:255',
        'companyname' => 'nullable|string|max:255',
        'address_primary' => 'nullable|string',
        'address_secondary' => 'nullable|string',
        'country' => 'nullable|string|max:255',
        'state' => 'nullable|string|max:255',
        'city' => 'nullable|string|max:255',
        'email' => 'nullable|email|max:255',
        'phone' => 'nullable|numeric',
        'employeeid' => 'nullable|numeric',
        'seller_permit' => 'nullable|numeric',
        'period' => 'nullable|string|max:255',
        'location' => 'nullable|string|max:255',
        'reference' => 'nullable|string',
        'permit_doc' => 'nullable|file|max:10240', // 10MB max
    ];

    public function mount()
    {
        // Set source from session
        $this->source = session()->get('gad_source') ?? session()->get('utm_medium') ?? 'seo';
    }

    public function store()
    {
        $this->validate();

        try {
            // Handle file upload
            $permitDocPath = null;
            if ($this->permit_doc) {
                $permitDocPath = $this->permit_doc->store('permit-docs', 'public');
            }

            // Create lead
            $lead = Lead::create([
                'firstname' => $this->firstname,
                'lastname' => $this->lastname,
                'companyname' => $this->companyname,
                'address_primary' => $this->address_primary,
                'address_secondary' => $this->address_secondary,
                'country' => $this->country,
                'state' => $this->state,
                'city' => $this->city,
                'email' => $this->email,
                'phone' => $this->phone,
                'employeeid' => $this->employeeid,
                'seller_permit' => $this->seller_permit,
                'period' => $this->period,
                'location' => $this->location,
                'reference' => $this->reference,
                'permit_doc' => $permitDocPath,
                'source' => $this->source,
                'mail_count' => 0,
            ]);

            // Send emails
            $this->sendEmails($lead);

            // Reset form
            $this->reset();
            $this->source = session()->get('gad_source') ?? session()->get('utm_medium') ?? 'seo';

            // Success message
            session()->flash('success', 'Your wholesale application has been submitted successfully!');

        } catch (\Exception $e) {
            session()->flash('error', 'There was an error submitting your application. Please try again.');
        }
    }

    private function sendEmails($lead)
    {
        $result = ['success' => true, 'message' => ''];

        try {
            $adminEmail = 'syedmuneebullah01@gmail.com';
            Log::info('Attempting to send admin email', ['admin_email' => $adminEmail]);

            if ($adminEmail) {
                Mail::to($adminEmail)->send(new AdminWholesaleNotification($lead));
                Log::info('Admin email sent successfully');
                $result['message'] .= 'Admin notified. ';
            } else {
                Log::warning('No admin email configured');
                $result['message'] .= 'No admin email configured. ';
            }

            // Send confirmation email to customer
            if ($lead->email) {
                Log::info('Attempting to send customer email', ['customer_email' => $lead->email]);
                Mail::to($lead->email)->send(new CustomerConfirmation($lead));
                Log::info('Customer email sent successfully');
                $result['message'] .= 'Confirmation email sent.';
            } else {
                Log::info('No customer email provided, skipping customer notification');
                $result['message'] .= 'No customer email provided.';
            }

        } catch (\Exception $e) {
            Log::error('Email sending failed: ' . $e->getMessage());
            $result['success'] = false;
            $result['message'] = $e->getMessage();
        }

        return $result;
    }

    public function render()
    {
        return view('livewire.user.apply-wholesale');
    }
}