<?php
namespace App\Http\Controllers\Admin\accounting;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Helpers\LogActivity;
use App\Models\{
    User,
    Role,
    School,
    Plan
};
use App\Models\accounting\{
    AccountLedger,
    AccountLedgerGroup,
    AccountBank,
    AccountItem,
    AccountItemUnit,
    AccountItemCategory
};
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Exports\ItemExport;
use App\Imports\ItemImport;
use Maatwebsite\Excel\Facades\Excel;
use Validator;

class ItemController extends Controller
{
    protected $admin_id;
    protected $school_id, $res,$allData,$data,$validate;
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            // fetch session and use it in entire class with constructor
            if (session()->get('loggedIn')['user_type'] == 'admin') {
                $this->admin_id = session()->get('loggedIn')['id'];
                $this->school_id = School::where("admin_id",$this->admin_id)->pluck("id")->first();
            } else {
                $this->admin_id = session()->get('loggedIn')['admin_id'];
                $this->school_id = School::where("admin_id",$this->admin_id)->pluck("id")->first();
            }
         
            return $next($request);
        });
    }

    public function exportItems()
    {        
        $filename = "items.xlsx";
        return Excel::download(new ItemExport($this->admin_id),$filename);
        
    }

    public function importItems(Request $request)
    {
        $file = $request->file('excel_file');        

        Excel::import(new ItemImport($this->admin_id), $file);

        return response()->json(["message"=>"success"],200);
    }

     // Display all employees
     public function index()
     {
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'account';
        $data['superadminSubMenu'] = 'item';

        $search = isset($_GET["search"]) ? $_GET["search"] : null;
        $name = isset($_GET["name"]) ? $_GET["name"] : null;
        $mobile = isset($_GET["mobile"]) ? $_GET["mobile"] : null;
        $email = isset($_GET["email"]) ? $_GET["email"] : null;
        $doj = isset($_GET["doj"]) ? $_GET["doj"] : null;
        $dob = isset($_GET["dob"]) ? $_GET["dob"] : null;
       $department = isset($_GET["department"]) ? $_GET["department"] : null;
        $designation = isset($_GET["designation"]) ? $_GET["designation"] : null;
        $start_date = isset($_GET["start_date"]) ? $_GET["start_date"] : null;
        $end_date = isset($_GET["end_date"]) ? $_GET["end_date"] : null;
       
       
        $query = AccountItem::where('account_items.admin_id',$this->admin_id)
        ->leftJoin("account_item_units","account_item_units.id","=","account_items.unit_id")
        ->leftJoin("account_item_categories","account_item_categories.id","=","account_items.category_id");
        
        

        if($search)
        {
            $query->where('account_items.name', 'LIKE', '%' . $search . '%');
            
        }
       
        $data['items'] = $query->select(
            "account_items.*",
            "account_item_units.name as unit_name",
            "account_item_categories.name as cat_name"
        )->orderBy('created_at','desc')->paginate(10);

        

        return view('accounting.item.list',$data);
     }
 
     // Show the form to create a new product
     public function create()
     {
       

        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'account';
        $data['superadminSubMenu'] = 'item';
        $data['categories'] = AccountItemCategory::where("admin_id",$this->admin_id)->get();
        $data['units'] = AccountItemUnit::where("admin_id",$this->admin_id)->get();
        $data["taxes"] = DB::table("account_tax_slabs")->get();
             

        return view('accounting.item.add',$data);
     }
 
     // Store a new product in the database
     public function store(Request $request)
     {
       
        $this->allData = $request->all();       
       
        //return $this->allData;
        $this->validate = Validator::make($request->all(),[
            "name"=>"required"
        ]);

        if($this->validate->fails())
        {
            return back()->withErrors($this->validate)->withInput();
        }

        if(isset($request->item_id) && !empty($request->item_id))
        {
            unset($this->allData["item_id"]);
            unset($this->allData["_token"]);
            
            $this->res = AccountItem::where("id",$request->item_id)->update($this->allData);

            if($this->res)
            {
                return back()->with("success","Item update successfully !");
            }
            return back()->with("error","failed !");
        }

        $this->allData["admin_id"] = $this->admin_id;
        $this->allData["sold"] = 0;

        $this->res = AccountItem::create($this->allData);

        if($this->res)
        {
            return back()->with("success","Item add successfully !");
        }
        return back()->with("success","failed !");
      
        
     }
 
     // Show the form to edit an existing product
     public function edit($id)
     {
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'account';
        $data['superadminSubMenu'] = 'bank';

        $data['item'] = AccountItem::where("id",$id)->first(); 
        
        $data['categories'] = AccountItemCategory::where("admin_id",$this->admin_id)->get();
        $data['units'] = AccountItemUnit::where("admin_id",$this->admin_id)->get();
        $data["taxes"] = DB::table("account_tax_slabs")->get();

        return view('accounting.item.edit',$data); 
     }
 
     
     
     // Delete a product
     public function delete(Request $request)
     {
       // return $request->id;

         $this->res = AccountItem::where('id',$request->id)->delete();
         if($this->res)
         {
            $logMessage = $request->rolename . ' Item delete successfully!';
			    LogActivity::addToLog($logMessage);
                
            
            return response()->json(["message"=>"success"],200);
         }
         
            return response()->json(["message"=>"failed"],424);
         
     }

     public function deleteMultiple(Request $request)
     {
        
        $this->res = AccountItem::whereIn('id',$request->ids)->delete();
        if($this->res)
        {
           $logMessage = $request->rolename . ' Item delete successfully!';
               LogActivity::addToLog($logMessage);
               
           
           return response()->json(["message"=>"success"],200);
        }
        
           return response()->json(["message"=>"failed"],424);
     }

     //category code

     public function categoryIndex()
     {
        
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'master';
        $data['superadminSubMenu'] = 'category';

        $search = isset($_GET["search"]) ? $_GET["search"] : null;

        
        $query = AccountItemCategory::where("admin_id",$this->admin_id);

        if($search)
        {
            $query->where("name","LIKE","%".$search."%");
        }
        $data['categories'] = $query->orderBy("created_at","DESC")->paginate(10);
        
    
        return view('accounting.master.category.list',$data);
     }

     public function addCategory(Request $request)
     {
        
        $this->allData = $request->all();       
       
        //return $this->allData;
        $this->validate = Validator::make($request->all(),[
            "name"=>"required"
        ]);

        if($this->validate->fails())
        {
            return back()->withErrors($this->validate)->withInput();
        }

        if(isset($request->category_id) && !empty($request->category_id))
        {
            unset($this->allData["category_id"]);
            unset($this->allData["_token"]);
            $this->res = AccountItemCategory::where("id",$request->category_id)->update($this->allData);

            if($this->res)
            {
                return back()->with("success","Category update successfully !");
            }
            return back()->with("error","failed !");
        }

        $this->allData["admin_id"] = $this->admin_id;

        $this->res = AccountItemCategory::create($this->allData);

        if($this->res)
        {
            return back()->with("success","Category add successfully !");
        }
        return back()->with("success","failed !");
     }

     public function deleteCategory(Request $request)
     {
        
        $this->res = AccountItemCategory::where('id',$request->category_id)->delete();
        if($this->res)
        {
            AccountItem::where("category_id",$request->category_id)->update(["category_id"=>0]);
           $logMessage = $request->rolename . ' Category delete successfully!';
               LogActivity::addToLog($logMessage);
               
           
           return response()->json(["message"=>"success"],200);
        }
        
           return response()->json(["message"=>"failed"],424);
     }

     public function multipleDeleteCategory(Request $request)
     {
        
        $this->res = AccountItemCategory::whereIn('id',$request->ids)->delete();
        if($this->res)
        {
            AccountItem::whereIn("category_id",$request->ids)->update(["category_id"=>0]);
           $logMessage = $request->rolename . ' Category delete successfully!';
               LogActivity::addToLog($logMessage);
               
           
           return response()->json(["message"=>"success"],200);
        }
        
           return response()->json(["message"=>"failed"],424);
     }
     //unit of measure code

     public function unitIndex()
     {
        
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'master';
        $data['superadminSubMenu'] = 'unit';

        $search = isset($_GET["search"]) ? $_GET["search"] : null;

        
        $query = AccountItemUnit::where("admin_id",$this->admin_id);

        if($search)
        {
            $query->where("name","LIKE","%".$search."%")
            ->orWhere("short_name","LIKE","%".$search."%");
        }
        $data['units'] = $query->orderBy("created_at","DESC")->paginate(10);
        
    
        return view('accounting.master.unit.list',$data);
     }

     public function addUnit(Request $request)
     {
        
        $this->allData = $request->all();       
       
        //return $this->allData;
        $this->validate = Validator::make($request->all(),[
            "name"=>"required"
        ]);

        if($this->validate->fails())
        {
            return back()->withErrors($this->validate)->withInput();
        }

        if(isset($request->unit_id) && !empty($request->unit_id))
        {
            unset($this->allData["unit_id"]);
            unset($this->allData["_token"]);
            $this->res = AccountItemUnit::where("id",$request->unit_id)->update($this->allData);

            if($this->res)
            {
                return back()->with("success","Unit update successfully !");
            }
            return back()->with("error","failed !");
        }

        $this->allData["admin_id"] = $this->admin_id;

        $this->res = AccountItemUnit::create($this->allData);

        if($this->res)
        {
            return back()->with("success","Unit add successfully !");
        }
        return back()->with("success","failed !");
     }

     public function deleteUnit(Request $request)
     {
        
        $this->res = AccountItemUnit::where('id',$request->category_id)->delete();
        if($this->res)
        {
            
           $logMessage = $request->rolename . ' Unit delete successfully!';
               LogActivity::addToLog($logMessage);
               
           
           return response()->json(["message"=>"success"],200);
        }
        
           return response()->json(["message"=>"failed"],424);
     }

     public function multipleDeleteUnit(Request $request)
     {
        
        $this->res = AccountItemUnit::whereIn('id',$request->ids)->delete();
        if($this->res)
        {
            
           $logMessage = $request->rolename . 'Unit delete successfully!';
            LogActivity::addToLog($logMessage);               
           
           return response()->json(["message"=>"success"],200);
        }
        
           return response()->json(["message"=>"failed"],424);
     }

     

}
