<?php
declare(strict_types=1);

namespace App;

final class ProfileSettings
{
    private bool $schemaEnsured = false;
    private array $columnCache = [];

    public function __construct(private \PDO $pdo)
    {
    }

    public function ensureSchema(): void
    {
        if ($this->schemaEnsured) {
            return;
        }

        if (!$this->hasColumn('user_profiles', 'location_tracking_preference')) {
            $this->pdo->exec(
                "ALTER TABLE user_profiles
                 ADD COLUMN location_tracking_preference ENUM('disabled','prompt','enabled')
                 NOT NULL DEFAULT 'prompt'
                 AFTER lng"
            );
            $this->columnCache['user_profiles.location_tracking_preference'] = true;
        }

        $this->schemaEnsured = true;
    }

    public function getLocationTrackingPreference(int $userId): string
    {
        if ($userId <= 0) {
            return 'prompt';
        }

        $this->ensureSchema();
        $stmt = $this->pdo->prepare('SELECT location_tracking_preference FROM user_profiles WHERE user_id = :id LIMIT 1');
        $stmt->execute(['id' => $userId]);
        $value = (string)($stmt->fetchColumn() ?: 'prompt');
        return in_array($value, ['disabled', 'prompt', 'enabled'], true) ? $value : 'prompt';
    }

    public function updateLocationTrackingPreference(int $userId, string $preference): void
    {
        if ($userId <= 0) {
            return;
        }

        $this->ensureSchema();
        $preference = in_array($preference, ['disabled', 'prompt', 'enabled'], true) ? $preference : 'prompt';
        $stmt = $this->pdo->prepare('UPDATE user_profiles SET location_tracking_preference = :pref, updated_at = NOW() WHERE user_id = :id');
        $stmt->execute([
            'pref' => $preference,
            'id' => $userId,
        ]);
    }

    private function hasColumn(string $table, string $column): bool
    {
        $cacheKey = $table . '.' . $column;
        if (array_key_exists($cacheKey, $this->columnCache)) {
            return $this->columnCache[$cacheKey];
        }

        $stmt = $this->pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.COLUMNS
            WHERE TABLE_SCHEMA = DATABASE()
              AND TABLE_NAME = :tableName
              AND COLUMN_NAME = :columnName
        ");
        $stmt->execute([
            'tableName' => $table,
            'columnName' => $column,
        ]);

        return $this->columnCache[$cacheKey] = ((int)$stmt->fetchColumn() > 0);
    }
}
