<?php
namespace Domain\User;

/**
 * Repository odpowiedzialny za dostep do danych uzytkownikow admina.
 */
class UserRepository
{
    private const MAX_PER_PAGE = 100;

    private $db;

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

    public function getById(int $userId): ?array
    {
        $user = $this->db->get('pp_users', '*', ['id' => $userId]);
        return $user ?: null;
    }

    public function updateById(int $userId, array $data): bool
    {
        return (bool)$this->db->update('pp_users', $data, ['id' => $userId]);
    }

    public function verifyTwofaCode(int $userId, string $code): bool
    {
        $user = $this->getById($userId);
        if (!$user) {
            return false;
        }

        if ((int)($user['twofa_failed_attempts'] ?? 0) >= 5) {
            return false;
        }

        if (empty($user['twofa_expires_at']) || time() > strtotime((string)$user['twofa_expires_at'])) {
            $this->updateById($userId, [
                'twofa_code_hash' => null,
                'twofa_expires_at' => null,
            ]);
            return false;
        }

        $ok = (!empty($user['twofa_code_hash']) && password_verify($code, (string)$user['twofa_code_hash']));
        if ($ok) {
            $this->updateById($userId, [
                'twofa_code_hash' => null,
                'twofa_expires_at' => null,
                'twofa_sent_at' => null,
                'twofa_failed_attempts' => 0,
                'last_logged' => date('Y-m-d H:i:s'),
            ]);
            return true;
        }

        $this->updateById($userId, [
            'twofa_failed_attempts' => (int)($user['twofa_failed_attempts'] ?? 0) + 1,
            'last_error_logged' => date('Y-m-d H:i:s'),
        ]);

        return false;
    }

    public function sendTwofaCode(int $userId, bool $resend = false): bool
    {
        $user = $this->getById($userId);
        if (!$user) {
            return false;
        }

        if ((int)($user['twofa_enabled'] ?? 0) !== 1) {
            return false;
        }

        $to = !empty($user['twofa_email']) ? (string)$user['twofa_email'] : (string)$user['login'];
        if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
            return false;
        }

        if ($resend && !empty($user['twofa_sent_at'])) {
            $last = strtotime((string)$user['twofa_sent_at']);
            if ($last && (time() - $last) < 30) {
                return false;
            }
        }

        $code = random_int(100000, 999999);
        $hash = password_hash((string)$code, PASSWORD_DEFAULT);

        $this->updateById($userId, [
            'twofa_code_hash' => $hash,
            'twofa_expires_at' => date('Y-m-d H:i:s', time() + 10 * 60),
            'twofa_sent_at' => date('Y-m-d H:i:s'),
            'twofa_failed_attempts' => 0,
        ]);

        $subject = 'Twoj kod logowania 2FA';
        $body = 'Twoj kod logowania do panelu administratora: ' . $code . '. Kod jest wazny przez 10 minut.';

        $sent = \Shared\Helpers\Helpers::send_email($to, $subject, $body);
        if ($sent) {
            return true;
        }

        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/plain; charset=UTF-8\r\n";
        $headers .= "From: no-reply@" . ($_SERVER['HTTP_HOST'] ?? 'localhost') . "\r\n";
        $encodedSubject = mb_encode_mimeheader($subject, 'UTF-8');

        return mail($to, $encodedSubject, $body, $headers);
    }

    public function delete(int $userId): bool
    {
        return (bool)$this->db->delete('pp_users', ['id' => $userId]);
    }

    public function find(int $userId): ?array
    {
        $user = $this->db->get('pp_users', '*', ['id' => $userId]);
        return $user ?: null;
    }

    public function save(
        int $userId,
        string $login,
        $status,
        string $password,
        string $passwordRepeat,
        $admin,
        $twofaEnabled = 0,
        string $twofaEmail = ''
    ): array {
        if ($userId <= 0) {
            if (strlen($password) < 5) {
                return ['status' => 'error', 'msg' => 'Podane haslo jest zbyt krotkie.'];
            }

            if ($password !== $passwordRepeat) {
                return ['status' => 'error', 'msg' => 'Podane hasla sa rozne'];
            }

            $inserted = $this->db->insert('pp_users', [
                'login' => $login,
                'status' => $this->toSwitchValue($status),
                'admin' => (int)$admin,
                'password' => md5($password),
                'twofa_enabled' => $this->toSwitchValue($twofaEnabled),
                'twofa_email' => $twofaEmail,
            ]);

            if ($inserted) {
                \Shared\Helpers\Helpers::delete_dir('../temp/');
                return ['status' => 'ok', 'msg' => 'Uzytkownik zostal zapisany.'];
            }

            return ['status' => 'error', 'msg' => 'Podczas zapisywania uzytkownika wystapil blad.'];
        }

        if ($password !== '' && strlen($password) < 5) {
            return ['status' => 'error', 'msg' => 'Podane haslo jest zbyt krotkie.'];
        }

        if ($password !== '' && $password !== $passwordRepeat) {
            return ['status' => 'error', 'msg' => 'Podane hasla sa rozne'];
        }

        if ($password !== '') {
            $this->db->update('pp_users', [
                'password' => md5($password),
            ], [
                'id' => $userId,
            ]);
        }

        $this->db->update('pp_users', [
            'login' => $login,
            'admin' => (int)$admin,
            'status' => $this->toSwitchValue($status),
            'twofa_enabled' => $this->toSwitchValue($twofaEnabled),
            'twofa_email' => $twofaEmail,
        ], [
            'id' => $userId,
        ]);

        \Shared\Helpers\Helpers::delete_dir('../temp/');
        return ['status' => 'ok', 'msg' => 'Uzytkownik zostal zapisany.'];
    }

    public function checkLogin(string $login, int $userId): array
    {
        $existing = $this->db->get('pp_users', 'login', [
            'AND' => [
                'login' => $login,
                'id[!]' => $userId,
            ],
        ]);

        if ($existing) {
            return ['status' => 'error', 'msg' => 'Podany login jest juz zajety.'];
        }

        return ['status' => 'ok'];
    }

    public function logon(string $login, string $password): int
    {
        if (!$this->db->get('pp_users', '*', ['login' => $login])) {
            return 0;
        }

        if (!$this->db->get('pp_users', '*', [
            'AND' => [
                'login' => $login,
                'status' => 1,
                'error_logged_count[<]' => 5,
            ],
        ])) {
            return -1;
        }

        if ($this->db->get('pp_users', '*', [
            'AND' => [
                'login' => $login,
                'status' => 1,
                'password' => md5($password),
            ],
        ])) {
            $this->db->update('pp_users', [
                'last_logged' => date('Y-m-d H:i:s'),
                'error_logged_count' => 0,
            ], [
                'login' => $login,
            ]);

            return 1;
        }

        $this->db->update('pp_users', [
            'last_error_logged' => date('Y-m-d H:i:s'),
            'error_logged_count[+]' => 1,
        ], [
            'login' => $login,
        ]);

        if ((int)$this->db->get('pp_users', 'error_logged_count', ['login' => $login]) >= 5) {
            $this->db->update('pp_users', ['status' => 0], ['login' => $login]);
            return -1;
        }

        return 0;
    }

    public function details(string $login): ?array
    {
        $user = $this->db->get('pp_users', '*', ['login' => $login]);
        return $user ?: null;
    }

    /**
     * @return array{items: array<int, array<string, mixed>>, total: int}
     */
    public function listForAdmin(
        array $filters,
        string $sortColumn = 'login',
        string $sortDir = 'ASC',
        int $page = 1,
        int $perPage = 15
    ): array {
        $allowedSortColumns = [
            'login' => 'pu.login',
            'status' => 'pu.status',
        ];

        $sortSql = $allowedSortColumns[$sortColumn] ?? 'pu.login';
        $sortDir = strtoupper(trim($sortDir)) === 'DESC' ? 'DESC' : 'ASC';
        $page = max(1, $page);
        $perPage = min(self::MAX_PER_PAGE, max(1, $perPage));
        $offset = ($page - 1) * $perPage;

        $where = ['pu.id != 1'];
        $params = [];

        $login = trim((string)($filters['login'] ?? ''));
        if ($login !== '') {
            if (strlen($login) > 255) {
                $login = substr($login, 0, 255);
            }
            $where[] = 'pu.login LIKE :login';
            $params[':login'] = '%' . $login . '%';
        }

        $status = trim((string)($filters['status'] ?? ''));
        if ($status === '0' || $status === '1') {
            $where[] = 'pu.status = :status';
            $params[':status'] = (int)$status;
        }

        $whereSql = implode(' AND ', $where);

        $sqlCount = "
            SELECT COUNT(0)
            FROM pp_users AS pu
            WHERE {$whereSql}
        ";

        $stmtCount = $this->db->query($sqlCount, $params);
        $countRows = $stmtCount ? $stmtCount->fetchAll() : [];
        $total = isset($countRows[0][0]) ? (int)$countRows[0][0] : 0;

        $sql = "
            SELECT
                pu.id,
                pu.login,
                pu.status
            FROM pp_users AS pu
            WHERE {$whereSql}
            ORDER BY {$sortSql} {$sortDir}, pu.id ASC
            LIMIT {$perPage} OFFSET {$offset}
        ";

        $stmt = $this->db->query($sql, $params);
        $items = $stmt ? $stmt->fetchAll() : [];

        return [
            'items' => is_array($items) ? $items : [],
            'total' => $total,
        ];
    }

    private function toSwitchValue($value): int
    {
        return ($value === 'on' || $value === 1 || $value === '1' || $value === true) ? 1 : 0;
    }
}
