<?php

namespace App\Http\Controllers;

use App\Models\Lead;
use App\Models\Employee;
use App\Models\Leadnote;
use Illuminate\Http\Request;

class LeadController extends Controller
{
    private $stages   = ['New','Contacted','Positive','Follow Up','Negotiation','Won','Lost'];
    private $sources  = ['Website','WhatsApp','Phone Call','Referral','Email','Walk-in','LinkedIn'];
    private $services = ['Website Design','SEO Package','Website + SEO','App Development','Digital Marketing','Hosting','Other'];
    private $priorities = ['High','Medium','Low'];

    // ── INDEX ─────────────────────────────────────────────────────────────────
    public function index(Request $req)
    {
        $query = Lead::with('employee');

        if ($q = $req->q) {
            $query->where(function($qb) use ($q) {
                $qb->where('name','like',"%$q%")
                   ->orWhere('company','like',"%$q%")
                   ->orWhere('phone','like',"%$q%")
                   ->orWhere('email','like',"%$q%");
            });
        }
        if ($req->stage)    $query->where('stage', $req->stage);
        if ($req->source)   $query->where('source', $req->source);
        if ($req->priority) $query->where('priority', $req->priority);
        if ($req->assigned) $query->where('assigned_to', $req->assigned);

        $leads     = $query->orderByDesc('updated_at')->get();
        $employees = Employee::where('status','Active')->get();

        return view('leads.index', [
            'leads'      => $leads,
            'employees'  => $employees,
            'stages'     => $this->stages,
            'sources'    => $this->sources,
            'filters'    => $req->only(['q','stage','source','priority','assigned']),
        ]);
    }

    // ── CREATE ────────────────────────────────────────────────────────────────
    public function create()
    {
        $employees = Employee::where('status','Active')->get();
        return view('leads.form', [
            'lead'       => null,
            'employees'  => $employees,
            'stages'     => $this->stages,
            'sources'    => $this->sources,
            'services'   => $this->services,
            'priorities' => $this->priorities,
        ]);
    }

    // ── STORE ─────────────────────────────────────────────────────────────────
    public function store(Request $req)
    {
        $req->validate([
            'name'        => 'required|string|max:100',
            'phone'       => 'required|string|max:20',
            'source'      => 'required|in:' . implode(',', $this->sources),
            'assigned_to' => 'required|exists:employees,id',
            'note'        => 'required|string',
        ]);

        $lead = Lead::create([
            'name'        => $req->name,
            'company'     => $req->company,
            'phone'       => $req->phone,
            'email'       => $req->email,
            'source'      => $req->source,
            'service'     => $req->service,
            'budget'      => (int) preg_replace('/[^0-9]/', '', $req->budget ?? '0'),
            'stage'       => $req->stage ?? 'New',
            'assigned_to' => $req->assigned_to,
            'priority'    => $req->priority ?? 'Medium',
            'last_contact'=> now(),
        ]);

        // Auto-create first note
        $emp = Employee::find($req->assigned_to);
        Leadnote::create([
            'lead_id'      => $lead->id,
            'added_by'     => $emp->name ?? 'Admin',
            'avatar_color' => $emp->avatar_color ?? '#1a73e8',
            'via'          => 'Note',
            'note'         => $req->note,
        ]);

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

    // ── SHOW (detail drawer – returns partial view via AJAX) ──────────────────
    // public function show(Lead $lead)
    // {
    //     $lead->load('employee', 'notes');
    //     $employees = Employee::where('status','Active')->get();
    //     return view('leads.show', compact('lead','employees'));
    // }
    // ── SHOW (detail drawer – returns partial view via AJAX) ──────────────────
    public function show(Request $req, Lead $lead)
    {
        $lead->load('employee', 'notes');
        $employees = Employee::where('status','Active')->get();

        if ($req->ajax() || $req->wantsJson()) {
            return view('leads.show-drawer', compact('lead','employees'));
        }

        return view('leads.show', compact('lead','employees'));
    }
    
    // ── EDIT ──────────────────────────────────────────────────────────────────
    public function edit(Lead $lead)
    {
        $employees = Employee::where('status','Active')->get();
        return view('leads.form', [
            'lead'       => $lead,
            'employees'  => $employees,
            'stages'     => $this->stages,
            'sources'    => $this->sources,
            'services'   => $this->services,
            'priorities' => $this->priorities,
        ]);
    }

    // ── UPDATE ────────────────────────────────────────────────────────────────
    public function update(Request $req, Lead $lead)
    {
        $req->validate([
            'name'        => 'required|string|max:100',
            'phone'       => 'required|string|max:20',
            'source'      => 'required',
            'assigned_to' => 'required|exists:employees,id',
        ]);

        $old = $lead->stage;
        $lead->update([
            'name'        => $req->name,
            'company'     => $req->company,
            'phone'       => $req->phone,
            'email'       => $req->email,
            'source'      => $req->source,
            'service'     => $req->service,
            'budget'      => (int) preg_replace('/[^0-9]/', '', $req->budget ?? '0'),
            'stage'       => $req->stage,
            'assigned_to' => $req->assigned_to,
            'priority'    => $req->priority ?? 'Medium',
            'last_contact'=> now(),
        ]);

        if ($req->note) {
            Leadnote::create([
                'lead_id'      => $lead->id,
                'added_by'     => 'Admin',
                'avatar_color' => '#1a73e8',
                'via'          => 'Note',
                'note'         => $req->note,
            ]);
        }

        if ($old !== $req->stage) {
            Leadnote::create([
                'lead_id'      => $lead->id,
                'added_by'     => 'Admin',
                'avatar_color' => '#1a73e8',
                'via'          => 'Note',
                'note'         => 'Stage changed from "' . $old . '" to "' . $req->stage . '".',
            ]);
        }

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

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

    // ── QUICK STAGE CHANGE (AJAX) ─────────────────────────────────────────────
    public function updateStage(Request $req, Lead $lead)
    {
        $lead->update(['stage' => $req->stage, 'last_contact' => now()]);
        Leadnote::create([
            'lead_id'      => $lead->id,
            'added_by'     => 'Admin',
            'avatar_color' => '#1a73e8',
            'via'          => 'Note',
            'note'         => 'Stage changed to "' . $req->stage . '".',
        ]);
        return response()->json(['success' => true]);
    }

    // ── QUICK ASSIGN CHANGE (AJAX) ────────────────────────────────────────────
    public function updateAssign(Request $req, Lead $lead)
    {
        $old = $lead->employee->name ?? 'Unassigned';
        $lead->update(['assigned_to' => $req->assigned_to, 'last_contact' => now()]);
        $emp = Employee::find($req->assigned_to);
        Leadnote::create([
            'lead_id'      => $lead->id,
            'added_by'     => 'Admin',
            'avatar_color' => '#1a73e8',
            'via'          => 'Note',
            'note'         => 'Reassigned from "' . $old . '" to "' . ($emp->name ?? '--') . '".',
        ]);
        return response()->json(['success' => true]);
    }

    // ── EXPORT CSV ────────────────────────────────────────────────────────────
    public function exportCsv()
    {
        $leads = Lead::with('employee')->orderByDesc('updated_at')->get();
        $headers = ['Content-Type'=>'text/csv','Content-Disposition'=>'attachment; filename="leads.csv"'];
        $cb = function() use ($leads) {
            $f = fopen('php://output', 'w');
            fputcsv($f, ['#','Name','Company','Phone','Email','Source','Service','Budget','Stage','Assigned To','Priority','Last Contact']);
            foreach ($leads as $l) {
                fputcsv($f, [
                    $l->id, $l->name, $l->company, $l->phone, $l->email,
                    $l->source, $l->service, $l->budget, $l->stage,
                    $l->employee->name ?? '--', $l->priority,
                    optional($l->last_contact)->format('d M Y'),
                ]);
            }
            fclose($f);
        };
        return response()->stream($cb, 200, $headers);
    }
}