<?php

namespace App\Traits;

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

trait QueryTrait
{
    use UserLoggedTrait;

    protected function makeFieldHidden($query, $fields)
    {
        $relationsToHideId = [
            'site',
            'role',
            'collaborator',
            'city',
            'zone',
            'promoter',
            'executive',
            'client_status',
            'endorsement_status',
            'user_creator',
            'user_updater'
        ];

        foreach ($fields as $field) {
            if (in_array($field, $relationsToHideId)) {
                $query->each(function ($item) use ($field) {
                    if ($item->{$field}) {
                        $item->{$field}->makeHidden(['id']);
                    }
                });
            } else {
                $query->makeHidden([$field]);
            }
        }

        return $query;
    }

    protected function responseJson($responseMessage = null, $responseData = null, $responseCode = 200)
    {
        switch ($responseCode) {
            case 200:
            case 201:
                return response()->json($responseData ?? true, 200);
            case 500:
            case 501:
                return response()->json($responseMessage, 501);
            default:
                return response()->json('WARNING.UNDEFINED-MESSAGE', 400);
        }
    }

    protected function generateLog($logChannel, Exception $exception)
    {
        Log::channel($logChannel)->info('Exception', [
            'file' => $exception->getFile(),
            'exception' => $exception->getMessage(),
            'line' => $exception->getLine(),
            'timestamp' => Carbon::now()->format('d-m-Y h:i:s')
        ]);
    }

    protected function readJson($model, $id)
    {
        $logFilePath = storage_path('logs/models/' . $model . '_changelog.log');

        if (!is_readable($logFilePath)) {
            throw new Exception("The log file path is not readable or does not exist: " . $logFilePath);
        }

        $logEntries = file($logFilePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $filteredLogs = [];

        foreach ($logEntries as $entry) {
            preg_match('/\{.*\}/', $entry, $matches);

            if (!empty($matches)) {
                $logData = json_decode($matches[0], true);

                if (isset($logData['id']) && $logData['id'] == $id) {
                    $filteredLogs[] = $logData;
                }
            }
        }

        return $filteredLogs;
    }
}
