<?php

namespace App\Livewire\Customers;

use Livewire\Component;
use App\Models\Customer;
use App\Models\User;
use App\Models\Role;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class Edit extends Component
{
    public Customer $customer;

    // Customer fields
    public $first_name = '';
    public $last_name = '';
    public $email = '';
    public $phone = '';
    public $secondary_phone = '';
    public $address = '';
    public $city = '';
    public $state = '';
    public $zip_code = '';
    public $notes = '';
    public $status = 'active';

    // User account management
    public $has_user_account = false;
    public $create_user_account = false;
    public $reset_password = false;
    public $new_password = '';
    public $user_status = 'active';

    protected $rules = [
        'first_name' => 'required|string|max:255',
        'last_name' => 'required|string|max:255',
        'email' => 'required|email|max:255',
        'phone' => 'required|string|max:20',
        'secondary_phone' => 'nullable|string|max:20',
        'address' => 'required|string|max:500',
        'city' => 'required|string|max:255',
        'state' => 'required|string|max:255',
        'zip_code' => 'required|string|max:10',
        'notes' => 'nullable|string|max:1000',
        'status' => 'required|in:active,inactive',
        'new_password' => 'required_if:reset_password,true|min:8|nullable',
    ];

    public function mount(Customer $customer)
    {
        $this->customer = $customer->load('user');
        
        // Load customer data
        $this->first_name = $customer->first_name;
        $this->last_name = $customer->last_name;
        $this->email = $customer->email;
        $this->phone = $customer->phone;
        $this->secondary_phone = $customer->secondary_phone;
        $this->address = $customer->address;
        $this->city = $customer->city;
        $this->state = $customer->state;
        $this->zip_code = $customer->zip_code;
        $this->notes = $customer->notes;
        $this->status = $customer->status;

        // Check if customer has user account (regardless of role status)
        $this->has_user_account = $customer->user !== null;
        
        if ($customer->user) {
            $this->user_status = $customer->user->status;
        }

        // Generate random password for reset
        $this->new_password = Str::random(12);
    }

    public function generatePassword()
    {
        $this->new_password = Str::random(12);
    }

    public function updateCustomer()
    {
        // Update validation rules to exclude current customer's email
        $rules = $this->rules;
        $rules['email'] = 'required|email|max:255|unique:customers,email,' . $this->customer->id;
        
        if ($this->create_user_account && !$this->has_user_account) {
            $rules['email'] .= '|unique:users,email';
        }

        $this->validate($rules);

        DB::transaction(function () {
            // Update customer record
            $this->customer->update([
                'first_name' => $this->first_name,
                'last_name' => $this->last_name,
                'email' => $this->email,
                'phone' => $this->phone,
                'secondary_phone' => $this->secondary_phone,
                'address' => $this->address,
                'city' => $this->city,
                'state' => $this->state,
                'zip_code' => $this->zip_code,
                'notes' => $this->notes,
                'status' => $this->status,
            ]);

            // Handle user account creation
            if ($this->create_user_account && !$this->has_user_account) {
                $user = User::create([
                    'name' => $this->first_name . ' ' . $this->last_name,
                    'email' => $this->email,
                    'password' => Hash::make($this->new_password),
                    'phone' => $this->phone,
                    'status' => 'active',
                ]);

                // Assign customer_portal role
                $customerRole = Role::where('name', 'customer_portal')->first();
                if ($customerRole) {
                    $user->roles()->attach($customerRole->id, [
                        'is_active' => true,
                        'assigned_at' => now(),
                    ]);
                }

                // Link customer to user
                $this->customer->update(['user_id' => $user->id]);
            }

            // Handle existing user account updates
            if ($this->has_user_account && $this->customer->user) {
                $userUpdates = [
                    'name' => $this->first_name . ' ' . $this->last_name,
                    'email' => $this->email,
                    'phone' => $this->phone,
                    'status' => $this->user_status,
                ];

                if ($this->reset_password) {
                    $userUpdates['password'] = Hash::make($this->new_password);
                }

                $this->customer->user->update($userUpdates);

                // Update customer_portal role activation based on user status
                $customerRole = Role::where('name', 'customer_portal')->first();
                if ($customerRole) {
                    // Check if user has the role
                    $existingRole = $this->customer->user->roles()->where('role_id', $customerRole->id)->first();
                    
                    if ($existingRole) {
                        // Update the role's is_active status based on user_status
                        $this->customer->user->roles()->updateExistingPivot($customerRole->id, [
                            'is_active' => $this->user_status === 'active'
                        ]);
                    } elseif ($this->user_status === 'active') {
                        // If role doesn't exist and user should be active, add it
                        $this->customer->user->roles()->attach($customerRole->id, [
                            'is_active' => true,
                            'assigned_at' => now(),
                        ]);
                    }
                }
            }
        });

        $message = 'Customer updated successfully!';
        if ($this->create_user_account && !$this->has_user_account) {
            $message .= ' User account created with password: ' . $this->new_password;
        } elseif ($this->reset_password) {
            $message .= ' Password reset to: ' . $this->new_password;
        }

        session()->flash('success', $message);

        return $this->redirect('/customers/' . $this->customer->id, navigate: true);
    }

    public function render()
    {
        return view('livewire.customers.edit');
    }
}
