<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Pathway;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;

class PathwayController extends Controller
{
    /**
     * Display a listing of the pathways.
     */
    public function index(Request $request)
    {
        $query = Pathway::query();

        // Search functionality
        if ($request->filled('search')) {
            $query->search($request->search);
        }

        // Status filter
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // Sorting
        $sortBy = $request->get('sort_by', 'sorting');
        $sortDirection = $request->get('sort_direction', 'asc');

        if (in_array($sortBy, ['name', 'status', 'sorting', 'created_at'])) {
            $query->orderBy($sortBy, $sortDirection);
        } else {
            $query->ordered();
        }

        $pathways = $query->paginate(10)->appends($request->query());

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

    /**
     * Show the form for creating a new pathway.
     */
    public function create()
    {
        return view('admin.pathways.create');
    }

    /**
     * Store a newly created pathway in storage.
     */
    public function store(Request $request)
    {
        $request->merge(['status' => $request->has('status')]);
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:pathways,name',
            'short_description' => 'nullable|string|max:1000',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'status' => 'boolean',
            'sorting' => 'nullable|integer|min:0'
        ]);
        // Handle logo upload
        if ($request->hasFile('logo')) {
            $logoPath = $request->file('logo')->store('pathways/logos', 'public');
            $validated['logo'] = $logoPath;
        }

        // Set default values
        $validated['sorting'] = $validated['sorting'] ?? 0;
        Pathway::create($validated);

        return redirect()->route('admin.pathways.index')
            ->with('success', 'Pathway created successfully.');
    }

    /**
     * Display the specified pathway.
     */
    public function show(Pathway $pathway)
    {
        return view('admin.pathways.show', compact('pathway'));
    }

    /**
     * Show the form for editing the specified pathway.
     */
    public function edit(Pathway $pathway)
    {
        return view('admin.pathways.edit', compact('pathway'));
    }

    /**
     * Update the specified pathway in storage.
     */
    public function update(Request $request, Pathway $pathway)
    {
        $request->merge(['status' => $request->has('status')]);
        $validated = $request->validate([
            'name' => [
                'required',
                'string',
                'max:255',
                Rule::unique('pathways', 'name')->ignore($pathway->id)
            ],
            'short_description' => 'nullable|string|max:1000',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'status' => 'boolean',
            'sorting' => 'nullable|integer|min:0'
        ]);

        // Handle logo upload
        if ($request->hasFile('logo')) {
            // Delete old logo if exists
            if ($pathway->logo && Storage::disk('public')->exists($pathway->logo)) {
                Storage::disk('public')->delete($pathway->logo);
            }

            $logoPath = $request->file('logo')->store('pathways/logos', 'public');
            $validated['logo'] = $logoPath;
        }

        // Set default values
        $validated['sorting'] = $validated['sorting'] ?? $pathway->sorting;

        $pathway->update($validated);

        return redirect()->route('admin.pathways.index')
            ->with('success', 'Pathway updated successfully.');
    }

    /**
     * Remove the specified pathway from storage.
     */
    public function destroy(Pathway $pathway)
    {
        // Delete logo file if exists
        if ($pathway->logo && Storage::disk('public')->exists($pathway->logo)) {
            Storage::disk('public')->delete($pathway->logo);
        }

        $pathway->delete();

        return redirect()->route('admin.pathways.index')
            ->with('success', 'Pathway deleted successfully.');
    }

    /**
     * Toggle the status of the specified pathway.
     */
    public function toggleStatus(Pathway $pathway)
    {
        $pathway->update(['status' => !$pathway->status]);

        $status = $pathway->status ? 'activated' : 'deactivated';

        return response()->json([
            'success' => true,
            'message' => "Pathway {$status} successfully.",
            'status' => $pathway->status,
            'status_text' => $pathway->status_text
        ]);
    }

    /**
     * Update the sorting order of pathways.
     */
    public function updateOrder(Request $request)
    {
        $request->validate([
            'pathways' => 'required|array',
            'pathways.*.id' => 'required|exists:pathways,id',
            'pathways.*.sorting' => 'required|integer|min:0'
        ]);

        foreach ($request->pathways as $pathwayData) {
            Pathway::where('id', $pathwayData['id'])
                ->update(['sorting' => $pathwayData['sorting']]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Pathway order updated successfully.'
        ]);
    }
}
