<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PaymentMethod;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

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

        if ($s = $request->get('s')) {
            $q->where(function($qq) use ($s){
                $qq->where('label', 'like', "%$s%")
                   ->orWhere('key', 'like', "%$s%")
                   ->orWhere('agent_number', 'like', "%$s%");
            });
        }

        $methods = $q->orderBy('sort')->orderBy('label')->paginate(12)->withQueryString();

        return view('admin.payment_methods.index', compact('methods'));
    }

    public function create()
    {
        $method = new PaymentMethod(['is_active'=>true, 'sort'=>0]);
        return view('admin.payment_methods.create', compact('method'));
    }

    public function store(Request $request)
    {
        $data = $this->validateData($request);

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

        PaymentMethod::create($data);

        return redirect()->route('admin.payment_methods.index')->with('success', 'Payment method created.');
    }

    public function edit(PaymentMethod $payment_method)
    {
        return view('admin.payment_methods.edit', ['method' => $payment_method]);
    }

    public function update(Request $request, PaymentMethod $payment_method)
    {
        $data = $this->validateData($request, $payment_method->id);

        if ($request->hasFile('logo_file')) {
            // delete old
            if ($payment_method->logo_path && str_starts_with($payment_method->logo_path, 'methods/')) {
                Storage::disk('public')->delete($payment_method->logo_path);
            }
            $data['logo_path'] = $request->file('logo_file')->store('methods', 'public');
        }

        if ($request->hasFile('instruction_file')) {
            if ($payment_method->instruction_img && str_starts_with($payment_method->instruction_img, 'methods/')) {
                Storage::disk('public')->delete($payment_method->instruction_img);
            }
            $data['instruction_img'] = $request->file('instruction_file')->store('methods', 'public');
        }

        $payment_method->update($data);

        return redirect()->route('admin.payment_methods.index')->with('success', 'Payment method updated.');
    }

    public function destroy(PaymentMethod $payment_method)
    {
        if ($payment_method->logo_path && str_starts_with($payment_method->logo_path, 'methods/')) {
            Storage::disk('public')->delete($payment_method->logo_path);
        }
        if ($payment_method->instruction_img && str_starts_with($payment_method->instruction_img, 'methods/')) {
            Storage::disk('public')->delete($payment_method->instruction_img);
        }

        $payment_method->delete();

        return back()->with('success', 'Payment method removed.');
    }

    // quick active toggle
    public function toggle(PaymentMethod $payment_method)
    {
        $payment_method->update(['is_active' => !$payment_method->is_active]);
        return back()->with('success', 'Status updated.');
    }

    // -----
    protected function validateData(Request $request, $id = null): array
    {
        return $request->validate([
            'key'            => ['required', 'alpha_dash', 'max:50', 'unique:payment_methods,key,'.($id??'NULL').',id'],
            'label'          => ['required', 'string', 'max:100'],
            'agent_number'   => ['nullable', 'string', 'max:30'],
            'logo_path'      => ['nullable', 'string', 'max:255'],            // optional if using url/text
            'instruction_img'=> ['nullable', 'string', 'max:255'],            // optional if using url/text
            'is_active'      => ['boolean'],
            'sort'           => ['nullable', 'integer', 'min:0'],
            // file inputs are optional
            'logo_file'        => ['nullable', 'image', 'max:2048'],
            'instruction_file' => ['nullable', 'image', 'max:4096'],
        ], [
            'key.unique' => 'This key already exists.',
        ]);
    }
}
