<?php

namespace App\Http\Controllers;

use App\Models\Subject;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;
class SubjectController extends Controller
{

    public function show()
    {
        $subjects = Subject::all();
        return view('subject.subjects', compact('subjects'));
    }

    public function pdfSubjectList()
    {
        $subjects = Subject::all();

        $pdf = Pdf::loadView('subject.pdfSubjectList', compact('subjects'))->setPaper('A4', 'portrait');

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

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'nullable|string',
            'total_marks' => 'required|integer|min:0',
            'passing_marks' => 'required|integer|min:0|lte:total_marks',
        ]);

        // Normalize input by removing spaces
        $inputName = preg_replace('/\s+/', '', $request->name);
        $inputCode = $request->code ? preg_replace('/\s+/', '', $request->code) : null;

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

        // Check for duplicate code (only if code is provided)
        if ($inputCode) {
            $existingCode = Subject::whereRaw('REPLACE(code, " ", "") = ?', [$inputCode])->first();
            if ($existingCode) {
                return redirect()->back()->with('error', "Subject code \"{$request->code}\" already exists (ignoring spaces).");
            }
        }

        // Create new subject
        $subject = new Subject();
        $subject->name = $request->name;
        $subject->code = $request->code;
        $subject->total_marks = $request->total_marks;
        $subject->passing_marks = $request->passing_marks;
        $subject->save();

        return redirect()->back()->with('success', 'Subject added successfully.');
    }
    public function update($id, Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'nullable|string',
            'total_marks' => 'required|integer|min:0',
            'passing_marks' => 'required|integer|min:0|lte:total_marks',
        ]);

        // Normalize inputs (remove spaces)
        $inputName = preg_replace('/\s+/', '', $request->name);
        $inputCode = $request->code ? preg_replace('/\s+/', '', $request->code) : null;

        // Check for duplicate name (excluding current record)
        $existingName = Subject::where('id', '!=', $id)
            ->whereRaw('REPLACE(name, " ", "") = ?', [$inputName])
            ->first();

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

        // Check for duplicate code (if provided), excluding current record
        if ($inputCode) {
            $existingCode = Subject::where('id', '!=', $id)
                ->whereRaw('REPLACE(code, " ", "") = ?', [$inputCode])
                ->first();

            if ($existingCode) {
                return redirect()->back()->with('error', "Another subject with the code \"{$request->code}\" already exists (ignoring spaces).");
            }
        }

        // Update the subject
        $subject = Subject::findOrFail($id);
        $subject->name = $request->name;
        $subject->code = $request->code;
        $subject->total_marks = $request->total_marks;
        $subject->passing_marks = $request->passing_marks;
        $subject->save();

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

    /*   public function delete($id)
    {
        $subject = Subject::findOrFail($id);
        $subject->delete();
        return redirect()->back()->with('success', 'Subject deleted successfully.');
    } */
}
