<?php

namespace App\Http\Controllers\Dashboard;
use Illuminate\Support\Facades\Validator;
use \App\Services\ApiService;
use App\Http\Controllers\Controller;
use App\Models\AvailableApp;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

class ApplicationController extends Controller
{
    public $uuid;
    public $api_base_url;
    public  $perPageOptions;
    public function __construct(protected ApiService $api_query ,$uuid = null)
    {
        $this->api_query = $api_query;
        $this->api_base_url = config('services.api.base_url');
        $this->uuid = $uuid ?? '';
       
    }
    public function viewFormApplication () 
    {
        return view('dashboard.forms.form-application')->with([
            'uuid' =>$this->uuid
        ]);
    }

    public function storeApplication(Request $request)
{
    try {

        $logo_name = null;
        $file_name = null;

        if ($request->hasFile('app_logo')) {
                $logo_name = Str::uuid() . '.' . $request->app_logo->getClientOriginalExtension();
                $request->app_logo->storeAs('img', $logo_name, 'public');
        }

    if ($request->hasFile('app_address_link_to_download')) {
        $file_name = Str::uuid() . '.' . $request->app_address_link_to_download->getClientOriginalExtension();
        $request->app_address_link_to_download->storeAs('setups', $file_name, 'public');
    }    

        $response = Http::withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . session('access_token')])->post("{$this->api_base_url}/applications", [
            'app_name' => $request->app_name,
            'app_version' => $request->app_version,
            'app_size' => $request->app_size,
            'app_description' => $request->app_description,
            'app_format_type' => $request->app_format_type,
            'app_duration' => $request->app_duration,
            'app_price' => $request->app_price,
            'app_logo' => $logo_name,
            'app_address_link_to_download' => $file_name,
        ]);

        if ($response->status() === 422) {
            return response()->json([
                'success' => false,
                'errors' => $response->json('errors'),
            ], 422);
        }

        if ($response->failed()) {
            return response()->json([
                'success' => false,
                'title' => 'Erro',
                'text' => $response->json('message') ?? 'Erro na API',
            ], 500);
        }

        return response()->json([
            'success' => true,
            'title' => 'Sucesso',
            'text' => 'Aplicação cadastrada com sucesso',
        ], 200);

    } catch (\Throwable $th) {
        return response()->json([
            'success' => false,
            'title' => 'Erro',
            'text' => 'Erro interno no servidor',
        ], 500);
    }
}



    public function showApps (Request $request) 
    {
        $uploaded_apps = $this->api_query->getEnterpriseAvailableApps($request);

        return response()->json([
            'data' => $uploaded_apps->items(),
            'meta' => [
                'current_page' => $uploaded_apps->currentPage(),
                'total' => $uploaded_apps->total(),
                'per_page' => $uploaded_apps->perPage(),
                'last_page' => $uploaded_apps->lastPage(),
                'from'  => $uploaded_apps->firstItem(),
                'to' => $uploaded_apps->lastItem(),
            ],
            'links' => [
                'first' => $uploaded_apps->url(1),
                'last'  => $uploaded_apps->url($uploaded_apps->lastPage()),
                'prev'  => $uploaded_apps->previousPageUrl(),
                'next'  => $uploaded_apps->nextPageUrl(),
            ]
        ]); 
    }
}
