<?php

namespace App\Http\Controllers\Admin;

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

class ParentController extends Controller
{

	public function index(Request $request)
	{
		$q = $request->string('q')->toString();

		$parents = ParentProfile::query()
			->with('user')
			->when($q, function ($query) use ($q) {
				$query->whereHas('user', function ($u) use ($q) {
					$u->where('first_name', 'like', "%{$q}%")
					  ->orWhere('last_name', 'like', "%{$q}%")
					  ->orWhere('email', 'like', "%{$q}%");
				});
			})
			->orderByDesc('created_at')
			->paginate(25)
			->withQueryString();

		return view('admin.parents.index', compact('parents', 'q'));
	}

	public function create()
	{
		$parents = ParentProfile::with('user')->get();
		$studentTypes = StudentType::all();

		return view('admin.students.create', compact('parents', 'studentTypes'));
	}

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'  => ['required', 'string', 'max:255'],
            'email' => ['nullable', 'email', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'notes' => ['nullable', 'string'],
        ]);

        ParentProfile::create($validated);

        return redirect()->route('admin.parents.index')
            ->with('success', 'Parent created.');
    }

    public function edit(ParentProfile $parent)
    {
        return view('admin.parents.edit', compact('parent'));
    }

    public function update(Request $request, ParentProfile $parent)
    {
        $validated = $request->validate([
            'name'  => ['required', 'string', 'max:255'],
            'email' => ['nullable', 'email', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'notes' => ['nullable', 'string'],
        ]);

        $parent->update($validated);

        return redirect()->route('admin.parents.edit', $parent)
            ->with('success', 'Parent updated.');
    }

    public function destroy(ParentProfile $parent)
    {
        $parent->delete();

        return redirect()->route('admin.parents.index')
            ->with('success', 'Parent deleted.');
    }
}