<?php

namespace App\Http\Controllers;

use App\Models\CrmItem;
use App\Models\CrmItemReturn;
use App\Models\CrmItemReturnLog;
use App\Models\Item;
use App\Models\ItemReturn;
use App\Models\ItemReturnItem;
use Brian2694\Toastr\Facades\Toastr;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CrmItemReturnController extends Controller
{
    public function crmItemReturn($client_id)
    {

        $start = Carbon::now()->startOfMonth()->format('Y-m-d 00:00:00');
        $end = Carbon::now()->endOfMonth()->format('Y-m-d 23:59:59');

        $data = [
            'crm_return_items' => CrmItemReturn::with('item')->where('client_id', $client_id)->where('approve_status', 'Not Approve')->whereBetween('created_at', [$start, $end])->get(),
            'crm_items' => Item::where('show_crm', 'Yes')->get(),
            'client_id' => $client_id,
        ];

        return view('crm.item_return.return', $data);
    }

    public function crmItemReturnSave(Request $request)
    {

        if (isset($request->item_quantity) && $request->item_quantity == 0) {
            Toastr::error('Please enter item', 'Error');
            return redirect()->back();
        }

        $start = Carbon::now()->startOfMonth()->format('Y-m-d 00:00:00');
        $end = Carbon::now()->endOfMonth()->format('Y-m-d 23:59:59');

        DB::beginTransaction();
        try {
            $old_data = CrmItemReturn::where('client_id', $request->client_id)->whereBetween('created_at', [$start, $end])->get();

            CrmItemReturn::where('client_id', $request->client_id)->whereBetween('created_at', [$start, $end])->where('approve_status', 'Not Approve')->delete();

            foreach ($request->item_quantity as $key => $value) {
                $item = new CrmItemReturn();
                $item->client_id = $request->client_id;
                $item->user_id = auth()->user()->id;
                $item->crm_item_id = $request->item_id[$key];
                $item->status = $request->item_return_status[$key];
                $item->quantity = $request->item_quantity[$key];
                $item->save();
            }

            $new_data = CrmItemReturn::where('client_id', $request->client_id)->whereBetween('created_at', [$start, $end])->get();
            $return_log = new CrmItemReturnLog();

            $return_log->client_id = $request->client_id;
            $return_log->user_id = auth()->user()->id;
            $return_log->old_data = json_encode($old_data);
            $return_log->new_data = json_encode($new_data);
            $return_log->save();


            DB::commit();
            Toastr::success('Item return successful', 'Success');
            return redirect()->back();
        } catch (\Exception $e) {
            DB::rollBack();
            Toastr::error('Something went wrong', 'Error');
            return redirect()->back();
        }
    }

    public function crmReturnReport()
    {
        $start = Carbon::now()->today()->firstOfMonth();
        $end = today();
        $items = Item::where('show_crm', 'Yes')->get();

        $data = [
            'start' => $start,
            'end'   => $end,
            'items' => $items
        ];

        return view('crm.report.return', $data);
    }

    public function crmReturnReportSearch(Request $request)
    {
        // dd($request->all());
        $start = Carbon::parse($request->from_date)->format('Y-m-d 00:00:00');
        $end = Carbon::parse($request->to_date)->format('Y-m-d 23:59:59');

        if ($request->item_id == 'all') {


            $grouped_by_item_id_and_status_row_sql =  DB::select(DB::raw("SELECT ci.name as item_name, cir.status, SUM(quantity) as quantity FROM crm_item_returns
                                                                            as cir LEFT JOIN items as ci on ci.id = cir.crm_item_id
                                                                            WHERE cir.created_at BETWEEN '$start' AND '$end'
                                                                            and cir.approve_status = 'Approve'
                                                                            GROUP BY crm_item_id, status
                                                                            ORDER BY cir.crm_item_id"));

            $output = [];

            foreach ($grouped_by_item_id_and_status_row_sql as $result) {
                $key = $result->item_name;

                // If the key is not yet in the output array, create it
                if (!isset($output[$key])) {
                    $output[$key] = [];
                }

                // Concatenate status and quantity
                $output[$key][$result->status] = $result->quantity;
            }


            $data = [
                'items' => $output,
                'items_unit' => CrmItem::with('crmItemUnit')->pluck('crm_item_unit_id'),
            ];
            // dd("comes");

            return view('crm.report.all_item_result', $data);
        } else {
            $return_items = CrmItemReturn::with('item', 'client', 'addedBy', 'approvedBy')
                ->whereBetween('created_at', [$start, $end])
                ->where('crm_item_id', $request->item_id)
                ->where('crm_item_id', $request->item_id)
                ->where('approve_status', 'Approve')
                ->get();
            $data = [
                'return_items' => $return_items,
            ];
            // dd($data);
            return view('crm.report.single_item_result', $data);
        }
    }

    public function crmItemReturnShow($client_id)
    {

        $start = Carbon::now()->startOfMonth()->format('Y-m-d 00:00:00');
        $end = Carbon::now()->endOfMonth()->format('Y-m-d 23:59:59');

        $data = [
            'crm_return_items' => CrmItemReturn::with('item')->where('client_id', $client_id)->whereBetween('created_at', [$start, $end])->get(),
            'crm_items' => Item::where('show_crm', 'Yes')->get(),
            'client_id' => $client_id,
        ];
        return view('crm.item_return.showItems', $data);
    }

    public function crmItemReturnApprove(Request $request)
    {
       if(!isset($request->crm_return_item_id)){
        Toastr::error("No item added to approve; please check.");
        return redirect()->back();
       }
        DB::beginTransaction();
        try {

            $date = today();
            $itemReturn = new ItemReturn();
            $itemReturn->date = $date;
            // $itemReturn->employee_id = $request->employee_id;
            $itemReturn->branch_id = 1;
            $itemReturn->recived_user_id = auth()->user()->id;
            $itemReturn->reason = "Customer Left";
            $itemReturn->serial_add_or_not = 'no';
            $itemReturn->save();

            foreach ($request->crm_return_item_id as $key => $value) {
                $return_item = CrmItemReturn::find($value);
                if ($return_item->approve_status == 'Not Approve' && $return_item->status == "Good") {
                    // dd($request->all());

                    // $return_item->approve_status = "Approve";
                    // $return_item->approve_by = auth()->user()->id;
                    // $return_item->approve_time = now();
                    // $return_item->save();
                    // dd($return_item);

                    $itemReturnItem = new ItemReturnItem();
                    $itemReturnItem->item_retern_id = $itemReturn->id;
                    $itemReturnItem->item_id = $return_item->crm_item_id;
                    $itemReturnItem->qty =  $return_item->quantity;
                    // $itemReturnItem->serial_no = $request->serialNumber[$i];
                    $itemReturnItem->save();
                }
            }

            foreach ($request->crm_return_item_id as $key => $value) {
                $return_item = CrmItemReturn::find($value);
                if ($return_item->approve_status == 'Not Approve') {
                    // dd($request->all());

                    $return_item->approve_status = "Approve";
                    $return_item->approve_by = auth()->user()->id;
                    $return_item->approve_time = now();
                    $return_item->save();
                    // dd($return_item);
                }
            }



            // $employeeName=Employee::where('id',$request->employee_id)->first();






            DB::commit();
            Toastr::success('Item return approve successful', 'Success');
            return redirect()->back();
        } catch (\Exception $e) {
            dd($e);
            DB::rollBack();
            Toastr::error('Something went wrong', 'Error');
            return redirect()->back();
        }
    }
}
