<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Models\Lead;
use App\Models\Territory;
use App\Models\User;
use App\Services\AssignmentService;

final class AssignmentController extends BaseController
{
    public function index(Request $request): void
    {
        $this->requireModule('assignment');
        view('assignment/index', [
            'title' => 'Lead assignment',
            'leads' => Lead::unassigned(),
            'owners' => User::salespeople(Auth::instance()->tenantId()),
            'territories' => Territory::allForTenant(),
            'notifications' => $this->notifications(),
        ]);
    }

    public function store(Request $request): void
    {
        $this->requireModule('assignment');
        $this->verifyCsrf($request);
        $ids = $request->input('lead_ids');
        if (!is_array($ids)) {
            $ids = array_filter(explode(',', (string) $ids));
        }
        if ($ids === []) {
            json_out(['ok' => false, 'error' => 'Pick at least one lead.'], 422);
        }
        $method = (string) $request->input('method', 'manual');
        $ok = 0;
        $error = null;
        foreach ($ids as $id) {
            $result = AssignmentService::assign(
                (int) $id,
                $method,
                $request->int('user_id') ?: null,
                $request->int('territory_id') ?: null
            );
            if (!empty($result['ok'])) {
                $ok++;
            } else {
                $error = $result['error'] ?? 'Could not assign.';
            }
        }
        if ($ok === 0) {
            json_out(['ok' => false, 'error' => $error ?: 'Could not assign.'], 422);
        }
        json_out(['ok' => true, 'assigned' => $ok, 'message' => $ok === 1 ? '1 lead assigned.' : $ok . ' leads assigned.']);
    }
}
