<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\TicketService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;

class DashboardController extends Controller
{

    protected $TicketService;

    public function __construct(TicketService $TicketService)
    {
        $this->TicketService = $TicketService;
    }

    public function index()
    {
        $result = $this->TicketService->getChamadosComDetalhes();

        if (isset($result['error'])) {
            return redirect()->route('login')->with('error', $result['error']);
        }

        $chamadosDetalhados = $result['data'];
        $message = $result['message'];
        $chamadosDetalhadosComTempo = [];

        foreach ($chamadosDetalhados as $chamado) {
            $solId = $chamado['chamadoId'];

            $tempoGasto = DB::connection('sqlsrv')
                ->table('Solicitacao')
                ->where('SolID', $solId)
                ->value('TempoGastoTotal');

            if ($tempoGasto) {
                // Converte minutos para horas e minutos
                $hours = floor($tempoGasto / 60); // Calcula as horas
                $minutes = $tempoGasto % 60; // Calcula os minutos restantes

                // Formata a string no formato hh:mm
                $tempoGastoFormatted = sprintf('%02d:%02d', $hours, $minutes);
            } else {
                $tempoGastoFormatted = '00:00';
            }

            $chamadosDetalhadosComTempo[] = array_merge($chamado, ['tempoGasto' => $tempoGastoFormatted ?? '00:00']);
        }

        return view('dashboard', compact('chamadosDetalhadosComTempo', 'message'));
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'tramiteId' => 'required|integer',
            'chamadoId' => 'required|integer',
            'status' => 'required|string',
            'origem' => 'required|string',
            'motivoId' => 'required|integer',
            'atividadeId' => 'required|integer',
            'data' => 'required|date',
            'horaInicio' => 'required|date',
            'horaFim' => 'required|date',
            'descricao' => 'required|string',
            'tramiteSolucao' => 'required|boolean',
        ]);

        $accessToken = Session::get('access_token');

        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $accessToken,
        ])->post('https://intersolid.ellevocloud.com/api/mob/tramite', $validatedData);

        return response()->json($response->json(), $response->status());
    }
}