<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\CorporateCompany;
use App\Models\Customer;
use App\Models\Service;
use App\Services\ApplicationService;
use App\Services\CustomerSearchService;
use App\Services\FeeEngineService;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class ApplicationWorkspaceController extends Controller
{
    public function __construct(
        protected CustomerSearchService $searchService,
        protected ApplicationService $appService,
        protected FeeEngineService $feeEngine,
    ) {}

    public function create(Request $request)
    {
        $tenant = $request->user()->tenant;
        $services = Service::where('tenant_id', $tenant->id)
            ->where('status', 'active')
            ->with('authority')
            ->orderBy('name_en')
            ->get();
        $companies = CorporateCompany::where('tenant_id', $tenant->id)
            ->where('status', 'active')
            ->orderBy('name_en')
            ->get();

        $selectedCustomer = null;
        if ($request->filled('customer_id')) {
            $customer = Customer::where('tenant_id', $tenant->id)
                ->with('contact')
                ->find($request->integer('customer_id'));

            if ($customer) {
                $selectedCustomer = [
                    'id' => $customer->id,
                    'customer_code' => $customer->customer_code,
                    'full_name_en' => $customer->full_name_en,
                    'primary_mobile' => $customer->contact?->primary_mobile,
                    'is_vip' => $customer->is_vip,
                ];
            }
        }

        return view('tenant.applications.workspace', compact('services', 'companies', 'selectedCustomer'));
    }

    public function searchCustomer(Request $request)
    {
        return response()->json(
            $this->searchService->search($request->user()->tenant, $request->query('query', ''))
        );
    }

    public function calculateFees(Request $request)
    {
        $tenant = $request->user()->tenant;
        $validated = $request->validate([
            'service_id' => ['required', Rule::exists('services', 'id')->where('tenant_id', $tenant->id)],
            'priority' => ['nullable', Rule::in(['normal', 'high', 'urgent', 'vip'])],
            'company_id' => ['nullable', Rule::exists('corporate_companies', 'id')->where('tenant_id', $tenant->id)],
        ]);
        $service = Service::where('tenant_id', $tenant->id)->findOrFail($validated['service_id']);

        return response()->json($this->feeEngine->calculateServiceFees($service, [
            'priority' => $validated['priority'] ?? 'normal',
            'company_id' => $validated['company_id'] ?? null,
        ]));
    }

    public function store(Request $request)
    {
        $tenant = $request->user()->tenant;
        $validated = $request->validate([
            'customer_id' => ['required', Rule::exists('customers', 'id')->where('tenant_id', $tenant->id)],
            'service_id' => ['required', Rule::exists('services', 'id')->where('tenant_id', $tenant->id)],
            'company_id' => ['nullable', Rule::exists('corporate_companies', 'id')->where('tenant_id', $tenant->id)],
            'priority' => ['nullable', Rule::in(['normal', 'high', 'urgent', 'vip'])],
            'applicant_type' => ['nullable', Rule::in(['individual', 'corporate_employee', 'family_member'])],
            'notes' => ['nullable', 'string', 'max:2000'],
        ]);
        $customer = Customer::where('tenant_id', $tenant->id)->findOrFail($validated['customer_id']);
        $service = Service::where('tenant_id', $tenant->id)->findOrFail($validated['service_id']);
        $application = $this->appService->createApplication(
            $tenant,
            $customer,
            $service,
            $validated,
            $request->user(),
        );

        return redirect()->route('app.applications.show', $application->id)
            ->with('status', "Application {$application->application_number} created successfully.");
    }
}
