<?php
/**
 * Admin Model
 */

class Admin {
    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    /**
     * Login admin
     */
    public function login($username, $password) {
        $stmt = $this->pdo->prepare("SELECT * FROM admins WHERE username = :username");
        $stmt->execute([':username' => $username]);
        $admin = $stmt->fetch();

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

        return false;
    }

    /**
     * Get admin by ID
     */
    public function getById($id) {
        $stmt = $this->pdo->prepare("SELECT * FROM admins WHERE id = :id");
        $stmt->execute([':id' => $id]);
        return $stmt->fetch();
    }

    /**
     * Create admin
     */
    public function create($data) {
        $stmt = $this->pdo->prepare("
            INSERT INTO admins (username, email, password, full_name)
            VALUES (:username, :email, :password, :full_name)
        ");

        return $stmt->execute([
            ':username' => $data['username'] ?? '',
            ':email' => $data['email'] ?? '',
            ':password' => password_hash($data['password'] ?? '', PASSWORD_BCRYPT),
            ':full_name' => $data['full_name'] ?? ''
        ]);
    }

    /**
     * Update admin
     */
    public function update($id, $data) {
        $fields = [];
        $params = [':id' => $id];

        foreach ($data as $key => $value) {
            if ($key === 'password') {
                $value = password_hash($value, PASSWORD_BCRYPT);
            }
            $fields[] = "$key = :$key";
            $params[":$key"] = $value;
        }

        $sql = "UPDATE admins SET " . implode(', ', $fields) . " WHERE id = :id";
        $stmt = $this->pdo->prepare($sql);
        return $stmt->execute($params);
    }

    /**
     * Check if admin is logged in
     */
    public static function isLoggedIn() {
        return isset($_SESSION['admin_id']) && !empty($_SESSION['admin_id']);
    }

    /**
     * Get current admin
     */
    public function getCurrentAdmin() {
        if (self::isLoggedIn()) {
            return $this->getById($_SESSION['admin_id']);
        }
        return null;
    }

    /**
     * Logout
     */
    public static function logout() {
        session_destroy();
        Utils::redirect('/routex/admin/login');
    }
}
