<?php

namespace App\Models;

use PDO;
use Config\Database;

class PendingUser extends BaseModel {
    protected static $table = 'pending_users';

    public $id;
    public $email;
    public $token;
    public $verified;
    public $created_at;
    public $token_expires_at;

    public function __construct($data = []) {

        parent::__construct($data);
        $this->verified = $data['verified'] ?? 0;
    }

    public function save()
    {
        $db = Database::getConnection();

        if ($this->id) {
            $query = "UPDATE pending_users SET email = :email, token = :token, verified = :verified, token_expires_at = :token_expires_at WHERE id = :id";
            $stmt = $db->prepare($query);
            $stmt->execute([
                ':id' => $this->id,
                ':email' => $this->email,
                ':token' => $this->token,
                ':verified' => $this->verified,
                ':token_expires_at' => $this->token_expires_at,
            ]);
        } else {
            $query = "INSERT INTO pending_users (email, token, verified, token_expires_at) VALUES (:email, :token, :verified, :token_expires_at)";
            $stmt = $db->prepare($query);
            $stmt->execute([
                ':email' => $this->email,
                ':token' => $this->token,
                ':verified' => $this->verified,
                ':token_expires_at' => $this->token_expires_at,
            ]);
            $this->id = $db->lastInsertId();
        }
    }
}