<?php

namespace Core\App\Models;

use DateTime;

class AdminModel extends BaseModel
{
    protected string $table = 'admins';

    /**
     * جلب Admin بواسطة username
     */
    public function findByUsername(string $username): ?array
    {
        $sql = "
            SELECT *
            FROM {$this->table}
            WHERE username = :username
            LIMIT 1
        ";

        return $this->fetchOne($sql, [
            'username' => $username
        ]);
    }

    /**
     * جلب Admin بواسطة البريد الإلكتروني
     */
    public function findByEmail(string $email): ?array
    {
        $sql = "
            SELECT *
            FROM {$this->table}
            WHERE email = :email
            LIMIT 1
        ";

        return $this->fetchOne($sql, [
            'email' => $email
        ]);
    }

    /**
     * التحقق من بيانات تسجيل الدخول
     */
    public function authenticate(string $username, string $password): ?array
    {
        $admin = $this->findByUsername($username);

        if (!$admin) {
            return null;
        }

        if ((int)$admin['is_active'] !== 1) {
            return null;
        }

        if (!password_verify($password, $admin['password'])) {
            return null;
        }

        $this->updateLastLogin((int)$admin['id']);

        return $admin;
    }

    /**
     * تحديث آخر تسجيل دخول
     */
    protected function updateLastLogin(int $adminId): void
    {
        $sql = "
            UPDATE {$this->table}
            SET last_login_at = :last_login
            WHERE id = :id
        ";

        $this->execute($sql, [
            'last_login' => (new DateTime())->format('Y-m-d H:i:s'),
            'id'         => $adminId
        ]);
    }

    /**
     * تحديث كلمة مرور الأدمن (تُستخدم في reset-password)
     */
    public function updatePassword(int $adminId, string $newPassword): bool
    {
        $sql = "
            UPDATE {$this->table}
            SET password = :password
            WHERE id = :id
            LIMIT 1
        ";

        return $this->execute($sql, [
            'password' => password_hash($newPassword, PASSWORD_DEFAULT),
            'id'       => $adminId
        ]);
    }

    /**
     * إنشاء Admin جديد
     * (يُستخدم مرة واحدة أو لاحقاً من لوحة التحكم)
     */
    public function create(
        string $username,
        string $password,
        ?string $email = null
    ): bool {
        $sql = "
            INSERT INTO {$this->table}
                (username, password, email)
            VALUES
                (:username, :password, :email)
        ";

        return $this->execute($sql, [
            'username' => $username,
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'email'    => $email
        ]);
    }
}
