<?php

namespace App\Http\Controllers;

use App\Models\Lead;
use App\Models\MasterData;
use Illuminate\Http\Request;

class LeadPipelineController extends Controller
{
    public function index()
    {
        $statuses = MasterData::where('type', 'lead_status')
            ->where('is_active', true)
            ->orderBy('sort_order')
            ->get();
            
        // Get leads grouped by status
        $leadsByStatus = [];
        foreach ($statuses as $status) {
            $leadsByStatus[$status->name] = Lead::where('status', $status->name)
                ->orderBy('updated_at', 'desc')
                ->get();
        }
        
        return view('leads.pipeline', compact('statuses', 'leadsByStatus'));
    }

    public function updateStatus(Request $request, Lead $lead)
    {
        $request->validate([
            'status' => 'required|string|exists:master_data,name'
        ]);

        $lead->update([
            'status' => $request->status
        ]);

        return response()->json(['success' => true]);
    }
}
