<?php

namespace App\Http\Controllers\Admin;

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

class PaymentMethodController extends Controller
{
    /**
     * Payment method list
     */
    public function index()
    {
        $methods = PaymentMethod::latest()->paginate(10);

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

    /**
     * Create page
     */
    public function create()
    {
        return view('admin.payment_methods.create');
    }

    /**
     * Store new payment method
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'   => ['required', 'string', 'max:255'],
            'number' => ['required', 'string', 'max:255'],
            'status' => ['required', 'in:active,inactive'],
            'photo'  => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
        ]);

        $photoPath = null;
        $uploadDir = public_path('uploads/payment_methods');

        if (!File::exists($uploadDir)) {
            File::makeDirectory($uploadDir, 0755, true, true);
        }

        if ($request->hasFile('photo')) {
            $file = $request->file('photo');
            $extension = strtolower($file->getClientOriginalExtension());

            if (!in_array($extension, ['jpg', 'jpeg', 'png', 'webp'])) {
                return back()->withErrors([
                    'photo' => 'Only jpg, jpeg, png, and webp are allowed.'
                ])->withInput();
            }

            $fileName = Str::uuid() . '.' . $extension;
            $file->move($uploadDir, $fileName);

            $photoPath = 'uploads/payment_methods/' . $fileName;
        }

        PaymentMethod::create([
            'name'   => $validated['name'],
            'number' => $validated['number'],
            'status' => $validated['status'],
            'photo'  => $photoPath,
        ]);

        return redirect()
            ->route('payment-methods.index')
            ->with('success', 'Payment method added successfully!');
    }

    /**
     * Edit page
     */
    public function edit(PaymentMethod $payment_method)
    {
        return view('admin.payment_methods.edit', compact('payment_method'));
    }

    /**
     * Update payment method
     */
    public function update(Request $request, PaymentMethod $payment_method)
    {
        $validated = $request->validate([
            'name'   => ['required', 'string', 'max:255'],
            'number' => ['required', 'string', 'max:255'],
            'status' => ['required', 'in:active,inactive'],
            'photo'  => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
        ]);

        $photoPath = $payment_method->photo;
        $uploadDir = public_path('uploads/payment_methods');

        if (!File::exists($uploadDir)) {
            File::makeDirectory($uploadDir, 0755, true, true);
        }

        if ($request->hasFile('photo')) {
            $this->deleteOldPhoto($payment_method->photo);

            $file = $request->file('photo');
            $extension = strtolower($file->getClientOriginalExtension());

            if (!in_array($extension, ['jpg', 'jpeg', 'png', 'webp'])) {
                return back()->withErrors([
                    'photo' => 'Only jpg, jpeg, png, and webp are allowed.'
                ])->withInput();
            }

            $fileName = Str::uuid() . '.' . $extension;
            $file->move($uploadDir, $fileName);

            $photoPath = 'uploads/payment_methods/' . $fileName;
        }

        $payment_method->update([
            'name'   => $validated['name'],
            'number' => $validated['number'],
            'status' => $validated['status'],
            'photo'  => $photoPath,
        ]);

        return redirect()
            ->route('payment-methods.index')
            ->with('success', 'Payment method updated successfully!');
    }

    /**
     * Delete payment method
     */
    public function destroy(PaymentMethod $payment_method)
    {
        $methodName = $payment_method->name;

        $this->deleteOldPhoto($payment_method->photo);

        $payment_method->delete();

        return redirect()
            ->route('payment-methods.index')
            ->with('success', "Payment method '{$methodName}' deleted successfully!");
    }

    /**
     * Toggle status (Activate / Deactivate)
     */
    public function toggleStatus(Request $request, PaymentMethod $payment_method)
    {
        $newStatus = $payment_method->status === 'active' ? 'inactive' : 'active';

        $payment_method->update([
            'status' => $newStatus,
        ]);

        $message = $newStatus === 'active'
            ? 'Payment method activated successfully!'
            : 'Payment method deactivated successfully!';

        if ($request->ajax() || $request->input('ajax') == '1') {
            return response()->json([
                'success'     => true,
                'status'      => $newStatus === 'active',
                'status_text' => $newStatus === 'active' ? 'Active' : 'Inactive',
                'message'     => $message,
            ]);
        }

        return redirect()
            ->route('payment-methods.index')
            ->with('success', $message);
    }

    /**
     * Delete old photo from public path
     */
    private function deleteOldPhoto(?string $photoPath): void
    {
        if (!$photoPath) {
            return;
        }

        $fullPath = public_path($photoPath);

        if (File::exists($fullPath) && File::isFile($fullPath)) {
            File::delete($fullPath);
        }
    }
}