<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Response;
use ScssPhp\ScssPhp\Compiler;
use Analytics;
use Spatie\Analytics\Period;
use Illuminate\Support\Facades\File;
use App\User;
use App\Order;
use Curl;
use Image;

class CMSController extends Controller
{
    public function __construct()
    {
        $this->middleware('web');
    }

    public function scss($filename = 'style')
    {
        $scss = new Compiler();
        $scss->setImportPaths(resource_path('sass'));

        try {
            $output = $scss->compile(file_get_contents(resource_path('sass/'.$filename.'.scss')));
        } catch(\Exception $e) {
            $output = '';
        }
        $response = Response::make($output);
        $response->header('Content-Type', 'text/css');
        return $response;
    }


    public function thumbnail($url, $width = 640, $height = 360) {
        $img = Image::make($url);
        $img->fit($width, $height);
        $img->fit(800, 600, function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize();
        });
        echo $img->response('jpg');
    }

    public function flush()
    {
        Artisan::call('cache:clear');
        Artisan::call('route:clear');
        Artisan::call('config:clear');
        Artisan::call('view:clear');

        return 'Caché limpio';
    }

    public function symlink()
    {
        try {
            $shortcut = 'public/uploads';
            if(file_exists($shortcut)) unlink($shortcut);
            $target = '../storage/app/public';
            symlink($target, $shortcut);
            return redirect(url('/'));
        } catch(\Exception $e) {
            return $e->getMessage();
        }
    }

    public function preview($view)
    {
        $user = User::inRandomOrder()->first();
        $order = Order::inRandomOrder()->first();
        $input = [
            'Nombre' => 'first_name',
            'Apellido' => 'last_name',
            'Email' => 'email_address',
            'Teléfono' => 'phone_number',
            'Mensaje' => 'message'
        ];

        return view('emails.'.$view, [
            'user' => $user,
            'order' => $order,
            'input' => $input
        ]);
    }

    public function analytics()
    {
        try {
            $data = Analytics::performQuery(
                Period::days(30),
                'ga:sessions, ga:users, ga:pageviews',
                [
                    'dimensions' => 'ga:date'
                ]
            );

            file_put_contents(storage_path('/app/analytics/data.json'), json_encode($data));
        } catch(\Exception $e) {
            return $e->getMessage();
        }
    }

    public function descargas($filename)
    {
        $path = storage_path('app/public/files/' . $filename);

        if (!File::exists($path)) {
            abort(404);
        }

        $file = File::get($path);
        $type = File::mimeType($path);

        $response = Response::make($file, 200);
        $response->header("Content-Type", $type);

        return $response;
    }

    public function cron()
    {
        $data = [
            'token' => env('ENDPOINT_TOKEN'),
            'codigoPais' => 'PY',
        ];
        $output = [];

        $departamentos = Curl::to(env('ENDPOINT_URL').'/tacpy/resources/departamentos')->withData($data)->asJson()->post();

        if($departamentos && $departamentos->respuestaDepartamentosDetalles) {
            foreach($departamentos->respuestaDepartamentosDetalles as $item) {
                $data = [
                    'token' => env('ENDPOINT_TOKEN'),
                    'codigoPais' => 'PY',
                    'codigoDepartamento' => $item->codigoDepartamento,
                ];

                $ciudades = Curl::to(env('ENDPOINT_URL') . '/tacpy/resources/ciudades')->withData($data)->asJson()->post();

                if ($ciudades && $ciudades->respuestaCiudadesDetalles) {
                    foreach ($ciudades->respuestaCiudadesDetalles as $item) {
                        $output[] = $item->descripcionCiudad;
                    }
                }
            }
        }

        $output = array_unique($output);
        sort($output);

        if($output) file_put_contents(storage_path('app/ciudades.json'), json_encode($output));
    }
}
