<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreCustomerNoteRequest;
use App\Models\Customer;
use App\Services\Tenancy\CurrentBusiness;
use Illuminate\Http\RedirectResponse;

class CustomerNoteController extends Controller
{
    public function store(StoreCustomerNoteRequest $request, Customer $customer, CurrentBusiness $currentBusiness): RedirectResponse
    {
        $business = $currentBusiness->get() ?? abort(403);

        abort_unless((int) $customer->business_id === (int) $business->id, 404);

        $meta = $customer->meta ?? [];
        $history = $meta['notes_history'] ?? [];
        array_unshift($history, [
            'author' => $request->user()?->name ?? 'Team member',
            'date' => now()->toDateString(),
            'text' => $request->validated('note'),
        ]);

        $meta['notes_history'] = $history;
        $customer->update([
            'notes' => $request->validated('note'),
            'meta' => $meta,
        ]);

        return redirect()
            ->route('admin.customers.show', $customer)
            ->with('status', 'Customer note added successfully.');
    }
}
