<?php

namespace App\Controllers\View;

use App\Controllers\BaseController;
use App\Models\EmergencyContactModel;
use App\Models\StudentModel;
use App\Models\UserModel;
use CodeIgniter\HTTP\ResponseInterface;

class EmergencyContactController extends BaseController
{
    protected $contactModel;
    protected $studentModel;
    protected $userModel;

    public function __construct()
    {
        $this->contactModel = new EmergencyContactModel();
        $this->studentModel = new StudentModel();
        $this->userModel = new UserModel(); // Add this
    }

    public function index()
    {
        $db = \Config\Database::connect();
        $parentIds = $this->contactModel
            ->distinct()
            ->select('parent_id')
            ->findAll();

        $data = [];

        foreach ($parentIds as $row) {
            $parentId = $row['parent_id'];

            $parent = $this->userModel->find($parentId); // Get parent info
            $parentName  = $parent ? $parent['firstname'] . ' ' . $parent['lastname'] : 'Unknown Parent';
            $parentPhone = is_array($parent) ? (string)($parent['cellphone'] ?? '') : '';

            // Try to load second parent phone from parents table (if available)
            $secondPhone = '';
            try {
                $row = $db->table('parents')
                    ->select('secondparent_phone')
                    ->where('firstparent_id', (int) $parentId)
                    ->orderBy('updated_at', 'DESC')
                    ->get()->getRowArray();
                if ($row && !empty($row['secondparent_phone'])) {
                    $secondPhone = (string) $row['secondparent_phone'];
                }
            } catch (\Throwable $e) {
                log_message('debug', 'EmergencyContactController: could not load second parent phone: ' . $e->getMessage());
            }

            $students = $this->studentModel
                ->where('parent_id', $parentId)
                ->findAll();

            $contacts = $this->contactModel
                ->getEmergencyContactsByParentId($parentId);

            $data[] = [
                'parent_id'   => $parentId,
                'parent_name' => $parentName,
                'students'    => $students,
                'contacts'    => $contacts,
                'parent_phones' => array_values(array_filter([$parentPhone, $secondPhone], static fn($v) => (string)$v !== '')),
            ];
        }

        return view('administrator/emergency_contact/index', ['groups' => $data]);
    }


    public function edit($id)
    {
        $contact = $this->contactModel->find($id);
        return view('administrator/emergency_contact/edit', ['contact' => $contact]);
    }

public function update($id)
{
    dd("Update was called with ID: $id", $this->request->getPost());
}



    public function delete($id)
    {
        $this->contactModel->delete($id);
        return redirect()->to('/administrator/emergency_contact')->with('success', 'Contact deleted.');
    }

    // API: JSON payload for emergency contacts grouped by parent
    public function data()
    {
        // Build groups similarly to index(), but return JSON
        $parentRows = $this->contactModel
            ->distinct()
            ->select('parent_id')
            ->findAll();

        $groups = [];
        foreach ($parentRows as $row) {
            $parentId = (int)($row['parent_id'] ?? 0);
            if ($parentId <= 0) continue;

            $parent = $this->userModel->find($parentId) ?: [];
            $parentName = trim(($parent['firstname'] ?? '') . ' ' . ($parent['lastname'] ?? '')) ?: 'Unknown Parent';

            $students = $this->studentModel
                ->select('id, firstname, lastname, school_id')
                ->where('parent_id', $parentId)
                ->findAll();

            $contacts = $this->contactModel
                ->where('parent_id', $parentId)
                ->orderBy('updated_at', 'DESC')
                ->findAll();

            $groups[] = [
                'parent_id'   => $parentId,
                'parent_name' => $parentName,
                'students'    => $students,
                'contacts'    => $contacts,
            ];
        }

        return $this->response->setJSON([
            'groups'   => $groups,
            'csrfHash' => csrf_hash(),
        ]);
    }
}
