<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Operator;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests\StoreOperatorRequest;
use App\Http\Requests\UpdateOperatorRequest;

class OperatorController extends Controller
{
    public function index()
    {
        $operators = Operator::orderBy('sort_order')->orderByDesc('id')->paginate(10);
        return view('admin.operators.index', compact('operators'));
    }

    public function create()
    {
        return view('admin.operators.create');
    }

    public function store(StoreOperatorRequest $request)
    {
        $data = $request->validated();

        if ($request->hasFile('logo')) {
            $data['logo'] = $request->file('logo')->store('logos', 'public');
        }

        Operator::create($data);

        return redirect()->route('operators.index')->with('success', 'Operator created.');
    }

    public function show(Operator $operator)
    {
        return view('admin.operators.show', compact('operator'));
    }

    public function edit(Operator $operator)
    {
        return view('admin.operators.edit', compact('operator'));
    }

    public function update(UpdateOperatorRequest $request, Operator $operator)
    {
        $data = $request->validated();

        if ($request->hasFile('logo')) {
            // পুরনো ফাইল মুছে দাও
            if ($operator->logo && Storage::disk('public')->exists($operator->logo)) {
                Storage::disk('public')->delete($operator->logo);
            }
            $data['logo'] = $request->file('logo')->store('logos', 'public');
        }

        $operator->update($data);

        return redirect()->route('operators.index')->with('success', 'Operator updated.');
    }

    public function destroy(Operator $operator)
    {
        if ($operator->logo && Storage::disk('public')->exists($operator->logo)) {
            Storage::disk('public')->delete($operator->logo);
        }

        $operator->delete();

        return redirect()->route('operators.index')->with('success', 'Operator deleted.');
    }
}
