<?php

namespace App\Livewire;

use App\Helpers\SmsHelper;
use App\Models\Quote;
use App\Models\QuoteItem;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Request Quote')]
#[Layout('components.layouts.app')]
class RequestQuote extends Component
{
    // Quote form fields
    public $name = '';
    public $companyName = '';
    public $service = '';
    public $phone = '';
    public $email = '';
    public $district = '';
    public $region = '';
    public $address = '';
    public $note = '';

    #[Computed]
    public function company()
    {
        return DB::table('companies')->where('id', 1)->first();
    }

    #[Computed]
    public function serviceCategories()
    {
        return DB::table('service_categories')
            ->where('is_active', 1)
            ->orderBy('order')
            ->get();
    }

    public function submitQuote()
    {
        $this->validate([
            'name' => 'required|string|max:255',
            'companyName' => 'nullable|string|max:255',
            'service' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'email' => 'required|email|max:255',
            'district' => 'nullable|string|max:255',
            'region' => 'nullable|string|max:255',
            'address' => 'nullable|string|max:500',
            'note' => 'nullable|string',
        ]);

        try {
            DB::beginTransaction();

            // Create quote
            $quote = Quote::create([
                'name' => $this->name,
                'company' => $this->companyName,
                'service' => $this->service,
                'phone' => $this->phone,
                'email' => $this->email,
                'district' => $this->district,
                'region' => $this->region,
                'address' => $this->address,
                'note' => $this->note,
                'mobile' => $this->phone, // Keep mobile for backward compatibility
                'description' => $this->note, // Keep description for backward compatibility
                'status' => 'pending',
            ]);

            DB::commit();

            // Send notifications
            $this->sendNotifications($quote);

            // Reset form
            $this->reset(['name', 'companyName', 'service', 'phone', 'email', 'district', 'region', 'address', 'note']);
            
            // Redirect to refresh with success message
            return redirect()->route('request-quote')->with('success', 'Consultation request submitted successfully! Consultation Number: ' . $quote->quote_number);
            
        } catch (\Exception $e) {
            DB::rollBack();
            \Illuminate\Support\Facades\Log::error('Quote submission failed: ' . $e->getMessage(), [
                'exception' => $e,
                'trace' => $e->getTraceAsString()
            ]);
            session()->flash('error', 'Failed to submit quote request. Please try again or contact us directly.');
        }
    }

    protected function sendNotifications($quote)
    {
        $companyData = $this->company;
        
        // Send email notification
        if ($companyData && $companyData->email) {
            try {
                \Illuminate\Support\Facades\Mail::to($companyData->email)
                    ->send(new \App\Mail\QuoteNotification($quote));
            } catch (\Exception $e) {
                \Illuminate\Support\Facades\Log::error('Failed to send quote email: ' . $e->getMessage());
            }
        }

        // Send SMS notification
        if ($companyData && $companyData->mobile) {
            $smsMessage = "New Quote Request {$quote->quote_number} from {$quote->name}. Service: {$quote->service}. Phone: {$quote->phone}";
            try {
                SmsHelper::send($companyData->mobile, $smsMessage);
            } catch (\Exception $e) {
                \Illuminate\Support\Facades\Log::error('Failed to send quote SMS: ' . $e->getMessage());
            }
        }
    }

    public function render()
    {
        return view('livewire.request-quote');
    }
}
