<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Partner;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class PartnerController extends Controller
{
    public function index()
    {
        $partners = Partner::orderBy('sort_order')->get();
        return view('admin.partners.index', compact('partners'));
    }

    public function create()
    {
        $partner = new Partner();
        return view('admin.partners.form', compact('partner'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'website_url' => 'nullable|url|max:255',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
            'logo_path' => 'nullable|string|max:255',
            'is_active' => 'boolean',
        ]);

        $partner = new Partner();
        $partner->name = $validated['name'];
        $partner->website_url = $validated['website_url'];
        $partner->is_active = $request->boolean('is_active', true);
        
        // Handle sort order - put at the end by default
        $partner->sort_order = Partner::max('sort_order') + 1;

        if ($request->hasFile('logo')) {
            $file = $request->file('logo');
            $filename = time() . '_' . Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)) . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads/partners'), $filename);
            $partner->logo_path = 'uploads/partners/' . $filename;
        } elseif ($request->filled('logo_path')) {
            $partner->logo_path = $request->logo_path;
        }

        $partner->save();

        return redirect()->route('admin.partners.index')->with('success', 'Partner added successfully!');
    }

    public function edit(Partner $partner)
    {
        return view('admin.partners.form', compact('partner'));
    }

    public function update(Request $request, Partner $partner)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'website_url' => 'nullable|url|max:255',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
            'logo_path' => 'nullable|string|max:255',
            'is_active' => 'boolean',
        ]);

        $partner->name = $validated['name'];
        $partner->website_url = $validated['website_url'];
        $partner->is_active = $request->boolean('is_active');

        if ($request->hasFile('logo')) {
            // Delete old logo only if it was a direct upload
            if ($partner->logo_path && Str::startsWith($partner->logo_path, 'uploads/partners/') && file_exists(public_path($partner->logo_path))) {
                @unlink(public_path($partner->logo_path));
            }

            $file = $request->file('logo');
            $filename = time() . '_' . Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)) . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads/partners'), $filename);
            $partner->logo_path = 'uploads/partners/' . $filename;
        } elseif ($request->filled('logo_path')) {
            $partner->logo_path = $request->logo_path;
        }

        $partner->save();

        return redirect()->route('admin.partners.index')->with('success', 'Partner updated successfully!');
    }

    public function destroy(Partner $partner)
    {
        if ($partner->logo_path && file_exists(public_path($partner->logo_path))) {
            @unlink(public_path($partner->logo_path));
        }
        
        $partner->delete();

        return redirect()->route('admin.partners.index')->with('success', 'Partner deleted successfully!');
    }

    public function reorder(Request $request)
    {
        $order = $request->input('order');
        foreach ($order as $index => $id) {
            Partner::where('id', $id)->update(['sort_order' => $index]);
        }
        return response()->json(['success' => true]);
    }
}
