<?php

namespace App\Models;

use PDO;
use Config\Database;

class PasswordReset extends BaseModel
{
    protected static $table = 'password_resets';

    public $id;
    public $email;
    public $token;
    public $created_at;
    public $expires_at;
    public $used;
    public $deleted_at;

    public function __construct($data = [])
    {
        parent::__construct($data);
        $this->used = $data['used'] ?? 0;
    }

    public function save()
    {
        $db = Database::getConnection();
        if ($this->id) {
            $query = "UPDATE password_resets 
                    SET email = :email, token = :token, created_at = :created_at, expires_at = :expires_at, used = :used 
                    WHERE id = :id";
            $stmt = $db->prepare($query);
            $stmt->execute([
                ':id' => $this->id,
                ':email' => $this->email,
                ':token' => $this->token,
                ':created_at' => $this->created_at,
                ':expires_at' => $this->expires_at,
                ':used' => $this->used,
            ]);
        } else {
            $query = "INSERT INTO password_resets (email, token, created_at, expires_at, used) 
                    VALUES (:email, :token, :created_at, :expires_at, :used)";
            $stmt = $db->prepare($query);
            $stmt->execute([
                ':email' => $this->email,
                ':token' => $this->token,
                ':created_at' => $this->created_at,
                ':expires_at' => $this->expires_at,
                ':used' => $this->used,
            ]);
            $this->id = $db->lastInsertId();
        }
    }

}
