<?php

namespace App\Http\Controllers\StockInventory\purchase;

use App\Model\account\JournalModel;
use App\Model\payment\PaymentDetailModel;
use App\Model\payment\PaymentModel;
use App\Model\product\ProductUnitModel;
use App\Model\stock_inventory\StockModel;
use App\Model\setup\WarehouseModel;
use App\User;
use Dotenv\Exception\ValidationException;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use DB;

use Auth;

use DataTables;

use App\Model\people\SupplierModel;

use App\Model\stock_inventory\PurchaseDetailsModel;

use App\Model\stock_inventory\PurchaseModel;

use App\Fun\Fun;
use Illuminate\Support\Facades\Gate;

class PurchaseController extends Controller

{

    function __construct()
    {
        $this->middleware('permission:Purchase List', ['only' => ['index']]);
        $this->middleware('permission:Purchase show', ['only' => ['show']]);
        Fun::lang();
    }
    public function index(Request $request)
    {

        if ($request->ajax()) {
            Fun::lang();
            $search = $request->input('search.value');
            $type = $request->type;
            $supplier = $request->supplier;
            $status = $request->status;
            $warehouse = $request->warehouse;
            $user_id = $request->user_id;

            $user_role = Auth::user()->branch_id;
            $user_role = findBranch($user_role);
            $user_role = $user_role?$user_role->main:0;
            $branch_warehouse = WarehouseModel::where('branch_id',Auth::user()->branch_id)->pluck('id');
            $data = PurchaseModel::where(['nso007_purchases.status' => 1])
                ->where(function ($q) use ($request) {
                    if ($request['from_date']&&$request['to_date']) {
                        $q->where('nso007_purchases.purchase_date', '>=', sDate($request['from_date']).' 00:00:00');
                        $q->where('nso007_purchases.purchase_date', '<=', sDate($request['to_date']).' 23:59:59');
                    }
                })
                ->where(function ($query) use ($type) {
                    if ($type) {
                        $query->Where('nso007_purchases.type', $type);
                    }
                })
                ->where(function ($query) use ($user_id) {
                    if ($user_id) {
                        $query->Where('nso007_purchases.user_id', $user_id);
                    }
                })
                ->where(function ($query) use ($user_role,$branch_warehouse) {
                    if ($user_role!==1) {
                        $query->Where('nso007_purchases.warehouse_id',$branch_warehouse);
                    }
                })
                ->where(function ($query) use ($supplier) {
                    if ($supplier) {
                        $query->where('nso007_purchases.supplier_id', $supplier);
                    }
                })
                ->where(function ($query) use ($warehouse) {
                    if ($warehouse) {
                        $query->where('nso007_purchases.warehouse_id', $warehouse);
                    }
                })
                ->where(function ($query) use ($status) {
                    if ($status) {
                        $query->where('nso007_purchases.payment_status',$status);
                    }
                })
                ->where(function ($query) use ($search) {
                    if($search)
                    $query->Where('nso007_purchases.invoice_number', 'LIKE', '%' . $search . '%');
                })
                ->orderBy('nso007_purchases.id', 'DESC');
            return Datatables::of($data)

                ->editColumn('user_id', function ($purchase) {
                    $user = findUser($purchase->user_id);
                    return $user?$user->name:'';
                })
                ->editColumn('warehouse_id', function ($purchase) {
                    $warehouse = findWarehouse($purchase->warehouse_id);
                    return $warehouse?$warehouse->warehouse_name:'';
                })
                ->addColumn('supplier_name', function ($purchase) {
                    $purchase->supplier = findSupplier($purchase->supplier_id);
                    return $purchase->supplier->supplier_name??'';
                })
                ->addColumn('supplier_phone', function ($purchase) {
                    return $purchase->supplier->supplier_phone??'';
                })
                ->addColumn('paid', function ($purchase) {
                    $total_paid = $purchase->paid;
                    return findCurrency($purchase->currency_id)->symbol . number_format($total_paid, 2);
                })
                ->addColumn('remain', function ($purchase) {
                    $total = getPurchaseTotal($purchase);
                    $remain = $total - $purchase->paid;
                    return findCurrency($purchase->currency_id)->symbol  . number_format(($remain > 0 ? $remain : 0), 2);
                })
                ->addColumn('total', function ($purchase) {
                    return findCurrency($purchase->currency_id)->symbol  . number_format(getPurchaseTotal($purchase), 2);
                })
                ->addColumn('purchase_date', function ($purchase) {
                    return myDate($purchase->purchase_date);
                })
                ->editColumn('payment_status', function ($sales) {
                    return checkPaymentStatus($sales->payment_status);
                })
                ->editColumn('type', function ($sales) {
                    return  __('administrator.'.$sales->type) ;
                })
                ->addColumn('action', function ($purchase) {
                    if(Gate::check('Purchase show'))
                    {
                        $btn_show =  '<a data-href="' . route("purchases.show", $purchase->id) . '" title="Show" class="button_info btn_purchase_invoice_public">' . __('administrator.show') . '</a>';
                        $btn_show .=  '<a data-href="' . route("purchases.delete", $purchase->id) . '" title="Delete" class="button_danger btn_delete">' . __('administrator.delete') . '</a>';
                    }else{
                        $btn_show = '';
                    }
                    return $btn_show;
                })
                ->addIndexColumn()
                ->rawColumns([ 'action', 'paid', 'remain','payment_status','total','supplier_name','supplier_phone'])
                ->make(true);
        }

        $purchase = PurchaseModel::groupBy('supplier_id')->pluck('supplier_id');
        $user = PurchaseModel::groupBy('user_id')->pluck('user_id');
        $supplier = getSupplier(null,$purchase)->pluck('supplier_name','id');
        $user = User::whereIn('id',$user)->pluck('name','id');
        $type = PurchaseModel::groupBy('type')->pluck('type','type');
        foreach($type as $key =>$row){
            $type[$key]= __('administrator.'.$row);
        }
        return view('stock-inventory.purchases.index',compact('supplier','type','user'));
    }

    public function destroy($id)
    {
            return DB::transaction(function() use ($id) {
                $master = PurchaseModel::find($id);
                $detail = PurchaseDetailsModel::where('purchase_id',$id)->get();
                foreach ($detail as $key => $value) {
                    $qty_per_unit = 1;
                    $where = ['barcode' => $value->barcode,'type' => $master->type,'warehouse_id' => $master->warehouse_id,'product_id'=>$value->product_id];
                    if($master->type==='material'){
                        $qty_per_unit = ProductUnitModel::where(['barcode'=>$value->barcode,'product_id'=>$value->product_id])->first()->qty_per_unit??1;
                        $where = array_merge($where,['product_id'=>$value->product_id]);

                    }
                    if($master->type==='fabric'){
                        $qty_per_unit = $value->qty_per_unit;
                        $where = array_merge($where,['qty_per_unit'=>$qty_per_unit]);
                    }
                    $stock = StockModel::where($where)->first();
                    if($stock){
                        $cut = $qty_per_unit*$value->qty;
                        if($stock->stock_qty>$cut){
                            $stock->stock_qty -= $cut;
                        }else{
                            $stock->stock_qty = 0;
                        }
                        $stock->save();
                    }
                }
                $payment = PaymentModel::where('invoice_id',$id)->where('type','purchase')->first();
                PaymentDetailModel::where('payment_id',$payment->id)->delete();
                $payment->delete();
                JournalModel::where(['transaction_type'=>'Purchase','journal_referenceid'=>$id])->delete();
                $master->delete();
                PurchaseDetailsModel::where('purchase_id',$id)->delete();
                return response()->json(['status'=>'ok']);
            });

    }

    public function show($id)

    {

        // Purchases

        $purchases = PurchaseModel::find($id);

        $supplier_id = $purchases->supplier_id;


        // Find Supplier Type

        $supplier_type = SupplierModel::join('nso007_supplier_type', 'nso007_supplier_type.id', '=', 'nso007_suppliers.supplier_type_id')
            ->where('nso007_suppliers.id', $supplier_id)
            ->first();
        // Purchase Details

        $purchase_details = PurchaseDetailsModel::select('nso007_suppliers.*', 'nso007_purchase_details.*', 'nso007_products.product_name')
            ->leftJoin('nso007_purchases', 'nso007_purchases.id', '=', 'nso007_purchase_details.purchase_id')
            ->leftJoin('nso007_products', 'nso007_products.id', '=', 'nso007_purchase_details.product_id')
            ->leftJoin('nso007_suppliers', 'nso007_suppliers.id', '=', 'nso007_purchases.supplier_id')
            ->where(['nso007_purchase_details.status' => 1,'nso007_purchase_details.purchase_id' => $id])
            ->get();

        return view('stock-inventory.purchases.show', compact('purchase_details', 'purchases', 'supplier_type'))->render();

    }

}

