<?php

namespace App\Http\Controllers;

use App\Modules\Bookings\Task;
use App\Modules\Clients\Client;
use App\Modules\Clients\Customer;
use App\Modules\Invoices\Invoice;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;

class HomeController extends BaseController
{
    /**
     *	The layout that should be used for responses.
     */
    protected $layout = 'layouts.master';

    /*
    |--------------------------------------------------------------------------
    | Default Home Controller
    |--------------------------------------------------------------------------
    |
    | You may wish to use controllers instead of, or in addition to, Closure
    | based routes. That's great! Here is an example controller method to
    | get you started. To route to this controller, just add the route:
    |
    |	Route::get('/', 'HomeController@showWelcome');
    |
    */

    public function getIndex()
    {
        return Redirect::to('dashboard')->withInput();
    }

    public function getDial($number)
    {
        // Get the user extension, and make a curl call.
        $extension = Auth::user()->extension;

        if (! $extension) {
            return Response::json(['error' => 'No extension assigned to your account.'], 400);
        }

        if (! $number) {
            return Response::json(['error' => 'Please provide a valid phone number'], 400);
        }

        $clicktocallServer = env('CLICKTOCALL_SERVER', '');
        if ($clicktocallServer) {
            file_get_contents('http://'.$clicktocallServer.'/clicktocall/call.php?num='.urlencode($number).'&ext='.urlencode($extension));
        }

        return Response::json('OK');
    }

    /**
     * Performs an overall search.
     *
     * @return JSON
     */
    public function search()
    {
        // Check to see if we have a search term
        if (! request('q')) {
            return [];
        }

        // Use DB facade for direct queries to avoid model relationships
        $searchTerm = request('q');
        
        // Check to see the items to search for
        $results = [
            'clients'    => Client::search($searchTerm)->take(5)->get(),
            'customers'  => Customer::search($searchTerm)->take(7)->get(),
            'repairs'    => Task::search($searchTerm, 'repair')->take(7)->get(),
            'onsite'     => Task::search($searchTerm, 'onsite')->take(7)->get(),
            'support'    => Task::search($searchTerm, 'support')->take(7)->get(),
            'sale_leads' => Task::search($searchTerm, 'sale_lead')->take(7)->get(),
            'invoices'   => Invoice::search($searchTerm)->take(5)->get(),
            'QA'         => Task::search($searchTerm, 'qa')->take(7)->get(),
        ];

        // Load clients for tasks - but only if we have results
        foreach ([$results['repairs'], $results['onsite'], $results['support'], $results['invoices'], $results['sale_leads']] as $array) {
            if ($array->count() > 0) {
                foreach ($array as $value) {
                    $value->client = $value->client;
                }
            }
        }

        return $results;
    }

    public function switchUser($user_id)
    {
        return Redirect::to('dashboard');
        /*
        $user = User::find($user_id);

        if ( ! $user)
            return Redirect::to('dashboard');

        // Store the original user
        if (! Session::has('original_user_id'))
        {
            Session::put('original_user_id', Auth::user()->id);
            Session::put('switch_time', time());
        }

        Auth::loginUsingId($user->id);
        return Redirect::to('dashboard');
        */
    }

    public function fixTasksMissingSite()
    {
        $tasks = Task::where('client_type', 'client')->whereNull('site_id')->get();

        foreach ($tasks as $task) {
            $client = $task->client;
            $site = $task->client->sites[0];
            $user = $site->users[0];

            $task->site_id = $site->id;
            $task->site_user_id = $user->id;
            if ($task->save()) {
                echo 'Task '.$task->id.' saved succesfully<br>';
            } else {
                echo '<div class="alert alert-danger">Failed to save task '.$task->id.' with errors: '.$task->errors->first().'</div>';
            }
        }

        if (count($tasks) == 0) {
            echo '<div class="alert alert-info">No tasks were found</div>';
        }
    }
}
