<?php

namespace App\Http\Controllers;


use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
use App\Models\Application;
use App\Models\ConfigData;
use GuzzleHttp\Client;



class ApplicationController extends Controller
{
    public function save($appname) {

        //tendría que venir los datos para llamar a la api
        //hacemos la llamada a google
        //guardamos los datos

        $app = new Application;
        $app->name = $appname;
        $app->save();


        return response()->json($app);
    }


    public function remove($appname) {
        $app=CacheData::find($appname);
        return response()->json($app);
    }

    public function update($appname) {
       
        $config = ConfigData::where('name',$appname)->get();
        $config = $config[0];

        $app = Application::where('name',$appname)->get();
        $app=$app[0];
        

        $key = $config->key;
        $resPorPagina = $config->res_por_pagina;
        $paginas = $config->paginas;
        $idCanal = $app->canal_id;
        $url = "https://www.googleapis.com/youtube/v3/search?key=" . $key . "&channelId=" . $idCanal . "&part=snippet,id&order=date&type=video&maxResults=" . $resPorPagina;
        $response = Http::get($url);
        $results = json_decode($response);

        $app->data = json_encode($results);
        $app->save();

        return $app;
    }


    public function getAll() {
        $app = Application::all();

        return response()->json($app);
    }

    public function get($appname) {
        
        $app = Application::where('name',$appname)->get();

        return $app[0];
    }

    public function getData($appname) {
        
        $app = Application::where('name',$appname)->get();

        return $app[0]->data;
    }

   
}