<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * User Model
 *
 * Handles system users (admin, staff, student) data retrieval
 * and authentication-related operations.
 */
class User extends Model
{
    /**
     * The database table associated with the model.
     */
    protected string $table = 'users';

    /**
     * Get a user by their email address.
     *
     * @param string $email The email address to look up
     * @return array<string, mixed>|null The user record or null if not found
     */
    public function getByEmail(string $email): ?array
    {
        $sql = sprintf(
            'SELECT * FROM `%s` WHERE `email` = :email LIMIT 1',
            $this->table
        );

        $stmt = $this->db->prepare($sql);
        $stmt->execute([':email' => $email]);

        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        return $result !== false ? $result : null;
    }

    /**
     * Create a new student user and return the insert ID.
     *
     * Hashes the password with bcrypt and sets the role to 'student'.
     *
     * @param array<string, mixed> $data User data including 'name', 'email', 'password' (plain text)
     * @return int The last inserted ID
     */
    public function createStudent(array $data): int
    {
        $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT);
        $data['role'] = 'student';
        $data['is_active'] = 1;

        return $this->create($data);
    }

    /**
     * Update a user's password hash.
     *
     * @param int $id The user ID
     * @param string $hash The new bcrypt password hash
     * @return bool True if the update affected at least one row
     */
    public function updatePassword(int $id, string $hash): bool
    {
        return $this->update($id, ['password' => $hash]);
    }
}
