<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
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
    {
        $search = trim((string) $request->query('search', ''));

        $customers = Customer::query()
            ->when($search !== '', function ($query) use ($search) {
                $query->where(function ($inner) use ($search) {
                    $inner->where('name', 'like', "%{$search}%")
                        ->orWhere('code', 'like', "%{$search}%")
                        ->orWhere('whatsapp', 'like', "%{$search}%")
                        ->orWhere('email', 'like', "%{$search}%");
                });
            })
            ->latest()
            ->paginate(20)
            ->withQueryString();

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

    public function create(): View
    {
        return view('admin.customers.form', [
            'customer' => new Customer(),
            'isEdit' => false,
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $this->validated($request);
        $userId = auth()->id();

        $customer = Customer::create([
            ...$data,
            'code' => $this->nextCustomerCode(),
            'created_by' => $userId,
            'updated_by' => $userId,
            'is_active' => true,
        ]);

        return redirect()->route('admin.customers.index')
            ->with('success', "Pelanggan {$customer->name} berhasil ditambahkan.");
    }

    public function edit(Customer $customer): View
    {
        abort_unless(auth()->user()?->isAdmin(), 403);

        return view('admin.customers.form', [
            'customer' => $customer,
            'isEdit' => true,
        ]);
    }

    public function update(Request $request, Customer $customer): RedirectResponse
    {
        abort_unless(auth()->user()?->isAdmin(), 403);

        $data = $this->validated($request, $customer->id);

        $customer->update([
            ...$data,
            'updated_by' => auth()->id(),
            'is_active' => $request->boolean('is_active', true),
        ]);

        return redirect()->route('admin.customers.index')
            ->with('success', "Data pelanggan {$customer->name} berhasil diperbarui.");
    }

    private function validated(Request $request, ?int $customerId = null): array
    {
        return $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'whatsapp' => ['nullable', 'string', 'max:20'],
            'email' => ['nullable', 'email', 'max:255', 'unique:customers,email' . ($customerId ? ',' . $customerId : '')],
            'address' => ['nullable', 'string', 'max:1000'],
            'tax_number' => ['nullable', 'string', 'max:50'],
        ]);
    }

    private function nextCustomerCode(): string
    {
        $prefix = 'CUST-' . now()->format('Ym') . '-';
        $last = Customer::whereNotNull('code')
            ->where('code', 'like', $prefix . '%')
            ->orderByDesc('code')
            ->value('code');

        $sequence = $last ? ((int) substr($last, -5)) + 1 : 1;

        return $prefix . str_pad((string) $sequence, 5, '0', STR_PAD_LEFT);
    }
}