<?php

namespace App\Http\Controllers;

use App\Models\Lead;
use App\Models\LeadSource;
use App\Models\User;
use Illuminate\Http\Request;

class LeadController extends Controller
{
    public function index(Request $request)
    {
        $query = Lead::with('agent');
        
        if ($request->search) {
            $query->where('name', 'like', '%' . $request->search . '%')
                  ->orWhere('phone', 'like', '%' . $request->search . '%')
                  ->orWhere('email', 'like', '%' . $request->search . '%');
        }
        
        $leads = $query->paginate(15);
        
        $userPrefs = \App\Models\UserPreference::where('user_id', \Illuminate\Support\Facades\Auth::id())
            ->where('module', 'leads')
            ->first();
            
        $visibleKeys = $userPrefs ? $userPrefs->visible_columns : ['name', 'phone', 'status', 'priority', 'agent', 'created_at'];

        $columns = [
            ['key' => 'name', 'label' => 'Name', 'visible' => in_array('name', $visibleKeys)],
            ['key' => 'phone', 'label' => 'Phone', 'visible' => in_array('phone', $visibleKeys)],
            ['key' => 'email', 'label' => 'Email', 'visible' => in_array('email', $visibleKeys)],
            ['key' => 'status', 'label' => 'Status', 'visible' => in_array('status', $visibleKeys)],
            ['key' => 'priority', 'label' => 'Priority', 'visible' => in_array('priority', $visibleKeys)],
            ['key' => 'agent', 'label' => 'Assigned Agent', 'visible' => in_array('agent', $visibleKeys)],
            ['key' => 'source', 'label' => 'Source', 'visible' => in_array('source', $visibleKeys)],
            ['key' => 'created_at', 'label' => 'Created Date', 'visible' => in_array('created_at', $visibleKeys)],
        ];

        return view('leads.index', compact('leads', 'columns', 'visibleKeys'));
    }

    public function create()
    {
        $sources = \App\Models\LeadSource::all();
        $statuses = \App\Models\MasterData::where('type', 'lead_status')->where('is_active', true)->orderBy('sort_order')->get();
        $priorities = \App\Models\MasterData::where('type', 'lead_priority')->where('is_active', true)->orderBy('sort_order')->get();
        $locations = \App\Models\MasterData::where('type', 'preferred_location')->where('is_active', true)->orderBy('sort_order')->get();
        
        $agents = \App\Models\User::role('Sales Agent')->get();
        $customFields = \App\Models\CustomField::where('model_type', \App\Models\Lead::class)
                            ->where('is_active', true)
                            ->orderBy('order')
                            ->get();

        return view('leads.create', compact('sources', 'statuses', 'priorities', 'locations', 'agents', 'customFields'));
    }

    public function export()
    {
        return \Maatwebsite\Excel\Facades\Excel::download(new \App\Exports\LeadsExport, 'leads.xlsx');
    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'phone' => 'nullable|string|max:20|unique:leads,phone',
            'email' => 'nullable|email|max:255',
            'cnic' => 'nullable|string|max:20|unique:leads,cnic',
            'whatsapp' => 'nullable|string|max:20',
            'lead_source_id' => 'nullable|exists:lead_sources,id',
            'assigned_agent_id' => 'nullable|exists:users,id',
            'status' => 'required|string',
            'priority' => 'required|string',
            'notes' => 'nullable|string',
        ];

        $customFields = \App\Models\CustomField::where('model_type', \App\Models\Lead::class)
                            ->where('is_active', true)
                            ->get();

        foreach ($customFields as $field) {
            $rule = $field->is_required ? 'required' : 'nullable';
            if ($field->type === 'Number' || $field->type === 'Currency') $rule .= '|numeric';
            $rules['custom_data.' . $field->key] = $rule;
        }

        $validated = $request->validate($rules);

        // Duplicate Detection
        if (!empty($validated['phone']) || !empty($validated['cnic'])) {
            $query = Lead::query();
            if (!empty($validated['phone'])) {
                $query->where('phone', $validated['phone']);
            }
            if (!empty($validated['cnic'])) {
                $query->orWhere('cnic', $validated['cnic']);
            }
            
            $duplicate = $query->first();
            
            if ($duplicate) {
                return back()->withInput()->with('error', 'A lead with this Phone or CNIC already exists: ' . $duplicate->name);
            }
        }

        Lead::create($validated);

        return redirect()->route('leads.index')->with('success', 'Lead created successfully.');
    }

    public function show(Lead $lead)
    {
        return view('leads.show', compact('lead'));
    }

    public function edit(Lead $lead)
    {
        $sources = \App\Models\LeadSource::all();
        $statuses = \App\Models\MasterData::where('type', 'lead_status')->where('is_active', true)->orderBy('sort_order')->get();
        $priorities = \App\Models\MasterData::where('type', 'lead_priority')->where('is_active', true)->orderBy('sort_order')->get();
        $locations = \App\Models\MasterData::where('type', 'preferred_location')->where('is_active', true)->orderBy('sort_order')->get();
        $agents = \App\Models\User::role('Sales Agent')->get();
        
        $customFields = \App\Models\CustomField::where('model_type', \App\Models\Lead::class)
                            ->where('is_active', true)
                            ->orderBy('order')
                            ->get();

        return view('leads.edit', compact('lead', 'sources', 'statuses', 'priorities', 'locations', 'agents', 'customFields'));
    }

    public function update(Request $request, Lead $lead)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'nullable|string|max:20|unique:leads,phone,' . $lead->id,
            'whatsapp' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'cnic' => 'nullable|string|max:20|unique:leads,cnic,' . $lead->id,
            'lead_source_id' => 'nullable|exists:lead_sources,id',
            'status' => 'required|string',
            'priority' => 'required|string',
            'assigned_agent_id' => 'nullable|exists:users,id',
            'notes' => 'nullable|string',
        ]);

        $lead->update($validated);

        return redirect()->route('leads.index')->with('success', 'Lead updated successfully.');
    }

    public function destroy(Lead $lead)
    {
        $lead->delete();
        return redirect()->route('leads.index')->with('success', 'Lead deleted successfully.');
    }

    public function convertToCustomer(Lead $lead)
    {
        // Check if customer already exists with this phone or cnic
        $query = \App\Models\Customer::query();
        if ($lead->phone) $query->where('phone', $lead->phone);
        if ($lead->cnic) $query->orWhere('cnic', $lead->cnic);
        
        $duplicate = $query->first();
        if ($duplicate) {
            return back()->with('error', 'A customer with this Phone or CNIC already exists: ' . $duplicate->full_name);
        }

        $customer = \App\Models\Customer::create([
            'full_name' => $lead->name,
            'phone' => $lead->phone,
            'email' => $lead->email,
            'cnic' => $lead->cnic,
            'whatsapp' => $lead->whatsapp,
            'customer_type' => 'Individual',
            'portal_password' => $lead->phone ?? '12345678',
        ]);

        $userIdentifier = $customer->phone ?: $customer->email;
        if ($userIdentifier) {
            $userQuery = \App\Models\User::query();
            if ($customer->phone) {
                $userQuery->where('phone', $customer->phone);
            } else {
                $userQuery->where('email', $customer->email);
            }
            
            $user = $userQuery->first();
            
            if (!$user) {
                $user = \App\Models\User::create([
                    'phone' => $customer->phone,
                    'email' => $customer->email,
                    'name' => $customer->full_name,
                    'password' => \Illuminate\Support\Facades\Hash::make($customer->portal_password)
                ]);
            }
            $user->assignRole('Customer');
            $customer->update(['user_id' => $user->id]);
        }

        // Mark lead as Won/Converted
        $wonStatus = \App\Models\MasterData::where('type', 'lead_status')->where('name', 'Won')->first();
        if ($wonStatus) {
            $lead->update(['status' => 'Won']);
        }

        return redirect()->route('customers.show', $customer->id)->with('success', 'Lead converted to customer successfully.');
    }
}
