<?php

use Illuminate\Support\Str;

if (! function_exists('validateDate')) {
    /**
     * Checks to see if a date is valid.
     *
     * @param  string $date
     * @param  string $format
     *
     * @return bool
     */
    function validateDate($date, $format = 'Y-m-d H:i:s')
    {
        $d = DateTime::createFromFormat($format, $date);

        return $d && $d->format($format) == $date;
    }
}

if (! function_exists('getAuthUserId')) {
    /**
     * Retrieves the logged in user id, it automatically checks with
     * the resource server or the local Auth library.
     *
     * @return int
     */
    function getAuthUserId()
    {
        return (Auth::guest()) ? getOauthUserId() : Auth::id();
    }
}

if (! function_exists('getOauthUserId')) {
    /**
     * Retrieves the logged in user id from Laravel Passport.
     *
     * @return int|null
     */
    function getOauthUserId()
    {
        try {
            // Check if we have a Passport token
            $request = request();
            if ($request->bearerToken()) {
                $user = Auth::guard('api')->user();
                return $user ? $user->id : null;
            }
            
            // Fallback to authenticated user
            return Auth::id();
        }
        catch (Exception $e) {
            return null;
        }
    }
}

if (! function_exists('dhm_to_seconds')) {
    /**
     * Converts the given days / hours / minutes string to
     * seconds.
     *
     * @param  string $formatedTime
     *         eg: 5d 3h 2m
     *
     * @return integer
     */
    function dhm_to_seconds($formatedTime)
    {
        // CRITICAL FIX: Handle null/empty values that were causing database issues
        if (empty($formatedTime) || trim($formatedTime) === '') {
            return 0;
        }

        $splited = explode(' ', $formatedTime);
        $seconds = 0;

        for ($i = 0; $i < count($splited); $i++) {
            // Skip empty segments
            if (empty($splited[$i]) || trim($splited[$i]) === '') {
                continue;
            }

            $num = 0;
            if (strrpos($splited[$i], 'd') !== false) {
                $num = intval(str_replace('d', '', $splited[$i]));
                $num = $num * 86400; // seconds per day
            }
            elseif (strrpos($splited[$i], 'h') !== false) {
                $num = intval(str_replace('h', '', $splited[$i]));
                $num = $num * 3600; // seconds per hour
            }
            elseif (strrpos($splited[$i], 'm') !== false) {
                $num = intval(str_replace('m', '', $splited[$i]));
                $num = $num * 60; // seconds per minute
            }
            else {
                // CRITICAL FIX: Handle plain numbers without units (assume minutes)
                $plainNumber = intval($splited[$i]);
                if ($plainNumber > 0) {
                    $num = $plainNumber * 60; // Treat as minutes
                }
            }

            $seconds = $seconds + $num;
        }

        return $seconds;
    }
}

if (! function_exists('str_random')) {
    /**
     * Generate a random string of the given length.
     *
     * @param  int  $length
     * @return string
     */
    function str_random($length = 16)
    {
        return Str::random($length);
    }
}

if (! function_exists('factory')) {
    /**
     * Legacy factory() helper for Laravel 8+ compatibility.
     *
     * @param  string  $class
     * @param  int|null  $count
     * @return \Illuminate\Database\Eloquent\FactoryBuilder
     */
    function factory($class, $count = null)
    {
        $factory = $class::factory();
        return is_null($count) ? $factory : $factory->count($count);
    }
}
