<?php

namespace App\Http\Controllers\Admin\Warehouse;

use App\Http\Controllers\Controller;
use App\Models\Warehouse;
use App\Models\WarehouseTransferMaster;
use App\Service\Warehouse\WarehouseTransfer;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class WarehouseTransferController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {


      $warehouse_transfer = WarehouseTransferMaster::with([
            'transferDetails' => function ($query) {
                $query->with([
                    'productAttribute' => function ($subQuery) {
                        $subQuery->with(['product', 'warehouse']);
                    },
                ]);
            },
            'warehouseForm',
            'warehouseTo',
        ])

            ->orderByDesc('id')
            ->get();

        return Inertia::render('Warehouse/WarehouseTransfer', compact('warehouse_transfer'));
    }

    public function view()
    {
        return response()->json(['warehouse' => Warehouse::orderbydesc('id')->get()]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {

        WarehouseTransfer::StoreData(request()->all());
        $warehouse_transfer = WarehouseTransferMaster::with([
            'transferDetails' => function ($query) {
                $query->with([
                    'productAttribute' => function ($subQuery) {
                        $subQuery->with(['product', 'warehouse']);
                    },
                ]);
            },
            'warehouseForm',
            'warehouseTo',
        ])

            ->orderByDesc('id')
            ->get();

        return response()->json(['success' => 'Add  successfully', 'warehouse_transfer' => $warehouse_transfer]);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Request $request, $id)
    {
        if (!request()->has('form_warehouse_id')) {
            request()->merge(['form_warehouse_id' => 'prevent']);
        }

        $master = WarehouseTransferMaster::where('id', $id)->first();
        $warehouse_transfer = WarehouseTransferMaster::with([
            'transferDetails' => function ($query) use ($master) {
                $query->with([
                    'productAttribute' => function ($subQuery) use ($master) {
                        $subQuery->with([
                            'product',
                            'warehouse' => function ($childQuery) use ($master) {
                                $childQuery->where('warehouse_id', $master->from_warehouse_id);
                            },
                            'batch' => function ($query) {
                                $query->where('warehouse_id', request()->form_warehouse_id ?? 1)->select('id', 'attribute_id', 'batch_no', 'quantity');
                            },
                        ]);
                    },
                ]);
            },
            'warehouseForm',
            'warehouseTo',
        ])->where('id', $id)
            ->orderByDesc('id')
            ->first();

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

    public function update(Request $request, string $id)
    {

        WarehouseTransfer::UpdateData(request()->all(), $id);
        $warehouse_transfer = WarehouseTransferMaster::with([
            'transferDetails' => function ($query) {
                $query->with([
                    'productAttribute' => function ($subQuery) {
                        $subQuery->with(['product', 'warehouse']);
                    },
                ]);
            },
            'warehouseForm',
            'warehouseTo',
        ])

            ->orderByDesc('id')
            ->get();

        return response()->json(['success' => 'Update successfully', 'warehouse_transfer' => $warehouse_transfer]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {

        WarehouseTransfer::deleteData($id);

        $warehouse_transfer = WarehouseTransferMaster::with([
            'transferDetails' => function ($query) {
                $query->with([
                    'productAttribute' => function ($subQuery) {
                        $subQuery->with(['product', 'warehouse']);
                    },
                ]);
            },
            'warehouseForm',
            'warehouseTo',
        ])

            ->orderByDesc('id')
            ->get();

        return response()->json(['success' => 'Warehouse delete successfully', 'warehouse_transfer' => $warehouse_transfer]);
    }

    public function transferReportView()
    {

        $warehouseList = Warehouse::orderbydesc('id')->get();

        return Inertia::render('Report/WareHouseTransfer', compact('warehouseList'));
    }

    public function transferReportSearch()
    {

        if (request()->start != 'null') {

            $dateStringWithoutTimezone = substr(request()->start, 0, strpos(request()->start, 'GMT'));

            // Make sure to trim any extra spaces before parsing
            $start = Carbon::parse(trim($dateStringWithoutTimezone));
        } else {
            $start = null;
        }

        if (request()->end !== 'null' && request()->end !== 'undefined' && !empty(request()->end)) {

            $dateStringWithoutTimezone = substr(request()->end, 0, strpos(request()->end, 'GMT'));
            $end = Carbon::parse(trim($dateStringWithoutTimezone));
        } else {
            $end = false;
        }

        $warehouseTransfer = DB::table('warehouse_transfer_view')
            ->when(request()->from_warehouse_id, function ($query) {
                return $query->where('from_warehouse_id', request()->from_warehouse_id);
            })
            ->when(request()->to_warehouse_id, function ($query) {
                return $query->where('to_warehouse_id', request()->to_warehouse_id);
            })
            ->when($start && $end, function ($query) use ($start, $end) {

                return $query->whereBetween('date', [$start->toDateString(), $end->toDateString()]);
            })
            ->when($start && !$end, function ($query) use ($start) {

                return $query->whereDate('date', '=', $start->toDateString());
            })
            ->get();

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