<?php
namespace app\models;

use app\app;
use app\models\transactions;

class invoices
{
    public static function init()
    {
        $query = "CREATE TABLE IF NOT EXISTS invoices (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL REFERENCES users(id),
            order_id INTEGER REFERENCES orders(id),
            invoice TEXT NOT NULL,
            verify TEXT NOT NULL,
            amount_msats REAL NOT NULL,
            expiry_date DATETIME NOT NULL,
            settled BOOLEAN DEFAULT FALSE
        )";
        app::$db->exec($query);
    }

    public static function add($user_id, $order_id, $invoice, $verify, $amount_msats, $expiry_date)
    {
        $query = "INSERT INTO invoices (user_id, order_id, invoice, verify, amount_msats, expiry_date) VALUES (:user_id, :order_id, :invoice, :verify, :amount_msats, :expiry_date)";
        $stmt  = app::$db->prepare($query);
        $stmt->bindParam(':user_id', $user_id, \PDO::PARAM_INT);
        $stmt->bindParam(':order_id', $order_id, \PDO::PARAM_INT);
        $stmt->bindParam(':invoice', $invoice);
        $stmt->bindParam(':verify', $verify);
        $stmt->bindParam(':amount_msats', $amount_milisats);
        $stmt->bindParam(':expiry_date', $expiry_date);
        $stmt->execute();

        return app::$db->lastInsertId();
    }

    public static function getById($invoice_id)
    {
        $stmt = app::$db->prepare("SELECT * FROM invoices WHERE id = :invoice_id");
        $stmt->bindParam(':invoice_id', $invoice_id, \PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }

    public static function delete($invoice_id)
    {
        $deleteStmt = app::$db->prepare("DELETE FROM invoices WHERE id = :invoice_id");
        $deleteStmt->bindParam(':invoice_id', $invoice_id, \PDO::PARAM_INT);
        $deleteStmt->execute();
    }

    public static function markSettled($invoice_id)
    {
        $stmt = app::$db->prepare("UPDATE invoices SET settled = 1 WHERE id = :invoice_id");
        $stmt->bindParam(':invoice_id', $invoice_id, \PDO::PARAM_INT);
        $stmt->execute();
    }

    public static function checkAll()
    {
        $stmt = app::$db->prepare("SELECT id FROM invoices WHERE settled = 0");
        $stmt->execute();
        $invoiceIds = $stmt->fetchAll(\PDO::FETCH_COLUMN);

        foreach ($invoiceIds as $invoiceId) {
            self::check($invoiceId);
        }
    }

    public static function check($invoice_id)
    {
        $invoice = self::get_byId($invoice_id);
        // Use LUD-21 Payment Verify
        $responseData = json_decode(file_get_contents($invoice['verify']), true);
        if ($responseData['settled']) {
            if ($invoice['order_id']) {
                orders::updateStatus($invoice['order_id'], "PROCESSING");
                self::markSettled($invoice_id);
            } else {
                transactions::add($invoice['user_id'], 'DEPOSIT', 0, $invoice['amount_msats'] / 1000);
            }
        } else {
            // Check if more than 24 hours past expiry
            $expiryDate  = new \DateTime($invoice['expiry_date']);
            $currentDate = new \DateTime();
            $interval    = $expiryDate->diff($currentDate);
            if ($interval->days >= 1) {
                self::delete($invoice_id);
            }
        }
    }
}
