<?php

namespace App\Http\Controllers\Project;

use App\Http\Controllers\Controller;
use App\Models\Admin\User;
use App\Traits\LoginTrait;
use App\Traits\Permissions_trait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Spatie\Activitylog\Models\Activity;
use App\Models\Project\Invoice_main;
use App\Models\Project\Invoice_detail;
use App\Models\Project\Alerts;
use Illuminate\Support\Facades\Validator;


class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    use Permissions_trait,LoginTrait;
    var $url;
    public function __construct()
    {
        $this->middleware('auth');
        $this->url = request()->path();
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        // if(!$this->Permissions_trait('view',$this->url)):
        //     abort(403,'Permission denied..');
        // endif;
        activity('Home Page Visit')
        ->causedBy(Auth::user())
        ->performedOn(new User() )
        ->tap(function (Activity $activity) {
            $activity->route_link = $this->url;
        })
        ->log('Home Page Visited by ' . Auth::user()->name);
        $data=array();
        $data['username'] = ucfirst(Auth::user()->username);
        /*counts*/ /*status counts*/
        $data['dataCount1'] = User::all()->where('type','user')->count();
        $data['dataCount1_active'] = User::all()->where('type','user')->where('status',1)->count();
        $data['dataCount1_unactive'] = User::all()->where('type','user')->where('status',2)->count();
        $data['dataCount1_deleted'] = User::all()->where('type','user')->where('status',0)->count();

        $data['dataCount2'] = User::all()->where('type','business')->count();
        $data['dataCount2_active'] = User::all()->where('type','business')->where('status',1)->count();
        $data['dataCount2_unactive'] = User::all()->where('type','business')->where('status',2)->count();
        $data['dataCount2_deleted'] = User::all()->where('type','business')->where('status',0)->count();

        $data['dataCount3'] = User::all()->where('type','admin')->count();
        $data['dataCount3_active'] = User::all()->where('type','admin')->where('status',1)->count();
        $data['dataCount3_unactive'] = User::all()->where('type','admin')->where('status',2)->count();
        $data['dataCount3_deleted'] = User::all()->where('type','admin')->where('status',0)->count();

        /*tables*/
        $data['post1'] = User::where('type','user')->limit(10)->get();
        $data['post2'] = User::where('type','business')->limit(10)->get();
        $data['post3'] = User::where('type','admin')->limit(10)->get();
        
        if (Auth::user()->type == "2") {
            $inv_id = 0;
            $vendor_id = Auth::user()->id;
            $data['tax_value'] = 15;
            $data['cart_data'] =   DB::select(DB::raw("select a.id,a.user_id,(SELECT name FROM user_detail WHERE uid = a.user_id) AS member_name,a.total_amount,a.discount_invoice,a.tax,a.net_total FROM invoice_main a
            WHERE
            a.vendor_id = '$vendor_id' AND a.member_selected = 1 AND a.status = '3'"));
            $data_inv = $data['cart_data'];
            // 
            $data['inv_id'] = $data['user_id'] = 0;
            foreach ($data_inv as $inv){
                $inv_id = $inv->id;
                $data['inv_id'] = $inv->id;
                $data['user_id'] = $inv->user_id;
            } 
        
            $data['cart_items'] =   DB::select(DB::raw("select a.id,a.product_id,a.name,a.qty,a.unit,a.price,a.discount,a.amount,a.status FROM invoice_detail a
            WHERE a.invoice_main_id = '$inv_id' "));
            // invoice members
            $data['members_list'] =  DB::table('members')
		    ->join('user_detail', 'members.user_id', '=', 'user_detail.uid')
		    ->join('users', 'members.user_id', '=', 'users.id')
		    ->select('members.user_id', 'user_detail.name','users.mobile')
		    ->where('members.vendor_id', $vendor_id)
		    ->get();
            // invoices products
            $data['products_list']=[];
            if (!empty($data['user_id'])) {
                $data['products_list'] =  DB::table('products')
                ->select('products.id', 'products.name','products.price','products.barcode')
                ->where('products.vendor_id', $vendor_id)
                ->get();
            }
            // return to views
            return view('sarf/pos.dashboard',compact('data'));
        } else {
            return view('sarf.dashboard',compact('data'));
        }
    }
	
    //add member to invoice
	public function invoice_member_add($member_id){
		$id = Auth::user()->id;
		$ar['pending'] = DB::select(DB::raw("SELECT a.id,a.status from invoice_main a WHERE a.vendor_id = '$id' AND a.user_id = '$member_id' AND a.status = 3" ));
		if(empty($ar['pending'])){	
            $post = new Invoice_main;
            $post->vendor_id = $id;
            $post->user_id = $member_id;
            $post->member_selected = 1;
            $post->status = 3;
            $msg = $post->save();
            if ($msg) {
                $invoice_main_id = $post->id;
                DB::table('invoice_main')->where('vendor_id',$id)->where('id',  '!=' , $invoice_main_id)->where('status',3)->update(array('member_selected' => 0));
                echo  json_encode(array('text' => 'added successfuly', 'cls' => 'success'));
            } else {
                echo  json_encode(array('text' => 'not add', 'cls' => 'error'));
            }
		}else{
			DB::table('invoice_main')->where('vendor_id',$id)->where('user_id', $member_id)->where('status',3)->update(array('member_selected' => 1));
			DB::table('invoice_main')->where('vendor_id',$id)->where('user_id',  '!=' , $member_id)->where('status',3)->update(array('member_selected' => 0));
            echo  json_encode(array('text' => 'member_invoice_already_pending', 'cls' => 'success'));
		}
	}

    //add product to invoice
	public function invoice_product_add(Request $request){
		$post = new Invoice_detail;
        $post->product_id = $request->product_id;
        $post->price = $request->price;
        $post->name = $request->product_name;
        $post->invoice_main_id = $request->invoice_main_id;
        $post->qty = $request->quantity;
        $post->unit = $request->unit;
        $post->amount = $request->price*$request->quantity;
        $post->offer_id = $request->offer_id;
        $msg = $post->save();
        if ($msg) {
            echo  json_encode(array('text' => 'items added', 'cls' => 'success'));
        } else {
            echo  json_encode(array('text' => 'not added', 'cls' => 'error'));
        }
	}

    public function extraDiscount(Request $request)
    {
        $net_total=$discount=0;
        $discount = $request->net_total*$request->exDiscount/100;
        $net_total = $request->net_total-$discount;
        return json_encode(array( 
            'net_total'=>$net_total,
        ));
    }

    public function generate_invoice(Request $request){
        $id = Auth::user()->id;
        if (isset($request->invoice_id) && isset($request->note)) {
            $user_id = getAny('user_id', 'invoice_main', 'id', $request->invoice_id);
            if(isset(DB::table('members')->where('vendor_id', $id )->where('user_id', $user_id)->first()->expense_type)){
                $vendor_type = DB::table('members')->where('vendor_id', $id )->where('user_id', $user_id)->first()->expense_type;	
            }else{
                $vendor_type = 0;	    
            }
            $post =  Invoice_main::find($request->invoice_id);
            $post->created_at = Date('Y-m-d H:i:s');
            $post->invoice_note = $request->note;
            $post->total_amount = $request->total_amount;
            $post->discount_invoice = $request->discount;
            $post->extra_discount = $request->extra_discount;
            $post->tax = $request->tax_total;
            $post->net_total = $request->net_amount;
            $post->expense_type = $vendor_type;
            $post->status = 1;
            $msg = $post->save();
            if ($msg) {
                $post2 = new Alerts;
                $post2->user_id = getAny('user_id', 'invoice_main', 'id', $request->invoice_id);
                $post2->vendor_id = getAny('vendor_id', 'invoice_main', 'id', $request->invoice_id);
                $post2->inv_offer_id = $request->invoice_id;
                $post2->title = "Invoice generated";
                $post2->discription = $request->note;
                $post2->alert_type = 1;
                $msg2 = $post2->save();
                return redirect()->back()->with('success',trans('generated successfully'))->withInput();
            } else {
                return redirect()->back()->with('error','Somthing went wrong')->withInput();
            }
        } else {
            return redirect()->back()->with('error','Please check your data.')->withInput();
        }
	}
    
    // delte item product invoice
    public function item_destroy($id, $inv_id)
    {
        if (isset($id) && !empty($id)) {
            $post = Invoice_detail::where('product_id',$id)->where('invoice_main_id',$inv_id)->delete();
            if ($post) {
                echo  json_encode(array('text' => 'Delete successfully', 'cls' => 'success'));
            } else {
                echo  json_encode(array('text' => 'Error', 'cls' => 'error'));
            }
        }
    }

    public function member_destroy()
    {
        $id = Auth::user()->id;
        if (isset($id) && !empty($id)) {
            $msg = DB::table('invoice_main')->where('vendor_id',$id)->where('status',3)->update(array('member_selected' => 0));
            if ($msg) {
                echo  json_encode(array('text' => 'member_removed_sussessfully', 'cls' => 'success'));
            } else {
                echo  json_encode(array('text' => 'fail_to_remove_member', 'cls' => 'error'));
            }
        }
    }
	
    // edit item form
    public function edit_item_form(Request $request)
    {
        $post = Invoice_detail::where('product_id',$request->id)->where('invoice_main_id',$request->invoice_main_id)->first();
        return view('sarf/pos.edit_item_form',compact('post'));
    }

    //add product to invoice
	public function invoice_product_update(Request $request){
        $data = [
            'price' => $request->price,
            'qty' => $request->quantity,
            'unit' => $request->unit,
            'amount' => $request->price*$request->quantity,
        ];
		$post = Invoice_detail::where('product_id',$request->product_id)
            ->where('invoice_main_id',$request->invoice_main_id)
            ->update($data);
        if ($post) {
            echo  json_encode(array('text' => 'items updated', 'cls' => 'success'));
        } else {
            echo  json_encode(array('text' => 'not updated', 'cls' => 'error'));
        }
	}

    // simple invoice code
    public function simple_invoice()
    {
        $vendor_id = Auth::user()->id;
        $data['members_list'] =  DB::table('members')
        ->join('user_detail', 'members.user_id', '=', 'user_detail.uid')
        ->join('users', 'members.user_id', '=', 'users.id')
        ->select('members.user_id', 'user_detail.name','users.mobile')
        ->where('members.vendor_id', $vendor_id)
        ->get();
        return view('sarf/pos.simple_invoice',compact('data'));
    }

    public function generate_simple_invoice(Request $request)
    {
        $vendor_id = Auth::user()->id;
        $validator = Validator::make($request->all(), [
            'member_id' => 'required|integer',
            'net_total' => 'required|integer',
            'invoice_note' => 'required|max:255',
        ]);
        
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        } else {
            $post = new Invoice_main;
            $post->user_id = $request->member_id;
            $post->vendor_id = $vendor_id;
            $post->invoice_note = $request->invoice_note;
            $post->net_total = $request->net_total;
            $post->date = Date('Y-m-d');
            $post->created_at = Date('Y-m-d H:i:s');
            $post->status = 1;
            $post->invoice_type = 2;
            $msg = $post->save();
            if ($msg) {
                $post2 = new Alerts;
                $post2->user_id = $request->member_id;
                $post2->vendor_id = $vendor_id;
                $post2->inv_offer_id = $post->id;
                $post2->title = "Simple Invoice generated";
                $post2->discription = $request->invoice_note;
                $post2->alert_type = 1;
                $msg2 = $post2->save();
                return redirect()->back()->with('success',trans('generated successfully'))->withInput();
            } else {
                return redirect()->back()->with('error','Somthing went wrong')->withInput();
            }
        }
    }
}
