<?php
class QuickContact
{
    public static function forOwner(string $ownerType, ?int $ownerId = null): array
    {
        Database::migrate();
        if ($ownerId === null) {
            $stmt = Database::pdo()->prepare("SELECT * FROM quick_contacts WHERE owner_type = ? AND owner_id IS NULL ORDER BY CASE category WHEN 'alunos' THEN 1 WHEN 'trabalho' THEN 2 ELSE 3 END, name ASC");
            $stmt->execute([$ownerType]);
        } else {
            $stmt = Database::pdo()->prepare("SELECT * FROM quick_contacts WHERE owner_type = ? AND owner_id = ? ORDER BY CASE category WHEN 'alunos' THEN 1 WHEN 'trabalho' THEN 2 ELSE 3 END, name ASC");
            $stmt->execute([$ownerType, $ownerId]);
        }
        return $stmt->fetchAll();
    }

    public static function groupedForOwner(string $ownerType, ?int $ownerId = null): array
    {
        $grouped = [
            'alunos' => [],
            'trabalho' => [],
            'outros' => [],
        ];
        foreach (self::forOwner($ownerType, $ownerId) as $contact) {
            $folder = normalize_contact_folder($contact['category'] ?? 'outros');
            $contact['category'] = $folder;
            $grouped[$folder][] = $contact;
        }
        return $grouped;
    }

    public static function save(string $ownerType, ?int $ownerId, array $data): array
    {
        Database::migrate();
        $id = (int)($data['contact_id'] ?? 0);
        $name = trim($data['name'] ?? '');
        $whatsapp = only_digits((string)($data['whatsapp'] ?? ''));
        $notes = trim($data['notes'] ?? '');
        $category = normalize_contact_folder($data['category'] ?? 'outros');
        if ($name === '' || $whatsapp === '') {
            return ['ok' => false, 'message' => 'Informe nome e WhatsApp do contato.'];
        }
        if ($id > 0) {
            $stmt = Database::pdo()->prepare('UPDATE quick_contacts SET name = ?, whatsapp = ?, notes = ?, category = ? WHERE id = ? AND owner_type = ? AND ' . ($ownerId === null ? 'owner_id IS NULL' : 'owner_id = ?'));
            $params = [$name, $whatsapp, $notes, $category, $id, $ownerType];
            if ($ownerId !== null) {
                $params[] = $ownerId;
            }
            $stmt->execute($params);
            return ['ok' => true, 'message' => 'Contato atualizado na pasta ' . contact_folder_label($category) . '.'];
        }
        $stmt = Database::pdo()->prepare('INSERT INTO quick_contacts (owner_type, owner_id, name, whatsapp, notes, category, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)');
        $stmt->execute([$ownerType, $ownerId, $name, $whatsapp, $notes, $category, date('Y-m-d H:i:s')]);
        return ['ok' => true, 'message' => 'Contato salvo na pasta ' . contact_folder_label($category) . '.'];
    }

    public static function delete(string $ownerType, ?int $ownerId, int $id): bool
    {
        Database::migrate();
        if ($ownerId === null) {
            $stmt = Database::pdo()->prepare('DELETE FROM quick_contacts WHERE id = ? AND owner_type = ? AND owner_id IS NULL');
            $stmt->execute([$id, $ownerType]);
        } else {
            $stmt = Database::pdo()->prepare('DELETE FROM quick_contacts WHERE id = ? AND owner_type = ? AND owner_id = ?');
            $stmt->execute([$id, $ownerType, $ownerId]);
        }
        return $stmt->rowCount() > 0;
    }

    public static function upsertStudentForProfessional(int $professionalId, int $studentId): void
    {
        Database::migrate();
        if ($professionalId <= 0 || $studentId <= 0) return;

        Communication::saveContact('professional', $professionalId, 'student', $studentId);
        Communication::saveContact('student', $studentId, 'professional', $professionalId);

        $student = User::find($studentId);
        if (!$student || only_digits((string)($student['whatsapp'] ?? '')) === '') return;
        $note = 'Aluno vinculado automaticamente. ID:' . $studentId;
        $find = Database::pdo()->prepare("SELECT id FROM quick_contacts WHERE owner_type='professional' AND owner_id=? AND notes=? LIMIT 1");
        $find->execute([$professionalId, $note]);
        $id = (int)($find->fetchColumn() ?: 0);
        if ($id > 0) {
            $stmt = Database::pdo()->prepare("UPDATE quick_contacts SET name=?,whatsapp=?,category='alunos' WHERE id=?");
            $stmt->execute([(string)$student['name'], only_digits((string)$student['whatsapp']), $id]);
        } else {
            $stmt = Database::pdo()->prepare("INSERT INTO quick_contacts (owner_type,owner_id,name,whatsapp,notes,category,created_at) VALUES ('professional',?,?,?,?, 'alunos',?)");
            $stmt->execute([$professionalId, (string)$student['name'], only_digits((string)$student['whatsapp']), $note, date('Y-m-d H:i:s')]);
        }
    }

}
