<?php

namespace App\Modules\Clients\controllers;

use Illuminate\Support\Facades\View;
use Illuminate\Http\Request;

use Postcode;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\BaseController;
use App\Models\Contract;
use App\Models\Sla;
use App\Modules\Clients\Client;
use App\Modules\Clients\Customer;

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

    /**
     *	Returns the index page.
     */
    public function getIndex()
    {
        // Load all contracts
        $contracts = Contract::all();
        $_contracts = ['' => null];

        foreach ($contracts as $contract) {
            $_contracts[$contract['id']] = $contract['name'];
        }

        // Load all SLAs
        $sla = Sla::all();
        $_sla = ['' => null];

        foreach ($sla as $s) {
            $_sla[$s['id']] = $s['name'];
        }

        $data = [
            'contracts'    => $_contracts,
            'sla_dropdown' => $_sla,
            'sla'          => $sla->toArray(),
        ];

        $this->layout->content = View::make('clients::index', $data);
    }
    
     /**
     *	Returns the subscriptions page.
     */
    public function subscriptions()
    {
        return View::make('clients::subscriptions');
    }

    public function postPostcode()
    {
        if (request()->has('postcode')) {
            $postcode = Postcode::lookup(request()->get('postcode'));
        } else {
            return response()->json(['success' => false, 'errors' => 'Please provide a postcode'], 400);
        }

        return response()->json(['success' => true, 'postcode' => $postcode]);
    }

    /**
     * Convert a customer to a business client.
     *
     * @param  int $id - the id of the customer
     *
     * @return \Response\Json
     */
    public function postConvertToClient($id)
    {
        $customer = Customer::find($id);

        if (! $customer) {
            return response()->json(['errors' => 'Unable to find the customer'], 404);
        }

        // Run everything as a transaction, so that we can rollback
        return DB::transaction(function () use ($customer) {
            $client = new Client();
            $client->name = $customer->name;

            if ($client->save()) {
                $site = new Site();
                $site->name = 'Main Site';
                $site->client_id = $client->id;
                $site->address = $customer->address;
                $site->address2 = $customer->address2;
                $site->postcode = $customer->postcode;
                $site->primary_phone = $customer->phone;

                if ($site->save()) {
                    $site_user = new SiteUser();
                    $site_user->site_id = $site->id;
                    $site_user->first_name = 'Main';
                    $site_user->last_name = 'User';
                    $site_user->email = $customer->email;
                    $site_user->phone = $customer->phone;
                    $site_user->mobile = $customer->mobile;
                    $site_user->authority = 1;
                    $site_user->position = 'default';

                    if ($site_user->save()) {
                        DB::table('tasks')->where('client_id', $customer->id)->where('client_type', 'customer')->update(['client_id' => $client->id, 'client_type' => 'client', 'site_id' => $site->id, 'site_user_id' => $site_user->id]);
                        DB::table('messages')->where('client_id', $customer->id)->where('client_type', 'customer')->update(['client_id' => $client->id, 'client_type' => 'client']);
                        DB::table('invoices')->where('client_id', $customer->id)->where('client_type', 'customer')->update(['client_id' => $client->id, 'client_type' => 'client']);
                        DB::table('projects')->where('client_id', $customer->id)->where('client_type', 'customer')->update(['client_id' => $client->id, 'client_type' => 'client']);
                        DB::table('devices')->where('client_id', $customer->id)->where('client_type', 'customer')->update(['client_id' => $client->id, 'client_type' => 'client']);
                        DB::table('keychain')->where('client_id', $customer->id)->where('client_type', 'customer')->update(['client_id' => $client->id, 'client_type' => 'client']);

                        // Delete the customer
                        $customer->delete();

                        return response()->json($client->toArray());
                    } else {
                        throw new Exception($site_user->errors->all(), 1);

                        return response()->json(['errors' => $site_user->errors->all()], 400);
                    }
                } else {
                    throw new Exception($site->errors->all(), 1);

                    return response()->json(['errors' => $site->errors->all()], 400);
                }
            } else {
                throw new Exception($client->errors->all(), 1);

                return response()->json(['errors' => $client->errors->all()], 400);
            }
        });
    }

    /**
     * Converts a client to a customer.
     *
     * @param  $id - the client id
     *
     * @return \Response\Json
     */
    public function postConvertToCustomer($id)
    {
        // Validate the client id
        $client = Client::findOrFail($id);

        // Run everything as a transaction, so that we can rollback
        return DB::transaction(function () use ($client) {
            $name = explode(' ', $client->name, 2);
            $site = $client->sites[0];
            $user = $site->users[0];

            $customer = new Customer();
            $customer->first_name = $name[0] ?: '';
            $customer->last_name = $name[1] ?: '';
            $customer->email = $user->email;
            $customer->phone = $user->phone;
            $customer->phone2 = $site->primary_phone;
            $customer->mobile = $user->mobile;
            $customer->address = $site->address;
            $customer->address2 = $site->address2;
            $customer->postcode = $site->postcode;

            // Save the customer
            if ($customer->save()) {

                // Move all the tasks over
                DB::table('tasks')->where('client_id', $client->id)->where('client_type', 'client')->update(['client_id' => $customer->id, 'client_type' => 'customer']);
                DB::table('messages')->where('client_id', $client->id)->where('client_type', 'client')->update(['client_id' => $customer->id, 'client_type' => 'customer']);
                DB::table('invoices')->where('client_id', $client->id)->where('client_type', 'client')->update(['client_id' => $customer->id, 'client_type' => 'customer']);
                DB::table('projects')->where('client_id', $client->id)->where('client_type', 'client')->update(['client_id' => $customer->id, 'client_type' => 'customer']);
                DB::table('devices')->where('client_id', $client->id)->where('client_type', 'client')->update(['client_id' => $customer->id, 'client_type' => 'customer']);
                DB::table('keychain')->where('client_id', $client->id)->where('client_type', 'client')->update(['client_id' => $customer->id, 'client_type' => 'customer']);

                // Delete the client
                $client->delete();

                return response()->json($customer->toArray());
            } else {
                throw new \Exception($customer->errors->first());
            }
        });
    }

    /**
     * Performs a lookup for the name of the customer,
     * based on their telephone number.
     *
     * @return string
     */
    public function getNameLookup(Request $request)
    {
        if (! $request->has('number')) {
            return '';
        }

        // The number gets passed as a parameter
        $number = $request->input('number');

        $customer = Customer::query()->where('phone', 'like', $number)->orWhere('phone2', 'like', $number)->orWhere('mobile', 'like', $number)->first();

        // Look for business clients if nothing found so far
        if (! $customer) {
            $user = SiteUser::query()->where('phone', 'like', $number)->orWhere('mobile', 'like', $number)->first();

            if ($user && $user->site && $user->site->client) {
                return $user->site->client->name.': '.$user->name;
            } else {
                $site = Site::query()->where('primary_phone', 'like', $number)->first();

                if ($site) {
                    return $site->client->name;
                }
            }
        } else {
            return $customer->name;
        }

        return '';
    }
    public function getCustomerReport(Request $request, $id)
    {

        // Return an empty page if no ID is passed
        if (! $id) {
            return '';
        }

        $customer = Customer::findOrFail($id);
        $customer->load('tasks');

        if ($request->input('start_date') && $request->input('end_date')) {
            $repairs = $customer->tasks()->where('type', 'repair')->whereBetween('created_at', [$request->input('start_date'), $request->input('end_date')])->get();
            $supports = $customer->tasks()->where('type', 'support')->whereBetween('created_at', [$request->input('start_date'), $request->input('end_date')])->get();
            $onsites = $customer->tasks()->where('type', 'onsite')->whereBetween('created_at', [$request->input('start_date'), $request->input('end_date')])->get();
        } else {
            $repairs = $customer->tasks()->where('type', 'repair')->get();
            $supports = $customer->tasks()->where('type', 'support')->get();
            $onsites = $customer->tasks()->where('type', 'onsite')->get();
        }

        $data = [
            'client'     => $customer,
            'repairs'    => $repairs,
            'supports'   => $supports,
            'onsites'    => $onsites,
            'start_date' => $request->input('start_date'),
            'end_date'   => $request->input('end_date'),
        ];

        $this->layout->content = View::make('clients::report', $data);
    }

    public function getClientReport($id)
    {

        // Return an empty page if no ID is passed
        if (! $id) {
            return '';
        }

        $client = Client::findOrFail($id);
        $client->load('tasks');

        if (request()->get('start_date') && request()->get('end_date')) {
            $repairs = $client->tasks()->where('type', 'repair')->whereBetween('created_at', [request()->get('start_date'), request()->get('end_date')])->get();
            $supports = $client->tasks()->where('type', 'support')->whereBetween('created_at', [request()->get('start_date'), request()->get('end_date')])->get();
            $onsites = $client->tasks()->where('type', 'onsite')->whereBetween('created_at', [request()->get('start_date'), request()->get('end_date')])->get();
        } else {
            $repairs = $client->tasks()->where('type', 'repair')->get();
            $supports = $client->tasks()->where('type', 'support')->get();
            $onsites = $client->tasks()->where('type', 'onsite')->get();
        }

        $data = [
            'client' => $client,
            'repairs' => $repairs,
            'supports' => $supports,
            'onsites' => $onsites,
            'start_date' => request()->get('start_date'),
            'end_date'   => request()->get('end_date'),
        ];

        return View::make('clients::report', $data);
    }
}
