<?php
namespace App;

use PDO;

class User {
    public static function create(string $name, string $email, string $password): int {
        $db = get_db();
        $hash = password_hash($password, PASSWORD_BCRYPT);
        $stmt = $db->prepare('INSERT INTO users (name, email, password_hash) VALUES (:name, :email, :hash)');
        $stmt->execute([
            ':name' => $name,
            ':email' => strtolower($email),
            ':hash' => $hash,
        ]);
        return (int)$db->lastInsertId();
    }

    public static function findByEmail(string $email): ?array {
        $db = get_db();
        $stmt = $db->prepare('SELECT * FROM users WHERE email = :email LIMIT 1');
        $stmt->execute([':email' => strtolower($email)]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }

    public static function find(int $id): ?array {
        $db = get_db();
        $stmt = $db->prepare('SELECT * FROM users WHERE id = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }

    public static function verifyCredentials(string $email, string $password): ?array {
        $user = self::findByEmail($email);
        if (!$user) {
            return null;
        }
        if (!password_verify($password, (string)$user['password_hash'])) {
            return null;
        }
        return $user;
    }

    public static function hasPaidOrder(int $userId): bool {
        $db = get_db();
        $stmt = $db->prepare("SELECT 1 FROM orders WHERE user_id = :uid AND status = 'paid' LIMIT 1");
        $stmt->execute([':uid' => $userId]);
        return (bool)$stmt->fetchColumn();
    }

    public static function accountAccessStatus(array $user): array {
        $createdAtRaw = (string)($user['created_at'] ?? '');
        $createdAtTs = strtotime($createdAtRaw);
        if ($createdAtTs === false) {
            $createdAtTs = time();
        }

        $trialEndsAtTs = strtotime('+4 days', $createdAtTs);
        $isPaid = self::hasPaidOrder((int)$user['id']);
        $isTrialActive = time() <= $trialEndsAtTs;
        $isLocked = (!$isPaid && !$isTrialActive);
        $secondsLeft = max(0, $trialEndsAtTs - time());
        $daysLeft = (int)ceil($secondsLeft / 86400);

        return [
            'is_paid' => $isPaid,
            'is_trial_active' => $isTrialActive,
            'is_locked' => $isLocked,
            'trial_ends_at' => date('Y-m-d H:i:s', $trialEndsAtTs),
            'trial_days_left' => $daysLeft,
        ];
    }
}
