<?php

namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;

use App\Models\MobileGateway;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;

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

        if ($s = $request->get('q')) {
            $q->where(function($w) use ($s){
                $w->where('name','like',"%{$s}%")
                  ->orWhere('code','like',"%{$s}%");
            });
        }
        if (!is_null($request->get('active'))) {
            $q->where('is_active', (bool)$request->get('active'));
        }

        $gateways = $q->orderBy('name')->paginate(12)->withQueryString();
        return view('backend.mobile_gateways.index', compact('gateways'));
    }

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'            => ['required','string','max:255'],
            'code'            => ['required','string','max:50','unique:mobile_gateways,code'],
            'min_limit'       => ['required','numeric','min:0'],
            'max_limit'       => ['required','numeric','gte:min_limit'],
            'is_active'       => ['required','in:0,1'],
            'logo_path'       => ['nullable','string','max:600'],        // external URL / emoji / text
            'logo_file'       => ['nullable','image','mimes:jpg,jpeg,png,webp,svg','max:2048'],

            'flat_fee'        => ['required','numeric','min:0'],
            'percent_fee'     => ['required','numeric','min:0'],
            'min_commission'  => ['required','numeric','min:0'],
            'max_commission'  => ['required','numeric','gte:min_commission'],
        ]);

        if ($request->hasFile('logo_file')) {
            $data['logo_path'] = $request->file('logo_file')->store('uploads/mobile-gateways','public');
        }

        MobileGateway::create($data);
        return redirect(url('/admin/mobile-gateways'))->with('success','Gateway created.');
    }

    public function show($id)
    {
        $gw = MobileGateway::findOrFail($id);
        return view('backend.mobile_gateways.show', compact('gw'));
    }

    public function edit($id)
    {
        $gw = MobileGateway::findOrFail($id);
        return view('backend.mobile_gateways.edit', compact('gw'));
    }

    public function update(Request $request, $id)
    {
        $gw = MobileGateway::findOrFail($id);

        $data = $request->validate([
            'name'            => ['required','string','max:255'],
            'code'            => ['required','string','max:50', Rule::unique('mobile_gateways','code')->ignore($gw->id)],
            'min_limit'       => ['required','numeric','min:0'],
            'max_limit'       => ['required','numeric','gte:min_limit'],
            'is_active'       => ['required','in:0,1'],
            'logo_path'       => ['nullable','string','max:600'],
            'logo_file'       => ['nullable','image','mimes:jpg,jpeg,png,webp,svg','max:2048'],
            'remove_logo'     => ['nullable','boolean'],

            'flat_fee'        => ['required','numeric','min:0'],
            'percent_fee'     => ['required','numeric','min:0'],
            'min_commission'  => ['required','numeric','min:0'],
            'max_commission'  => ['required','numeric','gte:min_commission'],
        ]);

        if ($request->boolean('remove_logo') && $gw->logo_path && Storage::disk('public')->exists($gw->logo_path)) {
            Storage::disk('public')->delete($gw->logo_path);
            $data['logo_path'] = null;
        }

        if ($request->hasFile('logo_file')) {
            $path = $request->file('logo_file')->store('uploads/mobile-gateways','public');
            if ($gw->logo_path && Storage::disk('public')->exists($gw->logo_path)) {
                Storage::disk('public')->delete($gw->logo_path);
            }
            $data['logo_path'] = $path;
        }

        $gw->update($data);
        return redirect(url('/admin/mobile-gateways'))->with('success','Gateway updated.');
    }

    public function destroy($id)
    {
        $gw = MobileGateway::findOrFail($id);
        if ($gw->logo_path && Storage::disk('public')->exists($gw->logo_path)) {
            Storage::disk('public')->delete($gw->logo_path);
        }
        $gw->delete();
        return redirect(url('/admin/mobile-gateways'))->with('success','Gateway deleted.');
    }

    public function toggle($id)
    {
        $gw = MobileGateway::findOrFail($id);
        $gw->update(['is_active' => !$gw->is_active]);
        return back()->with('success','Status toggled.');
    }
}
