<?php

namespace App\Http\Controllers;

use App\Models\Section;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;
class SectionController extends Controller
{
    public function show()
    {
        $sections = Section::all();
        return view('section.sections', compact('sections'));
    }

    public function pdfSectionList()
    {
        $sections = Section::all();

        $pdf = Pdf::loadView('section.pdfSectionList', compact('sections'))->setPaper('A4', 'portrait');

        return $pdf->download('section-list.pdf');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'capacity' => 'nullable|string',
        ]);

        // Remove spaces for duplicate check
        $inputName = preg_replace('/\s+/', '', $request->name);

        // Check for duplicate section name (ignoring spaces)
        $existingSection = Section::whereRaw('REPLACE(name, " ", "") = ?', [$inputName])->first();
        if ($existingSection) {
            return back()->with('error', 'Section name "' . $request->name . '" already exists (ignoring spaces).');
        }

        // Save the section
        $section = new Section();
        $section->name = $request->name;
        $section->capacity = $request->capacity;
        $section->save();

        return redirect()->back()->with('success', 'Section added successfully.');
    }


    public function update($id, Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'capacity' => 'nullable|string',
        ]);

        // Remove spaces from input
        $inputName = preg_replace('/\s+/', '', $request->name);

        // Check for duplicate (ignoring spaces), excluding the current section
        $existingSection = Section::where('id', '!=', $id)
            ->whereRaw('REPLACE(name, " ", "") = ?', [$inputName])
            ->first();

        if ($existingSection) {
            return back()->with('error', 'Another section with the name "' . $request->name . '" already exists (ignoring spaces).');
        }

        // Proceed with update
        $section = Section::findOrFail($id);
        $section->name = $request->name;
        $section->capacity = $request->capacity;
        $section->save();

        return redirect()->back()->with('success', 'Section updated successfully.');
    }



    /*  public function delete($id)
    {
        $section = Section::findOrFail($id);
        if ($section != null) {
            $section->delete();
        }

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