<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Offer;
use App\Models\Operator;
use Illuminate\Http\Request;

class OfferController extends Controller
{
    public function index(Request $request)
    {
        $q = $request->string('q')->toString();

        $offers = Offer::with('operator')
            ->when($q, fn($query) =>
                $query->where('title', 'like', "%{$q}%")
                      ->orWhereHas('operator', fn($op) => $op->where('name', 'like', "%{$q}%"))
            )
            ->orderBy('sort_order')
            ->orderByDesc('created_at')
            ->paginate(12)
            ->withQueryString();

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

    public function create()
    {
        $operators = Operator::orderBy('name')->pluck('name', 'id');
        return view('admin.offers.create', compact('operators'));
    }

    public function store(Request $request)
    {
        $data = $this->validated($request);
        Offer::create($data);

        return redirect()
            ->route('admin.offers.index')
            ->with('success', 'Offer created successfully.');
    }

    public function edit(Offer $offer)
    {
        $operators = Operator::orderBy('name')->pluck('name', 'id');
        return view('admin.offers.edit', compact('offer', 'operators'));
    }

    public function update(Request $request, Offer $offer)
    {
        $data = $this->validated($request);
        $offer->update($data);

        return redirect()
            ->route('admin.offers.index')
            ->with('success', 'Offer updated successfully.');
    }

    public function destroy(Offer $offer)
    {
        $offer->delete();

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

    public function show(Offer $offer)
    {
        $offer->load('operator');
        return view('admin.offers.show', compact('offer'));
    }

    private function validated(Request $request): array
    {
        return $request->validate([
            'operator_id'   => ['required', 'exists:operators,id'],
            'title'         => ['required', 'string', 'max:255'],
            'regular_price' => ['required', 'numeric', 'min:0'],
            'sale_price'    => ['nullable', 'numeric', 'min:0'],
            'data_gb'       => ['nullable', 'integer', 'min:0'],
            'minutes'       => ['nullable', 'integer', 'min:0'],
            'validity_days' => ['nullable', 'integer', 'min:0'],
            'status'        => ['required', 'in:active,inactive'],
            'sort_order'    => ['nullable', 'integer', 'min:0'],
        ]);
    }
}
