<?php

namespace App\Service\Shop;

use App\Models\ReqProductShiftDetails;
use App\Models\ReqProductShiftMaster;
use App\Models\RequisitionMaster;
use App\Models\WarehouseStock;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Services\NotificationService;

class ReqShifingService
{
    public static function create(array $data)
    {
    

        try {

            DB::beginTransaction();
            $collect = collect($data);
            $requsition_id = $collect['invoice_no'];
            $masert_requsition = RequisitionMaster::where('id', $requsition_id)->first()->invoice_no;
            $maserShifting = ReqProductShiftMaster::create([
                'reqsition_id' => $requsition_id,
                'reqsition_no' => $masert_requsition,
                'shop_id' => $collect['shop_id'],
                'warehouse_id' => $collect['warehouse_id'],
                'created_by' => Auth::user()->id,
            ]);

            foreach ($collect['list'] as $item) {

                WarehouseStock::where('warehouse_id', $collect['warehouse_id'])->when(setting()->business_id == 3, fn($q) => $q->where('batch_no', $item['batch_no']))->where('attribute_id', $item['attribute_id'])->update([
                    'quantity' => DB::Raw('quantity -' . $item['send_qty']),
                ]);
                ReqProductShiftDetails::create([
                    'shift_masters_id' => $maserShifting->id,
                    'product_id' => $item['product_id'],
                    'attribute_id' => $item['attribute_id'],
                    'sending_qty' => $item['send_qty'],
                    'batch_no' => $item['batch_no'] ?? null,
                ]);
            }

            // Send notification for new requisition
            $requisition = RequisitionMaster::with('user.shop', 'shop')->find($requsition_id);

            $redirectConfig = (object) [
                'route' => 'shipment-received',
                'warehouseId' => $collect['shop_id'],
            ];

            $requisitionNotificationData = [
                'title' => 'Requisition Products Shifted',
                'message' => "Requisition #{$requisition->invoice_no} has been created by " . Auth::user()->name,
                'requisition_id' => $requisition->id,
                'requisition_invoice' => $requisition->invoice_no,
                'created_by' => $requisition->user->name ?? 'Unknown User',
                'shop_name' => Auth::user()->shop->name ?? 'Unknown Shop',
               
            ];


            NotificationService::sendRequisitionCreatedNotification($requisitionNotificationData, $redirectConfig);

            RequisitionMaster::where('id', $requsition_id)->update([
                'status' => 2,
            ]);

            DB::commit();
        } catch (\Throwable $th) {
            // throw $th;
            DB::rollBack();

            // Rethrow or handle gracefully
            throw $th;
        }
    }

    public static function Update(array $data, $id)
    {

        try {

            DB::beginTransaction();

            $collect = collect($data);

            $previous_master = ReqProductShiftMaster::where('id', $id)->first();
            $previous = ReqProductShiftDetails::where('shift_masters_id', $id)->get();

            ReqProductShiftMaster::where('id', $id)->update([
                'warehouse_id' => $collect['warehouse_id'],
                'created_by' => Auth::user()->id,
            ]);
            foreach ($previous as $key => $value) {

                WarehouseStock::where('warehouse_id', $previous_master->warehouse_id)->where('attribute_id', $value->attribute_id)->update([
                    'quantity' => DB::Raw('quantity +' . $value->sending_qty),
                ]);
            }

            $created_product = [];
            foreach ($collect['list'] as $item) {
                WarehouseStock::where('warehouse_id', $collect['warehouse_id'])->where('attribute_id', $item['attribute_id'])->update([
                    'quantity' => DB::Raw('quantity -' . $item['send_qty']),

                ]);
                array_push($created_product, $item['attribute_id']);

                ReqProductShiftDetails::where('shift_masters_id', $id)->where('attribute_id', $item['attribute_id'])->update([
                    'product_id' => $item['product_id'],
                    'attribute_id' => $item['attribute_id'],
                    'sending_qty' => $item['send_qty'],

                ]);
            }
            ReqProductShiftDetails::where('shift_masters_id', $id)->whereNotIn('product_id', $created_product)->delete();

            DB::commit();
        } catch (\Throwable $th) {
            // throw $th;
            DB::rollBack();

            // Rethrow or handle gracefully
            throw $th;
        }
    }

    public static function accept($data, $id)
    {
        $collect = collect($data);
        $shifting_info = ReqProductShiftMaster::where('id', $id)->first();
        $shifting_info->status = 2;
        $shifting_info->save();

        ReqProductShiftMaster::where('id', $id)->update([
            'status' => 2,

        ]);

        foreach ($collect['list'] as $item) {

            $edgiest = WarehouseStock::where('warehouse_id', $shifting_info->shop_id)
                ->where('attribute_id', $item['attribute_id'])
                ->when(setting()->business_id == 3, fn($q) => $q->where('batch_no', $item['batch_no']))
                ->first();
            if ($edgiest) {
                $edgiest->update([
                    'quantity' => DB::raw('quantity + ' . $item['rev_qty']),
                ]);
            } else {
                $data = WarehouseStock::where('warehouse_id', $shifting_info->warehouse_id)->where('attribute_id', $item['attribute_id'])->first();
                WarehouseStock::create([
                    'warehouse_id' => $shifting_info->shop_id,
                    'product_id' => $item['product_id'],
                    'attribute_id' => $item['attribute_id'],
                    'quantity' => $item['rev_qty'],
                    'unit_price' => $data->unit_price,
                    'tp_price' => $data->tp_price,
                    'mrp_price' => $data->mrp_price,
                    'batch_no' => $data->batch_no,

                ]);
            }
            ReqProductShiftDetails::where('shift_masters_id', $id)->update([
                'received_qty' => $item['rev_qty'],

            ]);
        }
    }
}
