<?php

namespace App\Http\Controllers\Admin;

use App\Models\Row2;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class Row2Controller extends Controller
{

    public function index()
    {
        $datas = Row2::all();
        return view('admin.row2.index', compact('datas'));
    }

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            $request->validate([
                'title' => 'required',
            ]);

            if ($request->hasFile('photo')) {

                $photo = time() . '_' . $request->file('photo')->getClientOriginalName();
                $request->file('photo')->move(public_path('img'), $photo);
            } else {
                $photo = null;
            }

        $model = new Row2();
        $model->title = $request->title;
        $model->photo = $photo;
        $model->save();

        // Return success response
        return redirect()->route('row2.index')->with('success', 'Row section created successfully');


        } catch (\Exception $e) {
            \Log::error('Error storing row2 section: ' . $e->getMessage());

            return back()->with('error', 'Something went wrong. Please try again.');
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $row2 = Row2::findOrFail($id);
        if ($row2->image && file_exists(public_path('img/' . $row2->image))) {
            unlink(public_path('img/' . $row2->image));
        }

        $row2->delete();

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