<?php

namespace App\Repositories\Core;

use Carbon\Carbon;

class HelperDate
{
    public static function toLocaleFormat($date)
    {
        if (! $date) {
            return $date;
        }
        $locale = session('locale');
        switch ($locale) {
            case 'fr':
                $format = 'd/m/Y';
                break;
            case 'en':
                $format = 'Y-m-d';
                break;
            default:
                $format = 'Y-m-d';
        }

        return Carbon::parse($date)->format($format);
    }

    public static function fromLocale($d)
    {
        return self::frenchDate($d);
    }

    public static function toLocale($d)
    {
        return self::toFrenchDate($d);
    }

    public static function frenchDate($d)
    {
        if (! $d) {
            return null;
        }

        return Carbon::createFromFormat('d/m/Y', $d)->format('Y-m-d');
    }

    public static function frenchDates($data, $fields)
    {
        foreach ($fields as $field) {
            if (isset($data[$field]) && $data[$field]) {
                $data[$field] = static::frenchDate($data[$field]);
            }
        }

        return $data;
    }

    public static function toFrenchDate($d)
    {
        if ($d && $d !== '0000-00-00') {
            return Carbon::createFromFormat('Y-m-d', $d)->format('d/m/Y');
        }

        return $d;
    }

    public static function toFrenchDates($data, $fields)
    {
        foreach ($fields as $field) {
            if (isset($data[$field]) && $data[$field]) {
                $data[$field] = static::toFrenchDate($data[$field]);
            }
        }

        return $data;
    }
}
