<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\Item;
use App\Models\ItemCategory;
use App\Models\Payment;
use App\Models\StockIn;
use App\Models\Purchase;
use App\Models\Supplier;
use App\Models\PurchaseItem;
use App\Models\SerialNumber;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;


class PurchaseController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function stock()
    {
        //$list = StockIn::groupBy('item_id')->get();

        // $list = StockIn::with('item.category','item.serialNumbers')->orderBy('id','DESC')->groupBy('item_id')->paginate('100');
        $list = Item::with('category','stockIn','stockOut','itemReturn','itemAdjustment')->paginate('100');
        return view('purchase.stock',[
            'page_title' => 'Stock List',
            'list' => $list,
            'url' => route('purchase.create'),
            'add_button' => 'true',
            'class' => 'btn btn-primary',
            'value' => 'Add New Purchase'
             ]);


        //new
        // $data=[

        //     'list'=> Item::with('category','stockIn','stockOut','itemReturn','itemAdjustment')->get(),
        // ];

        // return view('purchase.stock',$data);
    }
    public function index()
    {
        $list = Purchase::get();
        return view('purchase.index',[
            'page_title' => 'Purchase List',
            'list' => $list,
            'url' => route('purchase.create'),
            'add_button' => 'true',
            'class' => 'btn btn-primary',
            'value' => 'Add New Purchase'
             ]);
    }

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

        return view('purchase.create',[
            'suppliers' => Supplier::all(),
            'categories' => ItemCategory::all(),
            'branches' => Branch::all(),
            'page_title'=> 'Add New Purchase'
        ]);

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //  dd($request->all());
         $request->validate([
            'products' => 'array|required',
            'supplier_id' => 'required',
            'voucher_no' => 'required',
            'payment_method' => 'required',
            'remark' => 'nullable',
        ]);
        DB::beginTransaction();
        try{


        $purchase = new Purchase();
        $purchase->invoice_number = "INV-" . \App\Classes\InvoiceNumber::serial_number();
        $purchase->remark = $request->remark;
        $purchase->supplier_id = $request->supplier_id;
        $purchase->branch_id = $request->branch_id;
        $purchase->subtotal = $request->subtotal;
        $purchase->paid = $request->paid;
        $purchase->payment_method = $request->payment_method;
        $purchase->voucher_no = $request->voucher_no;
        $purchase->due = $request->due;
        $purchase->creator_user_id = Auth::id();
        $purchase->save();
        $products = $request->get('products');

        foreach ($products as $key => $product) {
            $item = new PurchaseItem();
            $item->purchase_id = $purchase->id;
            $item->item_id = $product['item_id'];
            $item->quantity = $product['quantity'];
            $item->buying_price = $product['price'];
            $item->save();

        }
        $payment_info = $request->get('payments');
        if (!empty($payment_info)) {
            // $payment_info = ;
            Payment::create([
                "purchase_id" => $purchase->id,
                "amount" => $request->paid,
                "cheque_number" => $payment_info['cheque_number'],
                "account_number" => $payment_info['account_number'],
                "branch_name" => $payment_info['branch_name'],
                "bank_name" => $payment_info['bank_name'],
            ]);
        }
        foreach ($products as $key => $product) {
            $stock = new StockIn();
            $stock->purchase_id =  $purchase->id;
            $stock->item_id = $product['item_id'];
            $stock->quantity = $product['quantity'];
            $stock->save();

        }

        DB::commit();
        // $request->session()->flash('success_message', 'Product purchase order successfull');
        // Toastr::success("Purchase Successfull");
        return back();
    }catch (\Exception $ex)
    {
        DB::rollback();
        dd($ex);
    }

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Purchase  $purchase
     * @return \Illuminate\Http\Response
     */
    public function show(Purchase $purchase)
    {
        return view('purchase.show',[
            'purchase' => $purchase,
            'page_title'=> 'Purchase Details'
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Purchase  $purchase
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data=[
            'purchase'=> Purchase::with('items.item.category','items.item.unit','payment_new')->find($id),
            'suppliers' => Supplier::all(),
            'categories' => ItemCategory::all(),
            'branches' => Branch::all(),
        ];
        // dd($data);
        return view('purchase.edit',$data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Purchase  $purchase
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Purchase $purchase)
    {
        // dd($request->all());
        DB::beginTransaction();
        try{

            if($request->payment_method_id=="Cheque"){

                 if($request->cheque_number==null || $request->account_number==null ||  $request->brance_number==null || $request->bank_name==null)
                 {
                    Toastr::error("Please Add All Cheque Information");
                    return back();
                 }
            }

            $serialNumbers=SerialNumber::where('purchase_id',$request->id)->where('status',"used")->first();
            if($serialNumbers){
                Toastr::info("Allready Use Serial Number Of this Purhase");
                return back();
            }
            if($request->productId==null){

                Toastr::info("Please Add Atleast One Item");
                return back();
            }


            $purchase = Purchase::find($request->id);

            $privious_paymentMethod= $purchase->payment_method;

            $purchase->remark = $request->remark;
            $purchase->supplier_id = $request->supplier_id;
            $purchase->branch_id = $request->branch_id;
            $purchase->subtotal = $request->payable;
            $purchase->paid = $request->paid;
            $purchase->payment_method = $request->payment_method_id;
            $purchase->voucher_no = $request->voucher_no;
            $purchase->due = $request->due;
            $purchase->updator_user_id  = Auth::id();
            $purchase->save();
            PurchaseItem::where('purchase_id',$request->id)->delete();

            $len= sizeof($request->productId);

            for($i=0;$i<$len;$i++) {
                $item = new PurchaseItem();
                $item->purchase_id = $purchase->id;
                $item->item_id = $request->productId[$i];
                $item->quantity = $request->quantity[$i];
                $item->buying_price =$request->price[$i];
                $item->save();

            }

            StockIn::where('purchase_id',$request->id)->delete();
            for($i=0;$i<$len;$i++) {
                $stock = new StockIn();
                $stock->purchase_id =  $purchase->id;
                $stock->item_id = $request->productId[$i];
                $stock->quantity =$request->quantity[$i];
                $stock->save();

            }

            Payment::where('purchase_id',$request->id)->delete();
            SerialNumber::where('purchase_id',$request->id)->delete();
            if ($request->payment_method_id == "Cheque") {
                Payment::create([
                    "purchase_id" => $purchase->id,
                    "amount" => $request->paid,
                    "cheque_number" => $request->cheque_number,
                    "account_number" => $request->account_number,
                    "branch_name" => $request->brance_number,
                    "bank_name" => $request->bank_name,
                ]);
            }


            // dd('comes');
            DB::commit();
            Toastr::success("Purchase Update Successfull");
            return redirect()->route('purchase.index');
        }catch (\Exception $e){
            DB::rollBack();
            dd($e);
            Toastr::error("Some Problem happen");
        }

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Purchase  $purchase
     * @return \Illuminate\Http\Response
     */
    public function destroy(Purchase $purchase)
    {
        //
    }


    public function getItemBySearchKeyword($keyword)
    {

        $items = Item::where('name', 'LIKE', $keyword . '%')
            ->orWhere('code', 'LIKE', $keyword . '%')
            ->get();

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

    }
    public function getItemByCategoryId($category_id)
    {

        $items = Item::where('category_id', $category_id)
            ->get();

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

    }
    public function getItemById($id)
    {

        $item = Item::with('unit', 'category')->where('id', $id)
            ->first();
        return response()->json($item);

    }

    public function serialNoAdd($purchase_id)
    {
        // dd('comes');
        $data=[
            'items'=>Purchase::with('items.itemWithSerialNumber')->find($purchase_id),
            'url'=>"serial-no-add/{$purchase_id}",
        ];
        //  dd($data);
        return view('purchase.serial_no_add',$data);
    }

    public function showSerialNo($id)
    {
        // dd('comess');
        $data=[
            'serial_no'=>SerialNumber::where('item_id',$id)->where('status','notused')->paginate('100'),
        ];
        return view('purchase.show_serial_no',$data);
    }

    public function addItemCard(Request $request)
    {
        $data= [
            'item'=> Item::with('category','unit')->find($request->id),
        ];
        return $data;
    }
}
