<?php

namespace Ignite\Core\Helpers;

use Carbon\Carbon;

class DateTime
{
    /**
     * @var Carbon|string|int
     */
    private $value;

    /**
     * DateTime constructor.
     *
     * @param Carbon|string|int $value
     */
    public function __construct($value)
    {
        $this->value = $value;
    }

    /**
     * Reformat a Date with a default value
     *
     * @param  string $format
     * @param  string $default
     * @return false|string
     */
    public function format($format = 'Y-m-d H:i:s', $default = '')
    {
        if (is_string($this->value)) {
            $this->value = trim($this->value);
        }

        if (empty($this->value)) {
            return $default;
        }

        if (! preg_match('/\s([0-9]{2}):([0-9]{2}):([0-9]{2})/', $this->value)) {
            $this->value = $this->value . ' 00:00:00';
        }

        try {
            $date = Carbon::parse($this->value);
        } catch (\Exception $e) {
            return $default;
        }

        return $date->format($format);
    }
}
