<?php

namespace App\Http\Controllers\hrm;

use App\Http\Controllers\Controller;

use App\Models\Expense;
use App\Models\Sale;
use Illuminate\Http\Request;
use App\Models\Department;
use App\Models\Societe;
use App\Models\Vehicule;
use Carbon\Carbon;
use DB;

class VehiculeController extends Controller
{

    //----------- GET ALL  vehicule --------------\\

    public function index(Request $request)
    {
        $this->authorizeForUser($request->user('api'), 'view', Vehicule::class);

        // How many items do you want to display.
        $perPage = $request->limit;
        $pageStart = \Request::get('page', 1);
        // Start displaying items from this number;
        $offSet = ($pageStart * $perPage) - $perPage;
        $order = $request->SortField;
        $dir = $request->SortType;

        $from = $request->from;
        $to = $request->to;
        $societe_id = $request->societe_id;

        $vehicules = Vehicule::where('deleted_at', '=', null)
            ->when($from && $to, function ($query) use ($from, $to) {
                return $query->whereBetween('created_at', array($from, $to));
            })

            // Search With Multiple Param
            ->where(function ($query) use ($request) {
                return $query->when($request->filled('search'), function ($query) use ($request) {
                    return $query->where('type', 'LIKE', "%{$request->search}%")
                        ->orWhere('matricule', 'LIKE', "%{$request->search}%");
                });
            });
        $totalRows = $vehicules->count();
        if ($perPage == "-1") {
            $perPage = $totalRows;
        }
        $vehicules = $vehicules->offset($offSet)
            ->limit($perPage)
            ->orderBy($order, $dir)
            ->get();

        $data = [];
        foreach ($vehicules as $vehicule) {
            $item["id"] = $vehicule->id;
            $item["matricule"] = $vehicule->matricule;
            $item["type"] = $vehicule->type;
            $item["total_sales"] = Sale::where('vehicule_1_id', $vehicule->id)
                ->orWhere('vehicule_2_id', $vehicule->id)
                ->orWhere('vehicule_3_id', $vehicule->id)
                ->when($societe_id, function ($query) use ($societe_id) {
                    return $query->where('societe_id', '=', $societe_id);
                })
                ->sum('GrandTotal');
            // $item["total_expenses"] = Expense::join('chiffeurs as c', 'expenses.chiffeur_id', '=', 'c.id')
            //     ->where('c.vehicule_id', $vehicule->id)
            //     ->sum('amount');
            $item["total_expenses"] = Expense::where('vehicule_id', $vehicule->id)
                ->when($societe_id, function ($query) use ($societe_id) {
                    return $query->where('societe_id', '=', $societe_id);
                })
                ->sum('amount');

            $data[] = $item;
        }


        $dataWithFooter = [
            "id" => '',
            "matricule" => '',
            "type" => '',
            "total_sales" => round(Sale::when($societe_id, function ($query) use ($societe_id) {
                return $query->where('societe_id', '=', $societe_id);
            })->whereIn('vehicule_1_id', $vehicules->pluck('id'))->orWhereIn('vehicule_2_id', $vehicules->pluck('id'))->orWhereIn('vehicule_3_id', $vehicules->pluck('id'))->sum('GrandTotal'), 2, PHP_ROUND_HALF_DOWN),
            "total_expenses" => round(Expense::when($societe_id, function ($query) use ($societe_id) {
                return $query->where('societe_id', '=', $societe_id);
            })->join('chiffeurs as c', 'expenses.chiffeur_id', '=', 'c.id')->whereIn('c.vehicule_id', $vehicules->pluck('id'))->sum('amount'), 2, PHP_ROUND_HALF_DOWN),
        ];
        $dataWithFooter['children'] = $data;
        $dataWithFooter =  [$dataWithFooter];

        $societes = Societe::where('deleted_at', '=', null)->get(['id', 'name']);

        return response()->json([
            'vehicules' => $dataWithFooter,
            'totalRows' => $totalRows,
            'societes' => $societes
        ]);
    }

    //----------- Store new Vehicule --------------\\

    public function store(Request $request)
    {
        $this->authorizeForUser($request->user('api'), 'create', Vehicule::class);

        request()->validate([
            'matricule'      => 'required|string',
            'type'      => 'required|string',
        ]);

        Vehicule::create([
            'matricule'    => $request['matricule'],
            'type'   => $request['type'],
        ]);

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

    //------------ function show -----------\\

    public function show($id)
    {
        //

    }

    //-----------Update Warehouse --------------\\

    public function update(Request $request, $id)
    {
        $this->authorizeForUser($request->user('api'), 'update', Vehicule::class);

        request()->validate([
            'matricule'      => 'required|string',
            'type'      => 'required|string',
        ]);

        Vehicule::where('id', $id)->first()->update([
            'matricule'    => $request['matricule'],
            'type'   => $request['type'],
        ]);

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

    //----------- Delete  vehicule --------------\\

    public function destroy(Request $request, $id)
    {
        $this->authorizeForUser($request->user('api'), 'delete', Vehicule::class);

        Vehicule::whereId($id)->update([
            'deleted_at' => Carbon::now(),
        ]);


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

    //-------------- Delete by selection  ---------------\\

    public function delete_by_selection(Request $request)
    {

        $this->authorizeForUser($request->user('api'), 'delete', Vehicule::class);

        $selectedIds = $request->selectedIds;
        foreach ($selectedIds as $vehicule_id) {
            Vehicule::whereId($vehicule_id)->update([
                'deleted_at' => Carbon::now(),
            ]);
        }

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

    //----------- GET ALL  Vehicule --------------\\

    public function Get_all_Vehicule()
    {
        $vehicules = Vehicule::where('deleted_at', '=', null)
            ->orderBy('id', 'desc')
            ->get(['id', 'matricule', 'type']);

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