<?php
declare(strict_types=1);

function admin_user(): ?array
{
    static $resolved = false;
    static $cached = null;

    if ($resolved) return $cached;
    $resolved = true;

    $id = (int) ($_SESSION['admin_id'] ?? 0);
    if ($id < 1) return null;

    try {
        // Burada ayrıca tablo-varlık kontrolü yapılmıyor. Doğrudan sorgulamak,
        // farklı MySQL/MariaDB sürümlerindeki SHOW TABLES uyumsuzluğunu önler.
        $stmt = db()->prepare(
            'SELECT id,name,email,role,must_change_password,is_active
             FROM users
             WHERE id=?
             LIMIT 1'
        );
        $stmt->execute([$id]);
        $user = $stmt->fetch();
    } catch (Throwable $e) {
        @file_put_contents(
            dirname(__DIR__) . '/storage/logs/admin-auth.log',
            '[' . date('c') . '] admin_user: ' . $e->getMessage() . "\n",
            FILE_APPEND | LOCK_EX
        );
        unset($_SESSION['admin_id'], $_SESSION['admin_login_at']);
        return null;
    }

    if (!$user || !(int) $user['is_active']) {
        unset($_SESSION['admin_id'], $_SESSION['admin_login_at']);
        return null;
    }

    return $cached = $user;
}

function require_admin(): void
{
    if (!admin_user()) {
        $_SESSION['intended'] = current_url();
        session_write_close();
        redirect('/admin/login.php');
    }
}

function admin_login(string $identifier, string $password): bool
{
    $identifier = mb_strtolower(trim($identifier));
    if ($identifier === '' || $password === '') return false;

    $stmt = db()->prepare(
        'SELECT * FROM users
         WHERE is_active=1 AND (LOWER(TRIM(email))=? OR LOWER(TRIM(name))=?)
         LIMIT 1'
    );
    $stmt->execute([$identifier, $identifier]);
    $user = $stmt->fetch();
    if (!$user) return false;

    $storedHash = (string) ($user['password_hash'] ?? '');
    $verified = password_verify($password, $storedHash);
    $legacyMd5 = false;

    if (!$verified && preg_match('/^[a-f0-9]{32}$/i', $storedHash) === 1) {
        $legacyMd5 = hash_equals(strtolower($storedHash), md5($password));
        $verified = $legacyMd5;
    }

    if (!$verified) return false;

    if ($legacyMd5 || password_needs_rehash($storedHash, PASSWORD_DEFAULT)) {
        $newHash = password_hash($password, PASSWORD_DEFAULT);
        if ($newHash !== false) {
            db()->prepare('UPDATE users SET password_hash=?,must_change_password=0 WHERE id=?')
                ->execute([$newHash, $user['id']]);
        }
    }

    session_regenerate_id(true);
    $_SESSION['admin_id'] = (int) $user['id'];
    $_SESSION['admin_login_at'] = time();
    $_SESSION['admin_session_check'] = bin2hex(random_bytes(16));

    db()->prepare('UPDATE users SET last_login_at=NOW() WHERE id=?')->execute([$user['id']]);
    audit_log('login', 'users', (int) $user['id'], 'Yönetim paneli girişi');
    return true;
}

function audit_log(string $action, string $entity, ?int $entityId = null, string $details = ''): void
{
    if (!db_table_exists('audit_logs')) return;
    $userId = isset($_SESSION['admin_id']) ? (int) $_SESSION['admin_id'] : null;
    try {
        $stmt = db()->prepare('INSERT INTO audit_logs (user_id,action,entity,entity_id,details,ip_address,created_at) VALUES (?,?,?,?,?,?,NOW())');
        $stmt->execute([$userId, $action, $entity, $entityId, $details, client_ip()]);
    } catch (Throwable) {}
}

function admin_can_access(string $file, ?array $user = null): bool
{
    $user ??= admin_user();
    if (!$user) return false;
    $role = (string) $user['role'];
    if ($role === 'super_admin') return true;
    $common = ['index.php','account.php'];
    $maps = [
        'manager' => ['reservations.php','services.php','service-edit.php','gallery.php','therapists.php','rooms.php','schedule.php','posts.php','pages.php','content-edit.php','article-generate.php','automation.php','settings.php','seo.php'],
        'reception' => ['reservations.php','schedule.php'],
        'editor' => ['services.php','service-edit.php','gallery.php','posts.php','pages.php','content-edit.php','article-generate.php','automation.php'],
    ];
    return in_array($file, array_merge($common, $maps[$role] ?? []), true);
}

function require_admin_access(string $file): void
{
    if (!admin_can_access($file)) {
        http_response_code(403);
        exit('Bu bölüm için yetkiniz bulunmuyor.');
    }
}
