<?php
namespace Models;

use Core\Model;

class User extends Model {
    protected string $table = 'users';

    public function findByEmail(string $email): ?array {
        return $this->db->fetch("SELECT * FROM users WHERE email=? LIMIT 1", [$email]);
    }

    public function findByAssessmentNo(string $no): ?array {
        return $this->db->fetch(
            "SELECT u.* FROM users u
             JOIN students s ON s.user_id=u.id
             WHERE s.assessment_no=? LIMIT 1", [$no]
        );
    }

    public function getWithRole(int $schoolId, int $page = 1, array $filters = []): array {
        $where  = ['school_id=?'];
        $params = [$schoolId];
        if (!empty($filters['search'])) {
            $where[]  = '(name LIKE ? OR email LIKE ? OR phone LIKE ?)';
            $s = '%'.$filters['search'].'%';
            $params[] = $s; $params[] = $s; $params[] = $s;
        }
        if (!empty($filters['role']))   { $where[] = 'role=?';      $params[] = $filters['role']; }
        if ($filters['status'] !== '')  { $where[] = 'is_active=?'; $params[] = (int)$filters['status']; }
        $w = implode(' AND ', $where);
        return $this->db->paginate("SELECT * FROM users WHERE $w ORDER BY name", $params, $page, 20);
    }

    public function updateLastLogin(int $id, string $ip): void {
        $this->update($id, ['last_login_at' => date('Y-m-d H:i:s'), 'last_login_ip' => $ip]);
    }

    public function setTwoFaCode(int $id, string $hashedCode): void {
        $this->update($id, [
            'two_fa_code'       => $hashedCode,
            'two_fa_expires_at' => date('Y-m-d H:i:s', strtotime('+10 minutes')),
        ]);
    }

    public function clearTwoFa(int $id): void {
        $this->update($id, ['two_fa_code' => null, 'two_fa_expires_at' => null]);
    }
}
