<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Lead;
use Illuminate\Support\Facades\Response;

class LeadController extends Controller
{
    /** GET /api/get-leads */
    public function index(Request $request)
    {
        $role     = $request->header('X-User-Role');
        $username = $request->header('X-User-Username');

        $query = Lead::orderBy('id', 'desc');

        // Brokers only see leads assigned to them
        if ($role === 'broker' && $username) {
            $query->where('assign_to', $username);
        }

        $leads = $query->get([
            'id',
            'customer_name',
            'whatsapp_number',
            'preferred_location',
            'requirement',
            'budget_range',
            'status',
            'notes',
            'assign_to',
            'created_at',
        ]);

        return response()->json([
            'success' => true,
            'data' => $leads
        ]);
    }

    /** POST /api/add-lead */
    public function store(Request $request)
    {
        $name   = trim($request->input('customer_name', ''));
        $phone  = trim($request->input('whatsapp_number', ''));
        $loc    = trim($request->input('preferred_location', ''));
        $req    = trim($request->input('requirement', ''));
        $budget = trim($request->input('budget_range', ''));

        if ($name === '' || $phone === '' || $loc === '' || $req === '' || $budget === '') {
            return response()->json([
                'success' => false,
                'error' => 'All fields are required'
            ], 422);
        }

        $lead = Lead::create([
            'customer_name'      => $name,
            'whatsapp_number'    => $phone,
            'preferred_location' => $loc,
            'requirement'        => $req,
            'budget_range'       => $budget,
            'status'             => 'New',
            'notes'              => null,
        ]);

        return response()->json([
            'success' => true,
            'id' => $lead->id
        ]);
    }

    /** POST /api/update-lead-status */
    public function updateStatus(Request $request)
    {
        $id     = $request->input('id', '');
        $status = $request->input('status', '');

        if ($id === '' || $status === '') {
            return response()->json([
                'success' => false,
                'message' => 'Missing data'
            ], 422);
        }

        $lead = Lead::find($id);

        if (!$lead) {
            return response()->json([
                'success' => false,
                'message' => 'Lead not found'
            ], 404);
        }

        $lead->status = $status;

        if ($status === 'New') {
            $lead->notes = null;
        }

        $lead->save();

        return response()->json([
            'success' => true,
            'message' => 'Lead status updated'
        ]);
    }

    /** POST /api/update-lead */
    public function update(Request $request)
    {
        $id = $request->input('id');

        if (!$id) {
            return response()->json([
                'success' => false,
                'message' => 'Lead ID missing'
            ], 422);
        }

        $lead = Lead::find($id);

        if (!$lead) {
            return response()->json([
                'success' => false,
                'message' => 'Lead not found'
            ], 404);
        }

        $status    = $request->input('status', $lead->status);
        $notes     = $request->input('notes', $lead->notes);
        $assign_to = $request->input('assign_to', $lead->assign_to);

        $lead->status    = $status;
        $lead->notes     = ($status === 'New') ? null : $notes;
        $lead->assign_to = $assign_to;
        $lead->save();

        return response()->json([
            'success' => true,
            'message' => 'Lead updated successfully',
            'data' => $lead
        ]);
    }

    /** GET /api/export-leads */
    public function export()
    {
        $leads = Lead::orderBy('id', 'desc')->get();

        $headers = [
            'Content-Type'        => 'text/csv; charset=UTF-8',
            'Content-Disposition' => 'attachment; filename="skystone_properties_leads.csv"',
        ];

        $callback = function () use ($leads) {
            $handle = fopen('php://output', 'w');

            fputs($handle, "\xEF\xBB\xBF");

            fputcsv($handle, [
                'ID',
                'Customer Name',
                'WhatsApp Number',
                'Preferred Location',
                'Requirement',
                'Budget Range',
                'Status',
                'Notes',
                'Assign To',
                'Created At',
            ]);

            foreach ($leads as $l) {
                fputcsv($handle, [
                    $l->id,
                    $l->customer_name,
                    $l->whatsapp_number,
                    $l->preferred_location,
                    $l->requirement,
                    $l->budget_range,
                    $l->status,
                    $l->notes,
                    $l->assign_to,
                    $l->created_at,
                ]);
            }

            fclose($handle);
        };

        return Response::stream($callback, 200, $headers);
    }

    public function bulkStore(Request $request)
{
    $leads = $request->input('leads', []);

    if (!is_array($leads) || count($leads) === 0) {
        return response()->json([
            'success' => false,
            'message' => 'No leads received',
            'received' => $request->all()
        ], 422);
    }

    $inserted = 0;
    $failed = [];

    foreach ($leads as $index => $lead) {
        $name = trim($lead['customer_name'] ?? '');
        $phone = trim($lead['whatsapp_number'] ?? '');

        if ($name === '' || $phone === '') {
            $failed[] = [
                'row' => $index + 1,
                'reason' => 'Missing customer_name or whatsapp_number'
            ];
            continue;
        }

        Lead::create([
            'customer_name'      => $name,
            'whatsapp_number'    => $phone,
            'preferred_location' => $lead['preferred_location'] ?? '',
            'requirement'        => $lead['requirement'] ?? '',
            'budget_range'       => $lead['budget_range'] ?? '',
            'status'             => $lead['status'] ?? 'New',
            'notes'              => $lead['notes'] ?? null,
            'assign_to'          => $lead['assign_to'] ?? null,
        ]);

        $inserted++;
    }

    return response()->json([
        'success' => true,
        'message' => "$inserted leads imported successfully",
        'inserted' => $inserted,
        'failed_count' => count($failed),
        'failed' => $failed
    ]);
}
}