<?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\Voyage;
use Carbon\Carbon;
use DB;

class VoyageController extends Controller
{

    //----------- GET ALL  voyage --------------\\

    public function index(Request $request)
    {
        $this->authorizeForUser($request->user('api'), 'view', Voyage::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;

        $voyages = Voyage::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('from', 'LIKE', "%{$request->search}%")
                        ->orWhere('to', 'LIKE', "%{$request->search}%")
                        ->orWhere('ref', 'LIKE', "%{$request->search}%");
                });
            });
        $totalRows = $voyages->count();
        if ($perPage == "-1") {
            $perPage = $totalRows;
        }
        $voyages = $voyages->offset($offSet)
            ->limit($perPage)
            ->orderBy($order, $dir)
            ->get();


        $data = [];
        foreach ($voyages as $voyage) {
            $item["id"] = $voyage->id;
            $item["ref"] = $voyage->ref;
            $item["from"] = $voyage->from;
            $item["to"] = $voyage->to;
            $item["total_sales"] = round(Sale::where('voyage_id', $voyage->id)
                ->sum('GrandTotal'), 2, PHP_ROUND_HALF_DOWN);;
            $item["total_expenses"] = round(Expense::join('sales as s', 'expenses.sale_id', '=', 's.id')
                ->where('s.voyage_id', $voyage->id)
                ->sum('amount'), 2, PHP_ROUND_HALF_DOWN);;
            $item["net_profit"] = round($item["total_sales"] - $item["total_expenses"], 2, PHP_ROUND_HALF_DOWN);

            $data[] = $item;
        }


        $dataWithFooter = [
            "total_sales" => round(Sale::whereIn('voyage_id', $voyages->pluck('id'))->sum('GrandTotal'), 2, PHP_ROUND_HALF_DOWN),
            "total_expenses" => round(Expense::join('sales as s', 'expenses.sale_id', '=', 's.id')->whereIn('s.voyage_id', $voyages->pluck('id'))->sum('amount'), 2, PHP_ROUND_HALF_DOWN),
        ];
        $dataWithFooter['net_profit'] = round($dataWithFooter['total_sales'] - $dataWithFooter['total_expenses'], 2, PHP_ROUND_HALF_DOWN);
        $dataWithFooter['children'] = $data;
        $dataWithFooter =  [$dataWithFooter];

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

    //----------- Store new Voyage --------------\\

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

        request()->validate([
            'from'      => 'required|string',
            'to'      => 'required|string',
        ]);

        $i = Voyage::count() + 1;
        $ref = "VY" . str_pad($i, 5, '0', STR_PAD_LEFT);
        Voyage::create([
            'from'    => $request['from'],
            'to'   => $request['to'],
            'ref' => $ref
        ]);

        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', Voyage::class);

        request()->validate([
            'from'      => 'required|string',
            'to'      => 'required|string',
        ]);

        Voyage::whereId($id)->update([
            'from'    => $request['from'],
            'to'   => $request['to']
        ]);

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

    //----------- Delete  voyage --------------\\

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

        Voyage::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', Voyage::class);

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

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

    //----------- GET ALL  Voyage --------------\\

    public function Get_all_Voyage()
    {
        $voyages = Voyage::where('deleted_at', '=', null)
            ->orderBy('id', 'desc')
            ->get(['id', 'from', 'to', 'ref']);

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