<?php

namespace App\Http\Controllers;

use App\Http\Requests\FamilyRequest;
use App\Models\Family;
use App\Services\FamilyService;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\View\View;

class FamilyController extends Controller implements HasMiddleware
{
    public function __construct(private FamilyService $service)
    {
    }

    public static function middleware(): array
    {
        return [
            new Middleware('can:viewAny,'.Family::class, only: ['index']),
            new Middleware('can:create,'.Family::class, only: ['create', 'store']),
            new Middleware('can:view,family', only: ['show']),
            new Middleware('can:update,family', only: ['edit', 'update']),
            new Middleware('can:delete,family', only: ['destroy']),
        ];
    }

    public function index(Request $request): View
    {
        $siblingsOnly = $request->boolean('siblings');

        $query = $this->service->listing();
        if ($siblingsOnly) {
            $query->has('students', '>', 1); // families with 2+ students
        }
        $families = $query->get();

        return view('families.index', compact('families', 'siblingsOnly'));
    }

    public function create(): View
    {
        return view('families.create', ['family' => new Family()]);
    }

    public function store(FamilyRequest $request): RedirectResponse
    {
        $family = $this->service->create($request->validated());

        return redirect()->route('families.show', $family)->with('success', 'Family created successfully.');
    }

    /**
     * Quick-create a family from the student admission modal. Returns JSON so the
     * new family can be appended to and auto-selected in the family dropdown.
     */
    public function quickStore(\Illuminate\Http\Request $request): \Illuminate\Http\JsonResponse
    {
        $this->authorize('create', Family::class);

        $data = $request->validate([
            'father_name' => ['required_without:guardian_name', 'nullable', 'string', 'max:150'],
            'guardian_name' => ['nullable', 'string', 'max:150'],
            'father_mobile' => ['nullable', 'string', 'max:30'],
            'father_cnic' => ['nullable', 'string', 'max:20'],
            'mother_name' => ['nullable', 'string', 'max:150'],
            'email' => ['nullable', 'email', 'max:150'],
            'address' => ['nullable', 'string', 'max:500'],
            'branch_id' => ['nullable', 'exists:branches,id'],
        ]);

        // Resolve a branch: explicit → active branch → user's branch → first branch.
        $data['branch_id'] = $data['branch_id']
            ?? app(\App\Support\BranchContext::class)->currentId()
            ?? auth()->user()?->branch_id
            ?? \App\Models\Branch::min('id');

        $family = $this->service->create($data);

        return response()->json([
            'id' => $family->id,
            'code' => $family->family_code,
            'label' => $family->family_code.' — '.$family->primary_contact_name,
        ]);
    }

    public function show(Family $family): View
    {
        $family->load(['students.schoolClass', 'students.section']);

        return view('families.show', compact('family'));
    }

    public function edit(Family $family): View
    {
        return view('families.edit', compact('family'));
    }

    public function update(FamilyRequest $request, Family $family): RedirectResponse
    {
        $this->service->update($family->id, $request->validated());

        return redirect()->route('families.show', $family)->with('success', 'Family updated successfully.');
    }

    public function destroy(Family $family): RedirectResponse
    {
        if ($family->students()->exists()) {
            return back()->with('error', 'Cannot delete a family that still has students.');
        }

        $this->service->delete($family->id);

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

    /** Create (or reset) a parent-portal login for a family. */
    public function createLogin(Family $family): RedirectResponse
    {
        $this->authorize('update', $family);

        $password = \Illuminate\Support\Str::password(10, symbols: false);
        $email = $family->email ?: strtolower($family->family_code).'@parent.school.test';

        if ($family->portalUser) {
            $family->portalUser->update(['password' => \Illuminate\Support\Facades\Hash::make($password)]);
            $user = $family->portalUser;
        } else {
            $user = \App\Models\User::create([
                'name' => $family->primary_contact_name !== '—' ? $family->primary_contact_name : 'Parent of '.$family->family_code,
                'email' => $email,
                'password' => \Illuminate\Support\Facades\Hash::make($password),
                'branch_id' => $family->branch_id,
                'is_active' => true,
                'email_verified_at' => now(),
            ]);
            $user->syncRoles(['Parent']);
            $family->update(['user_id' => $user->id]);
        }

        return back()->with('success', "Parent login ready — Email: {$user->email}  |  Password: {$password}  (save this now)");
    }
}
