<?php

namespace App\Services\AttendanceTracking;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;

class AttendanceParentLookupService
{
    public function getPrimaryParentForStudent(int $studentId): ?array
    {
        $row = DB::table('students as s')
            ->selectRaw('u.id AS user_id, u.email, u.cellphone, CONCAT(u.firstname, " ", u.lastname) AS parent_name')
            ->leftJoin('users as u', 'u.id', '=', 's.parent_id')
            ->where('s.id', $studentId)
            ->first();

        if (!$row || empty($row->user_id)) {
            return null;
        }

        return [
            'user_id'     => (int) $row->user_id,
            'email'       => (string) ($row->email ?? ''),
            'parent_name' => (string) ($row->parent_name ?? ''),
            'phone'       => $row->cellphone ?? null,
        ];
    }

    public function getSecondaryParentForStudent(int $studentId, ?string $fallbackSchoolYear = null): ?array
    {
        try {
            $stu = DB::table('students')
                ->select('id', 'parent_id', 'school_year', 'semester')
                ->where('id', $studentId)
                ->first();

            if (!$stu) {
                return null;
            }

            $primaryId  = (int) ($stu->parent_id ?? 0);
            $schoolYear = (string) ($stu->school_year ?? $fallbackSchoolYear ?? '');

            $pb = DB::table('parents')->where('firstparent_id', $primaryId);
            if ($schoolYear !== '') {
                $pb->where('school_year', $schoolYear);
            }

            $pRow = $pb->orderByDesc('updated_at')->first();
            if (!$pRow) {
                return null;
            }

            $secondId = (int) ($pRow->secondparent_id ?? 0);
            if ($secondId > 0) {
                $u2 = DB::table('users')
                    ->select('id', 'firstname', 'lastname', 'email', 'cellphone')
                    ->where('id', $secondId)
                    ->first();

                if ($u2 && !empty($u2->email)) {
                    return [
                        'user_id'     => (int) $u2->id,
                        'email'       => (string) $u2->email,
                        'parent_name' => trim(($u2->firstname ?? '') . ' ' . ($u2->lastname ?? '')),
                        'phone'       => (string) ($u2->cellphone ?? ''),
                    ];
                }
            }

            $fallbackEmail = (string) ($pRow->secondparent_email ?? '');
            $fallbackPhone = (string) ($pRow->secondparent_phone ?? '');
            $fallbackFirst = (string) ($pRow->secondparent_firstname ?? '');
            $fallbackLast  = (string) ($pRow->secondparent_lastname ?? '');

            if ($fallbackEmail || $fallbackPhone || $fallbackFirst || $fallbackLast) {
                return [
                    'user_id'     => $secondId ?: null,
                    'email'       => $fallbackEmail,
                    'parent_name' => trim($fallbackFirst . ' ' . $fallbackLast) ?: null,
                    'phone'       => $fallbackPhone,
                ];
            }
        } catch (Throwable $e) {
            Log::error('getSecondaryParentForStudent() failed: ' . $e->getMessage());
        }

        return null;
    }

    public function parentsInfo(int $studentId, ?string $currentSchoolYear = null): array
    {
        if ($studentId <= 0) {
            return [
                'success' => false,
                'message' => 'Missing student_id',
                'status'  => 422,
            ];
        }

        try {
            $stu = DB::table('students')
                ->select('id', 'parent_id', 'school_year', 'semester')
                ->where('id', $studentId)
                ->first();

            if (!$stu) {
                return [
                    'success' => false,
                    'message' => 'Student not found',
                    'status'  => 404,
                ];
            }

            $primaryId  = (int) $stu->parent_id;
            $schoolYear = $stu->school_year ?: $currentSchoolYear;

            $u1 = DB::table('users')
                ->select('id', 'firstname', 'lastname', 'email', 'cellphone')
                ->where('id', $primaryId)
                ->first();

            $primary = $u1 ? [
                'id'        => (int) $u1->id,
                'firstname' => (string) $u1->firstname,
                'lastname'  => (string) $u1->lastname,
                'email'     => (string) $u1->email,
                'cellphone' => (string) $u1->cellphone,
            ] : null;

            $secondaryRaw = $this->getSecondaryParentForStudent($studentId, $schoolYear);

            $secondary = $secondaryRaw ? [
                'id'        => $secondaryRaw['user_id'] ?? null,
                'firstname' => null,
                'lastname'  => null,
                'email'     => $secondaryRaw['email'] ?? '',
                'cellphone' => $secondaryRaw['phone'] ?? '',
                'name'      => $secondaryRaw['parent_name'] ?? '',
            ] : null;

            return [
                'success' => true,
                'data'    => [
                    'primary'   => $primary,
                    'secondary' => $secondary,
                ],
            ];
        } catch (Throwable $e) {
            Log::error('parentsInfo() failed: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => 'Server error',
                'status'  => 500,
            ];
        }
    }
}