<?php

namespace App\Modules\Stock;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;

class StockPurchaseOrderItemControllerRESTv1 extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $query = StockPurchaseOrderItem::select('*')->with('order');

        if ($request->has('stock_id')) {
            $query->where('stock_id', $request->input('stock_id'));
        }

        if ($request->has('supplier_id')) {
            $query = $query->join('stock_purchase_orders', 'stock_purchase_orders.id', '=', 'stock_purchase_order_items.stock_purchase_order_id')
                ->where('stock_purchase_orders.supplier_id', $request->input('supplier_id'));
        }

        //Order by id desc
        $query->orderBy('stock_purchase_order_items.id', 'DESC');

        // Apply limits and execute the query
        $query = $query->paginate($request->input('limit', 20));

        $response = [
            'success'      => true,
            'data'         => $query->getCollection()->toArray(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
            'from'         => $query->firstItem(),
            'to'           => $query->lastItem(),
        ];

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function show($id)
    {
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $item = StockPurchaseOrderItem::findOrFail($id);

        return DB::transaction(function () use (&$item, $id, $request) {
            try {
                //If received items but sn not required
                if ($request->input('sn_na', 0)) {
                    $item->received_quantity = $request->input('received_quantity');
                    $item->save();

                    return response()->json(['item' => $item, 'added_all' => true]);
                }

                //Update the serials for the item
                if ($request->has('serials')) {

                    //Indicates if all the serial numbers have been added
                    $added_all = true;
                    $serials = [];

                    foreach ($request->input('serials') as $serial) {
                        $item_serial = StockPurchaseOrderItemSerial::create(['order_item_id' => $serial['purchase_order_item_id'], 'serial_number' => $serial['serial_number']]);
                        if ($item_serial->id) {
                            $serial['added'] = true;
                        } else {
                            $serial['added'] = false;
                            $added_all = false;
                        }

                        array_push($serials, $serial);
                    }

                    $item = StockPurchaseOrderItem::findOrFail($id);
                    $response = [
                        'item'      => $item,
                        'serials'   => $serials,
                        'added_all' => $added_all,
                    ];

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

                // Check that the number of received items is not reduced
                if ($request->has('refused_quantity') && $request->input('refused_quantity', 0) < $item->refused_quantity) {
                    return response()->json(['Not allowed to reduce the number of items refused.'], 400);
                }

                $oldItem = clone $item;
                $item->fill($request->all());

                // Check that the total refused and receved items are not more than the total items quantity
                if ($item->refused_quantity + $item->received_quantity > $item->quantity) {
                    return response()->json(['Can not be more refused and received items than the total of items ordered.'], 400);
                }

                if (! $item->save()) {
                    return response()->json([$item->errors->all()], 400);
                }

                if ($request->has('refused_quantity')) {
                    $order = StockPurchaseOrder::findOrFail($item->stock_purchase_order_id);
                    // Kashflow integration removed - using Xero instead
                    // $xeroService = app(\App\Modules\Xero\Services\XeroService::class);
                    // TODO: Implement Xero purchase order sync if needed
                }

                return response()->json(['item' => $item]);
            } catch (\Excetion $e) {
                DB::rollback();

                return response()->json(['error' => $e->getMessage()], 400);
            }
        });
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function destroy($id)
    {
    }
}
