<?php

namespace App\Modules\Clients\controllers\api\v1;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Gate;
use App\Modules\Bookings\Task;
use App\Http\Controllers\BaseController;
use App\Modules\Clients\Customer;

class CustomersControllerREST extends BaseController
{
    /**
     * Return all the records as an encoded JSON.
     *
     * @return JSON
     */
    public function all()
    {
        // ob_start('ob_gzhandler');

        // Get an instance of a customer so we can retrieve the table name
        $customer = new Customer();
        $data = DB::table($customer->getTable())->whereNull('deleted_at')->orderBy('id', 'desc')->get();
        $total = count($data);

        foreach ($data as $key => $value) {
            $value->name = trim($value->first_name.' '.$value->last_name);
        }

        $response = [
            'success'      => true,
            'data'         => $data,
            'total'        => $total,
            'current_page' => 1,
            'last_page'    => 1,
            'from'         => 1,
            'to'           => $total,
        ];

        return $response;

        /*
        $encoded_html = gzencode(json_encode($response), 9);
        header('Content-Type: application/json');
        header('Content-Length: ' . strlen($encoded_html));
        header('Content-Encoding: gzip');
        return $encoded_html;
        */
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        // Check to see if all the records were requested
        if ($request->get('all') && $request->get('all') != 'false') {
            return $this->all();
        }

        $query = Customer::query()->select('*');

        if ($request->get('q')) {
            $query = $query->where(function ($query) use ($request) {
                    return $query->where(DB::raw("CONCAT_WS(' ', first_name, last_name)"), 'like', '%'.$request->get('q').'%')
                                ->orWhere('phone', 'like', $request->get('q').'%')
                                ->orWhere('phone2', 'like', $request->get('q').'%')
                                ->orWhere('mobile', 'like', $request->get('q').'%')
                                ->orWhere('email', 'like', '%'.$request->get('q').'%');
                });
        }

        if ($request->get('name')) {
            $query = $query->where(DB::raw("CONCAT_WS(' ', first_name, last_name)"), 'like', '%'.$request->get('name').'%');
        }

        if ($request->get('modifiedSince')) {
            $query->where('customers.updated_at', '>=', $request->get('modifiedSince'));
        }

        $query->orderBy('id', 'desc');

        // Apply limits and execute the query
        // $query = $query->take($request->get('limit', 20))->skip($request->get('skip', 0))->get();
        $query = $query->paginate($request->get('limit', 20));

        foreach ($query as $value) {
            if ($request->get('active_tasks')) {
                $value->active_tasks = Task::query()->open()->where('client_id', $value->id)->where('client_type', 'customer')->count();
            }

            if ($request->get('spent')) {
                $value->spent = Task::query()->where('client_id', $value->id)->where('client_type', 'customer')->sum('labour');
            }
        }

        $response = [
            'success'      => true,
            'data'         => $query->getCollection()->toArray(),
            'total'        => $query->total(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
            'from'         => $query->firstItem(),
            'to'           => $query->lastItem(),
        ];

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        Log::info("store customer hit");
        $client = Customer::create($request->except('id'));

        if (! $client->id) {
            $response = [
                'success' => false,
                'errors'  => $client->errors,
            ];
        } else {
            Event::dispatch('CustomerCreated', $client);
            Log::info("CustomerCreated fired");
            $response = [
                'success' => true,
                'data'    => $client->toArray(),
            ];
        }

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function show($id)
    {
        $customer = Customer::find($id);

        // $customer->load('sites', 'primary_site', 'primary_contact', 'sla');

        $response = [
            'success' => true,
            'data'    => $customer->toArray(),
        ];

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function update(Request $request, $id)
    {
        Log::info("update customer hit");
        $customer = Customer::find($id);

        // to be created
        // if ($request->has('name')) $customer->name = $request->get('name');

        $customer->fill($request->except('id'));

        if ($customer->save()) {
            Event::dispatch('CustomerUpdated', $customer);
            Log::info("CustomerUpdated fired");
            $response = ['success' => true, 'data' => $customer->toArray()];
        } else {
            $response = ['success' => false, 'error' => $customer->errors];
        }

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        if (Gate::denies('delete-client')) {
            abort(403);
        }
    }
}
