<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

class ApiHelper
{
    public static function success($message = 'Success', $data = [], $statusCode = 200)
    {
        return response()->json([
            'status' => true,
            'message' => $message,
            'data' => $data
        ], $statusCode);
    }

    public static function error($errorCode = '', $message = 'Something went wrong', $exception = null, $statusCode = 500)
    {

        if ($exception) {

            Log::error($errorCode, [
                'message' => $exception->getMessage(),
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
            ]);
        }

        return response()->json([
            'status' => false,
            'message' => $message
        ], $statusCode);
    }

    public static function validationError($message = 'Validation error', $errors = [], $statusCode = 422)
    {

        return response()->json([
            'status' => false,
            'message' => $message,
            'errors' => $errors
        ], $statusCode);
    }

    public static function unauthorized($message = 'Unauthorized access', $statusCode = 401)
    {
        return response()->json([
            'status' => false,
            'message' => $message
        ], $statusCode);
    }

    public static function notFound($message = 'Resource not found', $statusCode = 404)
    {
        return response()->json([
            'status' => false,
            'message' => $message
        ], $statusCode);
    }

    public static function forbidden($message = 'Forbidden access', $statusCode = 403)
    {
        return response()->json([
            'status' => false,
            'message' => $message
        ], $statusCode);
    }

    public static function formatDateTime($dateTime)
    {
        if (!$dateTime) {
            return null;
        }

        return Carbon::parse($dateTime)
            ->format('d M Y h:i A');
    }

    public static function formatDate($date)
    {
        if (!$date) {
            return null;
        }

        return Carbon::parse($date)
            ->format('d M Y');
    }

    public static function formatTime($time)
    {
        if (!$time) {
            return null;
        }

        return Carbon::parse($time)
            ->format('h:i A');
    }

    public static function checkRoleAccess($allowedRoles = [])
    {
        $user = Auth::user();

        if (!$user) {

            return self::unauthorized(
                'Unauthorized access'
            );
        }

        if (!in_array($user->role_id, $allowedRoles)) {

            return self::forbidden(
                'Forbidden access'
            );
        }

        return true;
    }
}
