<?php

declare(strict_types=1);

class Logger
{
    private PDO $pdo;

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

    public function log(
        string $job,
        string $status,
        string $message,
        float $started
    ): void {

        $duration = (int)((microtime(true) - $started) * 1000);

        $st = $this->pdo->prepare("
            INSERT INTO cron_logs
            (
                job_name,
                status,
                message,
                started_at,
                finished_at,
                duration_ms
            )
            VALUES
            (
                ?,
                ?,
                ?,
                FROM_UNIXTIME(?),
                NOW(),
                ?
            )
        ");

        $st->execute([
            $job,
            $status,
            $message,
            (int)$started,
            $duration
        ]);
    }

    public function error(Throwable $e): void
    {
        $folder = dirname(__DIR__) . "/logs";

        if (!is_dir($folder)) {
            mkdir($folder,0777,true);
        }

        $text =
            "[".date('Y-m-d H:i:s')."] ".
            $e->getMessage().
            PHP_EOL.
            $e->getTraceAsString().
            PHP_EOL.
            str_repeat("-",60).
            PHP_EOL;

        file_put_contents(
            $folder."/cron.log",
            $text,
            FILE_APPEND
        );
    }
}