<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Services\AuditService;
use App\Services\SecureFileService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

class GuarantorController extends Controller
{
    public function store(Request $request, Customer $customer, SecureFileService $files): RedirectResponse|JsonResponse
    {
        Gate::authorize('manageGuarantors', $customer);
        $data = $request->validate([
            'full_name' => ['required','string','max:255'], 'nin' => ['nullable','string','max:100'],
            'phone' => ['required','string','max:50'], 'address' => ['nullable','string','max:255'],
            'occupation' => ['nullable','string','max:150'], 'relationship' => ['nullable','string','max:100'],
            'signed_guarantee' => ['nullable','file','mimes:pdf,jpg,jpeg,png,webp','max:10240'],
        ]);
        $file = $data['signed_guarantee'] ?? null; unset($data['signed_guarantee']);
        if ($file) { $data['signed_guarantee_path'] = $files->store($file, "customers/{$customer->id}/guarantors"); }
        $data['created_by'] = $request->user()->id;
        $guarantor = $customer->guarantors()->create($data);
        AuditService::record('customer.guarantor.created', $customer, [], ['guarantor_id' => $guarantor->id, 'name' => $guarantor->full_name], $customer->branch_id);

        if ($request->expectsJson()) {
            return response()->json([
                'message' => 'Guarantor added.',
                'guarantor' => [
                    'id' => $guarantor->id,
                    'customer_id' => $guarantor->customer_id,
                    'full_name' => $guarantor->full_name,
                    'phone' => $guarantor->phone,
                    'nin' => $guarantor->nin,
                    'relationship' => $guarantor->relationship,
                    'occupation' => $guarantor->occupation,
                    'address' => $guarantor->address,
                    'status' => $guarantor->status,
                ],
            ], 201);
        }

        return redirect()->route('customers.show', [$customer, 'tab' => 'guarantors'])->with('success', 'Guarantor added.');
    }
}
