<?php

namespace App\Observers;

use App\Models\Lead;
use App\Models\Order;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class LeadObserver
{
    /**
     * Handle the Lead "updated" event.
     */
    public function updated(Lead $lead): void
    {
        // When a lead is marked as 'converted', we create an order
        if ($lead->isDirty('status') && $lead->status === 'converted') {
            $this->createOrderFromLead($lead);
        }
    }

    /**
     * Create an order and user (if needed) from a converted lead.
     */
    protected function createOrderFromLead(Lead $lead): void
    {
        // 1. Ensure a User exists for this lead
        $user = $lead->user;

        if (!$user) {
            // Check if email already registered
            $user = User::where('email', $lead->email)->first();

            if (!$user) {
                // Ensure name is not null
                $name = $lead->name ?? (explode('@', $lead->email)[0] ?? 'Customer');
                if (empty(trim($name))) {
                    $name = 'Customer';
                }

                // Create a new customer account
                $user = User::create([
                    'name' => $name,
                    'email' => $lead->email,
                    'password' => Hash::make(Str::random(12)),
                ]);
            }
            
            $lead->user_id = $user->id;
            $lead->saveQuietly();
        }

        // 2. Create the Order
        $serviceId = $lead->offer?->service_id ?? null;

        Order::create([
            'user_id' => $user->id,
            'service_id' => $serviceId,
            'status' => 'pending',
            'payment_status' => 'pending',
            'notes' => "Converted from Lead: " . ($lead->notes ?? 'No notes provided.'),
            'admin_notes' => "Auto-generated from lead conversion system.",
            'total_amount' => 0, // Admin will set this manually
            'currency' => 'PKR',
        ]);
    }
}
