<?php

namespace App\Http\Controllers;

use App\NoHome;
use App\User;
use Carbon\Carbon;
use OneSignal;
use Image;
use Storage;
use App\Models\CurrentContracts;
use App\Models\FinishedContracts;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Grimzy\LaravelMysqlSpatial\Types\Point;
use Illuminate\Support\Facades\File;

class NoHomeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\NoHome  $noHome
     * @return \Illuminate\Http\Response
     */
    public function show(NoHome $noHome)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\NoHome  $noHome
     * @return \Illuminate\Http\Response
     */
    public function edit(NoHome $noHome)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\NoHome  $noHome
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, NoHome $noHome)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\NoHome  $noHome
     * @return \Illuminate\Http\Response
     */
    public function destroy(NoHome $noHome)
    {
        //
    }

    public function test(Request $request)
    {

      $rules = [
        'contract_id' => 'required|numeric',
        'description' => 'required|string',
        'lat' => 'numeric|nullable',
        'lng' => 'numeric|nullable',
        //'house_photo' => 'image|mimes:jpeg,jpg,png|max:2048',
      ];

      $validator = Validator::make($request->all(), $rules);
      if ($validator->fails()) {
        return response()->json([
            'message' => 'Por favor corrija'
        ]);
      } else {
        $user = Auth::user();
        $disk = Storage::disk('gcs');

        if ($request->file('house_photo')) {
          $name = Carbon::now();
          $filename = $name . '.jpg';
          $disk->putFileAs('img/users/'.  $user->id . '/', $request->file('house_photo'), $filename, 'public');
        }
        return response()->json([
            //'message' => 'Por favor espere a los 10 minutos de tolerancia de la hora acordada'
            'contract_id' => $request->contract_id,
            'lat' => $request->lat,
            'lng' => $request->lng,
        ]);
      }
    }

    public function nohomecheck(Request $request){
      $user = Auth::user();
      $contract = CurrentContracts::where('supplier_id', $user->suppliers->id)->whereBetween('appointment', [Carbon::now()->subMinutes(15), Carbon::now()->addMinutes(10)])->first();

      if ($contract) {
        $client = User::where('id', $contract->user_id)->first();
        if (Carbon::now()->diffInMinutes($contract->appointment, false) < 10) {
          return response()->json($contract);
        } else {
          OneSignal::sendNotificationUsingTags(
               "El proveedor para el servicio en " . $contract->address . " ha llegado. Dírigeta a la sección de contratos confirmados para más detalles",
               array(
                   ["field" => "tag", "key" => "iChamba_ID", "relation" => "=", "value" => $client->id]
               ),
               $url = null,
               $data = null,
               $buttons = null,
               $schedule = null,
               $headings = $client->name + ", tu proveedor del servicio ha llegado"
          );
          return response()->json([
              //'message' => 'Por favor espere a los 10 minutos de tolerancia de la hora acordada'
              'message' => 'wait'
          ]);
        }
      } else {
        return response()->json([
            //'message' => 'No hay contratos citados a esta hora'
            'message' => 'no-contract'
        ]);
      }
    }


    public function nohomeconfirm(Request $request) {

      $rules = [
        'contract_id' => 'required|numeric',
        'description' => 'required|string',
        'lat' => 'numeric|nullable',
        'lng' => 'numeric|nullable',
        //'house_photo' => 'image|mimes:jpeg,jpg,png|max:2048',
      ];

      $validator = Validator::make($request->all(), $rules);
      if ($validator->fails()) {
        return redirect()->back()->withInput($request->all())->withErrors($validator);
      } else {

        $user = Auth::user();
        $disk = Storage::disk('gcs');
        $ccontract = CurrentContracts::where('id', $request->contract_id)->first();
        $client = User::where('id', $ccontract->user_id)->first();

        if ($user->suppliers->id == $ccontract->supplier_id) {
          if (Carbon::now()->diffInMinutes($ccontract->appointment, false) >= 11) {
            if ($request->lat != null && $request->lng != null) {
              $geometry = new Point($request->lat, $request->lng);
            }

            $fcontract = new FinishedContracts();
            $fcontract->user_id = $ccontract->user_id;
            $fcontract->supplier_id = $ccontract->supplier_id;
            $fcontract->category_id = $ccontract->category_id;
            $fcontract->address = $ccontract->address;
            $fcontract->location = $ccontract->location;
            $fcontract->int_number = $ccontract->int_number;
            $fcontract->references = $ccontract->references;
            $fcontract->appointment = $ccontract->appointment;
            $fcontract->amount = $ccontract->amount;
            $fcontract->details = $ccontract->details;
            $fcontract->IVA = $ccontract->IVA;
            $fcontract->ISR = $ccontract->ISR;
            $fcontract->ichamba_fee = $ccontract->ichamba_fee;
            $fcontract->revenue = $ccontract->revenue;
            $fcontract->details = $ccontract->details;
            $fcontract->en = $ccontract->en;
            $fcontract->transaction_id = $ccontract->transaction_id;
            $fcontract->status_id = 5;
            $fcontract->save();

            $nohome = new NoHome();
            $nohome->contract_id = $fcontract->id;
            if ($geometry != null) {
              $nohome->location = $geometry;
            }

            if ($request->file('house_photo')) {
              $disk = Storage::disk('gcs');

              $name = Carbon::now();
              $filename = $name . '.jpg';
              $disk->putFileAs('img/users/'.  $user->id . '/', $request->file('house_photo'), $filename, 'public');
              $nohome->house_photo = $disk->url('img/users/'.  $user->id . '/' . $filename);
            }
            $nohome->house_description = $request->description;

            $nohome->save();


            return response()->json([
                'message' => 'Ausencia registrada con éxito, nos comunicaremos con usted por correo electrónico en caso de alguna circunstancia'
            ]);
          } else {
            OneSignal::sendNotificationUsingTags(
                 "El proveedor para el servicio en " . $ccontract->address . " ha llegado. Dírigeta a la sección de contratos confirmados para más detalles",
                 array(
                     ["field" => "tag", "key" => "iChamba_ID", "relation" => "=", "value" => $client->id]
                 ),
                 $url = null,
                 $data = null,
                 $buttons = null,
                 $schedule = null,
                 $headings = $client->name . ", tu proveedor del servicio ha llegado"
            );
            return response()->json([
                'order' => 'wait',
                'message' => 'Por favor espere a los 10 minutos de tolerancia de la hora acordada'
            ]);
          }
        }
      }
    }
}
