<?php

namespace App\Http\Controllers\hrm;

use App\Http\Controllers\Controller;

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

class SocieteController extends Controller
{

    //----------- GET ALL  societe --------------\\

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

        $societes = Societe::with('expense')
            ->where('deleted_at', '=', null)

            ->when($from && $to, function ($query) use ($from, $to) {
                return $query->whereBetween('created_at', array($from, $to));
            })
            ->when($request->filled('facturation'), function ($query) use ($facturation) {
                return $query->whereHas('expense', function($qr) use ($facturation) {
                    return $qr->where('facturation', $facturation);
                });
            })

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


        $data = [];
        foreach ($societes as $societe) {
            $item["id"] = $societe->id;
            $item["name"] = $societe->name;
            $item["email"] = $societe->email;
            $item["number"] = $societe->number;
            $item["address"] = $societe->address;
            $item["ice"] = $societe->ice;
            $item["total_sales"] = round(Sale::where('societe_id', $societe->id)
                ->sum('GrandTotal'), 2, PHP_ROUND_HALF_DOWN);
            $item["total_purchases"] = round(Purchase::where('societe_id', $societe->id)
                ->sum('GrandTotal'), 2, PHP_ROUND_HALF_DOWN);
            $item["total_expenses"] = round(Expense::where('societe_id', $societe->id)
                ->where('facturation', '=', 0)
                ->sum('amount'), 2, PHP_ROUND_HALF_DOWN);
            $item["profit"] = round($item["total_sales"] - $item["total_purchases"] - $item["total_expenses"], 2, PHP_ROUND_HALF_DOWN);

            $data[] = $item;
        }

        $dataWithFooter = [
            "id" => '',
            "name" => '',
            "email" => '',
            "number" => '',
            "address" => '',
            "ice" => '',
            "total_sales" => round(Sale::whereIn('societe_id', $societes->pluck('id'))->sum('GrandTotal'), 2, PHP_ROUND_HALF_DOWN),
            "total_purchases" => round(Purchase::whereIn('societe_id', $societes->pluck('id'))->sum('GrandTotal'), 2, PHP_ROUND_HALF_DOWN),
            "total_expenses" => round(Expense::where('facturation', 0)->whereIn('societe_id', $societes->pluck('id'))->sum('amount'), 2, PHP_ROUND_HALF_DOWN),
        ];
        $dataWithFooter['profit'] = round($dataWithFooter['total_sales'] - $dataWithFooter['total_purchases'] - $dataWithFooter['total_expenses'], 2, PHP_ROUND_HALF_DOWN);
        $dataWithFooter['children'] = $data;
        $dataWithFooter =  [$dataWithFooter];


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

    //----------- Store new Societe --------------\\

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

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

        Societe::create([
            'name'    => $request['name'],
            'email'   => $request['email'],
            'number'   => $request['number'],
            'address' => $request['address'],
            'ice' => $request['ice'],
        ]);

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

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

        Societe::whereId($id)->update([
            'name'    => $request['name'],
            'email'   => $request['email'],
            'number'   => $request['number'],
            'address' => $request['address'],
            'ice' => $request['ice'],
        ]);

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

    //----------- Delete  societe --------------\\

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

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

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

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

    //----------- GET ALL  Societe --------------\\

    public function Get_all_Societe()
    {
        $societes = Societe::where('deleted_at', '=', null)
            ->orderBy('id', 'desc')
            ->get(['id', 'name']);

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