<?php

namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;

use App\Models\Operator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class OperatorController extends Controller
{
    public function index(Request $request)
    {
        $q = Operator::query();

        if ($s = $request->get('q')) {
            $q->where(function ($w) use ($s) {
                $w->where('name', 'like', "%{$s}%")
                  ->orWhere('code', 'like', "%{$s}%");
            });
        }
        if ($st = $request->get('status')) {
            $q->where('status', $st);
        }

        $operators = $q->orderBy('sort_order')
                       ->orderBy('name')
                       ->paginate(12)
                       ->withQueryString();

        return view('backend.operators.index', compact('operators'));
    }

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'       => 'required|string|max:255',
            'code'       => 'required|string|max:100|unique:operators,code',
            'status'     => 'required|in:active,inactive',
            'sort_order' => 'nullable|integer|min:0',
            'logo'       => 'nullable|image|mimes:jpg,jpeg,png,webp,svg|max:2048',
        ]);

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

        $data['sort_order'] = $data['sort_order'] ?? 0;

        Operator::create($data);
        return redirect(url('/admin/operators'))->with('success', 'Operator created.');
    }

    public function show($id)
    {
        $operator = Operator::findOrFail($id);
        return view('backend.operators.show', compact('operator'));
    }

    public function edit($id)
    {
        $operator = Operator::findOrFail($id);
        return view('backend.operators.edit', compact('operator'));
    }

    public function update(Request $request, $id)
    {
        $operator = Operator::findOrFail($id);

        $data = $request->validate([
            'name'       => 'required|string|max:255',
            'code'       => 'required|string|max:100|unique:operators,code,'.$operator->id,
            'status'     => 'required|in:active,inactive',
            'sort_order' => 'nullable|integer|min:0',
            'logo'       => 'nullable|image|mimes:jpg,jpeg,png,webp,svg|max:2048',
            'remove_logo'=> 'nullable|boolean',
        ]);

        // remove logo
        if ($request->boolean('remove_logo') && $operator->logo) {
            Storage::disk('public')->delete($operator->logo);
            $data['logo'] = null;
        }

        // new upload
        if ($request->hasFile('logo')) {
            $path = $request->file('logo')->store('uploads/operators', 'public');
            if ($operator->logo) {
                Storage::disk('public')->delete($operator->logo);
            }
            $data['logo'] = $path;
        }

        $data['sort_order'] = $data['sort_order'] ?? 0;

        $operator->update($data);
        return redirect(url('/admin/operators'))->with('success', 'Operator updated.');
    }

    public function destroy($id)
    {
        $operator = Operator::findOrFail($id);
        if ($operator->logo) {
            Storage::disk('public')->delete($operator->logo);
        }
        $operator->delete();
        return redirect(url('/admin/operators'))->with('success', 'Operator deleted.');
    }

    public function toggle($id)
    {
        $operator = Operator::findOrFail($id);
        $operator->update([
            'status' => $operator->status === 'active' ? 'inactive' : 'active'
        ]);
        return back()->with('success', 'Status toggled.');
    }
}
