<?php

namespace App\Http\Controllers;

use App\Models\Founder;
use Illuminate\Http\Request;

class FounderController extends Controller
{
    public function index()
    {
        $founders = Founder::all();
        return view('admin.founders.index', compact('founders'));
    }

    public function create()
    {
        return view('admin.founders.form');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'position' => 'required|string|max:255',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'about' => 'nullable|string',
        ]);

        if ($request->hasFile('image')) {
            $imageName = time() . '.' . $request->image->extension();
            $request->image->move(public_path('images/founder'), $imageName);
            $imagePath = 'images/founder/' . $imageName;
        }

        Founder::create([
            'name' => $request->name,
            'position' => $request->position,
            'image' => $imagePath,
            'about' => $request->about,
        ]);

        return redirect()->route('founders.index')->with('success', 'Founder added successfully.');
    }

    public function edit($id)
    {
        $founder = Founder::findOrFail($id);
        return view('admin.founders.form', compact('founder'));
    }

    public function update(Request $request, $id)
    {
        $founder = Founder::findOrFail($id);

        $request->validate([
            'name' => 'required|string|max:255',
            'position' => 'required|string|max:255',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'about' => 'nullable|string',
        ]);

        if ($request->hasFile('image')) {
            if ($founder->image && file_exists(public_path($founder->image))) {
                unlink(public_path($founder->image));
            }

            $imageName = time() . '.' . $request->image->extension();
            $request->image->move(public_path('images/blog'), $imageName);
            $imagePath = 'images/blog/' . $imageName;
        } else {
            $imagePath = $founder->image;
        }

        $founder->name = $request->name;
        $founder->position = $request->position;
        $founder->about = $request->about;
        $founder->image = $imagePath;
        $founder->save();

        return redirect()->route('founders.index')->with('success', 'Founder updated successfully.');
    }

    public function destroy($id)
    {
        $founder = Founder::findOrFail($id);
        // Optionally delete the image file from storage
        // Storage::disk('public')->delete($founder->image);
        $founder->delete();

        return redirect()->back()->with('success', 'Founder deleted successfully.');
    }
}
