<?php

namespace App\Http\Controllers\Admin\Customers;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\Blacklist;
use App\Services\CustomerRiskService;
use Illuminate\Http\Request;

class BlacklistController extends Controller
{
    protected $riskService;

    public function __construct(CustomerRiskService $riskService)
    {
        $this->riskService = $riskService;
    }

    public function index()
    {
        $blacklist = Blacklist::with('customer', 'blacklistedBy', 'liftedBy')
            ->orderBy('blacklisted_from', 'desc')
            ->paginate(20);

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

    public function create(Customer $customer)
    {
        return view('admin.customers.blacklist.create', compact('customer'));
    }

    public function store(Request $request, Customer $customer)
    {
        $validated = $request->validate([
            'reason' => 'required|in:financial,violations,fraud,dangerous_driving,non_payment,administrative',
            'description' => 'required|string|max:1000',
            'evidence' => 'nullable|string|max:500',
            'notes' => 'nullable|string|max:500',
            'duration_days' => 'nullable|integer|min:1',
        ]);

        $blacklist = $this->riskService->addToBlacklist(
            $customer,
            $validated['reason'],
            $validated['description'],
            auth()->id(),
            $validated['duration_days'] ?? null
        );

        if (isset($validated['evidence'])) {
            $blacklist->update(['evidence' => $validated['evidence']]);
        }
        if (isset($validated['notes'])) {
            $blacklist->update(['notes' => $validated['notes']]);
        }

        return redirect()->route('admin.customers.ratings.show', $customer)
            ->with('success', app()->getLocale() == 'ar' ? 'تم إضافة العميل إلى قائمة الحظر' : 'Customer added to blacklist');
    }

    public function lift(Request $request, Blacklist $blacklist)
    {
        $validated = $request->validate([
            'lift_reason' => 'required|string|max:500',
        ]);

        $blacklist->lift(auth()->id(), $validated['lift_reason']);

        return back()->with('success', app()->getLocale() == 'ar' ? 'تم رفع الحظر عن العميل' : 'Customer removed from blacklist');
    }

    public function destroy(Blacklist $blacklist)
    {
        $customer = $blacklist->customer;
        $blacklist->delete();

        return redirect()->route('admin.customers.ratings.show', $customer)
            ->with('success', app()->getLocale() == 'ar' ? 'تم حذف سجل الحظر' : 'Blacklist record deleted');
    }
}
