<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\CustomerRequest;
use App\Models\Company;
use App\Models\Customer;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class CustomerController extends Controller
{
    public function index(Request $request): View
    {
        $customers = Customer::when($request->user()->company_id, fn ($q, $companyId) => $q->where('company_id', $companyId))
            ->latest()
            ->get();

        return view('admin.customers.index', compact('customers'));
    }

    public function create(Request $request): View
    {
        return view('admin.customers.create', [
            'customer' => new Customer(['status' => 'active']),
            'companies' => $request->user()->company_id ? collect() : Company::orderBy('name')->get(),
        ]);
    }

    public function store(CustomerRequest $request): RedirectResponse
    {
        $data = $request->validated();
        $data['company_id'] = $request->user()->company_id ?: $data['company_id'];

        Customer::create($data);

        return redirect()->route('admin.customers.index')->with('success', 'Customer added.');
    }

    public function edit(Request $request, Customer $customer): View
    {
        $this->authorizeCompanyOwnership($customer);

        return view('admin.customers.edit', [
            'customer' => $customer,
            'companies' => $request->user()->company_id ? collect() : Company::orderBy('name')->get(),
        ]);
    }

    public function update(CustomerRequest $request, Customer $customer): RedirectResponse
    {
        $this->authorizeCompanyOwnership($customer);

        $data = $request->validated();
        $data['company_id'] = $request->user()->company_id ?: ($data['company_id'] ?? $customer->company_id);

        $customer->update($data);

        return redirect()->route('admin.customers.index')->with('success', 'Customer updated.');
    }

    public function destroy(Customer $customer): RedirectResponse
    {
        $this->authorizeCompanyOwnership($customer);

        $customer->delete();

        return redirect()->route('admin.customers.index')->with('success', 'Customer deleted.');
    }
}
