<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Concerns\ResolvesPlatformAdminContext;
use App\Http\Controllers\Controller;
use App\Models\PlatformLead;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class PlatformLeadController extends Controller
{
    use ResolvesPlatformAdminContext;

    public function index(Request $request): View
    {
        $this->ensurePlatformAdmin($request);

        $filters = [
            'status' => trim((string) $request->query('status', '')),
            'keyword' => trim((string) $request->query('keyword', '')),
            // 精确过滤：线索ID（用于从订单/运营动作回溯到某条线索）
            'lead_id' => trim((string) $request->query('lead_id', '')),
        ];

        $query = PlatformLead::query();

        $query->when($filters['status'] !== '', fn (Builder $b) => $b->where('status', $filters['status']));

        $query->when($filters['lead_id'] !== '' && ctype_digit($filters['lead_id']), function (Builder $b) use ($filters) {
            $b->where('id', (int) $filters['lead_id']);
        });

        $query->when($filters['keyword'] !== '', function (Builder $b) use ($filters) {
            $kw = $filters['keyword'];
            $b->where(function (Builder $q) use ($kw) {
                $q->where('name', 'like', '%' . $kw . '%')
                    ->orWhere('mobile', 'like', '%' . $kw . '%')
                    ->orWhere('email', 'like', '%' . $kw . '%')
                    ->orWhere('company', 'like', '%' . $kw . '%');
            });
        });

        $leads = $query->latest('id')->paginate(15)->withQueryString();

        return view('admin.platform_leads.index', [
            'leads' => $leads,
            'filters' => $filters,
            'statusLabels' => $this->statusLabels(),
        ]);
    }

    public function setStatus(Request $request, PlatformLead $lead): RedirectResponse
    {
        $this->ensurePlatformAdmin($request);

        $data = $request->validate([
            'status' => ['required', Rule::in(array_keys($this->statusLabels()))],
        ]);

        $lead->status = (string) $data['status'];
        $lead->save();

        return redirect()->back()->with('success', '线索状态已更新：#' . $lead->id . ' → ' . ($this->statusLabels()[$lead->status] ?? $lead->status));
    }

    private function statusLabels(): array
    {
        return [
            'new' => '新线索',
            'contacted' => '已联系',
            'qualified' => '已确认需求',
            'converted' => '已转化',
            'closed' => '已关闭',
        ];
    }
}
