<?php


namespace App\Http\Controllers\backend;

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

class HeadlineController extends Controller
{
    // Show the page (list + create form)
    public function index()
    {
        $headlines = Headline::latest()->paginate(12);
        return view('admin.headlines.index', [
            'headlines' => $headlines,
            'editing'   => false,
            'current'   => null,
        ]);
    }

    // Store a new headline
    public function store(Request $request)
    {
        $data = $request->validate([
            'headline' => ['required','string'],
        ]);

        Headline::create($data);

        return redirect()->route('headlines.index')->with('status', 'Headline created.');
    }

    // Open the same page in "edit mode"
    public function edit($id)
    {
        $current   = Headline::findOrFail($id);
        $headlines = Headline::latest()->paginate(12);

        return view('admin.headlines.index', [
            'headlines' => $headlines,
            'editing'   => true,
            'current'   => $current,
        ]);
    }

    // Update
    public function update(Request $request, $id)
    {
        $data = $request->validate([
            'headline' => ['required','string'],
        ]);

        $headline = Headline::findOrFail($id);
        $headline->update($data);

        return redirect()->route('headlines.index')->with('status', 'Headline updated.');
    }

    // Delete (inline form, no modal)
    public function destroy($id)
    {
        $headline = Headline::find($id);
        if ($headline) {
            $headline->delete();
            return redirect()->route('headlines.index')->with('status', 'Headline deleted.');
        }
        return redirect()->route('headlines.index')->with('status', 'Record not found.');
    }
}
