<?php

namespace App\Http\Controllers\Inventory;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Inventory\Item;
use App\Inventory\InventoryCategory;
use App\Inventory\InventoryUnit;
use App\Inventory\ProjectStock;
use App\Inventory\Stock;
use App\Branch;
use App\Http\Requests\InventoryRequests\ItemRequest;
use Illuminate\Contracts\Encryption\DecryptException;

use Crypt;
class ItemController extends Controller
{


  public function viewAllitems()
  {
    $item = new Item;
    $branch = new Branch;
    $category = new InventoryCategory;
    $unit     = new InventoryUnit;
    $type = ['Service'];
    $type2 = ['Product'];

      $service_list          = $item->getItemListByType($type);
      $product_list          = $item->getItemListByType($type2);
      $product_category_list = $category->getCategoryListByType(['Product']);
      $service_category_list = $category->getCategoryListByType(['Service']);

      $unit_list             = $unit->getAllInventoryUnit();

      $branch  =  $branch->getBranchList();


        return view('inventory_module.item.manage_item',
        [
          'branch'                    => $branch,
          'service_list'              => $service_list,
          'product_list'              => $product_list,
          'product_category_list'     => $product_category_list,
          'service_category_list'     => $service_category_list,
          'unit_list'                 => $unit_list,
        ]
    );

  }

    public function storeProduct(ItemRequest $request)
    {
    	try
        {

    	 $item = new Item;



         $form_collect            = $request->input();

         if($form_collect['product_minimum'] > $form_collect['product_maximum'])
         {
                   parent::errorMessage('Product minimum amount  must be less than product maximum.');
                   return redirect()->back();
         }

         $form_collect['product_category'] = decrypt($form_collect['product_category']);
         $form_collect['product_unit']     = decrypt($form_collect['product_unit']);
         $form_collect['type']    = 'Product';
         //$form_collect['branch_id']    = decrypt($form_collect['project']);

         $item_cat = new InventoryCategory;
         $item_cat = $item_cat->getbyID($form_collect['product_category']);
         $get_items_count = Item::where('inventory_category_id', $form_collect['product_category'])->count();
         $get_items = Item::where('inventory_category_id', $form_collect['product_category'])->orderBy('created_at','desc')->first();
         if($get_items_count == 0)
         {
           $cc = (int) $item_cat->category_code;

           $form_collect['product_code'] = $cc+1;
         }
         else{
           $cc = (int) $get_items->code;
           $form_collect['product_code'] = $cc+1;
         }


         $curr_product         = $item->storeProduct($form_collect);

        if(isset($curr_product->id))
        {
            parent::setLogMessage('Product"'.$curr_product->name.'" has been added');

            parent::successMessage('Product has been added.',parent::getLogMessage());
        }

        }
      catch (DecryptException $e)
        {

        }

        return redirect('items');
    }
    public function getItemDetails($id,$unit_id)
    {
        try
        {


            if(\Request::ajax())
            {
                $data = [];

                $item = new Item;
                $unit = new InventoryUnit;

                $item_id = decrypt($id);

                $curr_item = $item->getItemById($item_id);

                if(isset($curr_item->id))
                {
                    $current_unit      = $unit->getInventoryUnitById(decrypt($unit_id));


                    $unit_list         = $unit->getAllInventoryUnit();
                    $data['item_name'] = $curr_item->name;
                    $data['item_code'] = $curr_item->code;

                    $data['item_id']   = Crypt::encrypt($curr_item->id);

                    $data['unit_list'] = '<option value="'.Crypt::encrypt(0).'">Select Unit</option>';

                    foreach ($unit_list as $rows)
                    {
                      if($rows->id == $current_unit->id)
                      {
                        $data['unit_list'].= '<option selected value="'.Crypt::encrypt($rows->id).'">'.$rows->name.'</option>';
                      }
                      else
                      {
                        $data['unit_list'] .= '<option value="'.Crypt::encrypt($rows->id).'">'.$rows->name.'</option>';
                      }


                    }



                }
             return $data;

            }

        }
        catch(DecryptException $e)
        {

        }
    }

    public function updateProduct(ItemRequest $request)
    {
        try
        {

         $item = new Item;

         $form_collect         = $request->input();
          if($form_collect['product_minimum'] > $form_collect['product_maximum'])
         {
                   parent::errorMessage('Product minimum amount must be less than product maximum.');
                   return redirect()->back();
         }

        $form_collect['product_category']    = decrypt($form_collect['product_category']);
         $form_collect['product_unit']    = decrypt($form_collect['product_unit']);
         $form_collect['product']         = decrypt($form_collect['product']);



         $curr_product = $item->updateProduct($form_collect);

        if(isset($curr_product->id))
        {
            parent::setLogMessage('Product"'.$curr_product->name.'" has been updated');

            parent::successMessage('Product has been updated.',parent::getLogMessage());
        }

        }

        catch (DecryptException $e)
        {

        }

        return redirect('items');
    }


    public function storeService(ItemRequest $request)
    {
    	try
        {

    	 $item = new Item;

         $form_collect         = $request->input();

         if($form_collect['service_minimum'] > $form_collect['service_maximum'])
         {
                   parent::errorMessage('Service minimum amount must be less than product maximum.');
                   return redirect()->back();
         }

       $form_collect['service_category'] = decrypt($form_collect['service_category']);
         $form_collect['service_unit']   = decrypt($form_collect['service_unit']);
         $form_collect['type'] = "Service";

         $item_cat = new InventoryCategory;
         $item_cat = $item_cat->getbyID($form_collect['service_category']);
         $get_items_count = Item::where('inventory_category_id', $form_collect['service_category'])->count();
         $get_items = Item::where('inventory_category_id', $form_collect['service_category'])->orderBy('created_at','desc')->first();
         if($get_items_count == 0)
         {
           $cc = (int) $item_cat->category_code;

           $form_collect['service_code'] = $cc+1;
         }
         else{
           $cc = (int) $get_items->code;
           $form_collect['service_code'] = $cc+1;
         }

         $curr_service         = $item->storeService($form_collect);

        if(isset($curr_service->id))
        {
            parent::setLogMessage('Service"'.$curr_service->name.'" has been added');

            parent::successMessage('Service has been added.',parent::getLogMessage());
        }

        }
      catch (DecryptException $e)
        {

        }

        return redirect('items');
    }

    public function updateService(ItemRequest $request)
    {
        try
        {

         $item = new Item;

         $form_collect         = $request->input();

           if($form_collect['service_minimum'] > $form_collect['service_maximum'])
         {
                   parent::errorMessage('Service minimum amount must be less than product maximum.');
                   return redirect()->back();
         }


        $form_collect['service_category']    = decrypt($form_collect['service_category']);
         $form_collect['service_unit']   = decrypt($form_collect['service_unit']);
         $form_collect['service']    = decrypt($form_collect['service']);

         $curr_service = $item->updateService($form_collect);

        if(isset($curr_service->id))
        {
            parent::setLogMessage('Service"'.$curr_service->name.'" has been updated');

            parent::successMessage('Service has been updated.',parent::getLogMessage());
        }

        }

        catch (DecryptException $e)
        {

        }

        return redirect('items');
    }

     public function getItemList($category,$type)
     {

        try
        {
             $item = new Item;

             $category = decrypt($category);


             $condition = ['type' => $type];
             $item_list = $item->getItemListByCategory($condition,$category);

             $view = '<option value="0">Select Item </option>';

             foreach($item_list as $rows)
             {
               $view .= '<option value="'.Crypt::encrypt($rows->id).'">'.$rows->name.'</option>';
             }
                return $view;

        }
        catch(DecryptException $e)
        {

        }

     }

     public function getitemid($id,$project)
     {

        try
        {
             $item = new Item;
             $stock = new Stock;

             $id = decrypt($id);
             $project = decrypt($project);

             $curr_item = $item->getItemById($id);
             $qty = $stock->getQty($id,$project);

             if($qty)
             {
            return response()->JSON(['item'=>$qty,'msg'=>"success"]);
            }
            else{
              return response()->JSON(['item'=>"",'msg'=>"error"]);
            }

        }
        catch(DecryptException $e)
        {

        }

     }


     public function getitemDetailsajax($id)
     {
        try
        {
          $id = decrypt($id);
             $item = Item::where('id',$id)->first();
                return $item;
        }
        catch(DecryptException $e)
        {
        }

     }

     public function getCategoryListByType($type)
     {

        try
        {
             $category = new InventoryCategory;

             $item     = new Item;

             $condition = ['category_type' => $type];

             $column = 'name';

             $item_type = [$type];


             $category_list = $category->getCategoryListByColumn($column,$condition);

             $item_list     = $item->getItemListByType($item_type);

             $data['view'] = '<option value="0">Select  Category </option>';

             foreach($category_list as $rows)
             {
               $data['view'] .= '<option value="'.Crypt::encrypt($rows->id).'">'.ucfirst($rows->name).'</option>';
             }

               $data['view1'] = '<option value="'.Crypt::encrypt(0).'">Select  Item </option>';

             foreach($item_list as $rows)
             {
               $data['view1'] .= '<option value="'.Crypt::encrypt($rows->id).'">'.ucfirst($rows->name).'</option>';
             }
                return $data;

        }
        catch(DecryptException $e)
        {

        }

     }

     public function storeInventoryCategory(Request $request)
     {
            $category = new InventoryCategory;

            $form_collect = $request->input();

            $check_category = $category->checkCategory($form_collect['name']);
            
            $check_code = $category->checkCode($form_collect['category_code']);

              if($check_category == 1 && $check_code == 1)
              {
                parent::errorMessage('Name/Code Already Exists.');

                if($request->ajax())
                {
                   return ['success' => false];
                }
                else
                {
                  return redirect()->back();
                }

              }

              $curr_category = $category->storeInventoryCategory($form_collect);

              if(isset($curr_category->id))
              {

              parent::setLogMessage('New category "'.$curr_category->name.'" has been added.');

              parent::successMessage('New category has been added.',parent::getLogMessage());
               if($request->ajax())
              {

                 $data['id']   = Crypt::encrypt($curr_category->id);
                 $data['name'] = $curr_category->name;
                 $data['category_code'] = $curr_category->category_code;
                 parent::clearMessageLog(1);

                 return $data;
              }
                  }

        return redirect()->back();



     }

      public function storeInventoryUnit(Request $request)
     {
            $unit         = new InventoryUnit;

            $form_collect = $request->input();

            $check_unit = $unit->checkUnit($form_collect['name']);

              if($check_unit == 1)
              {
                parent::errorMessage('Name Already Exists.');

                if($request->ajax())
                {
                   return ['success' => false];
                }
                else
                {
                  return redirect()->back();
                }

              }

              $curr_unit = $unit->storeInventoryUnit($form_collect);

              if(isset($curr_unit->id))
              {

              parent::setLogMessage('New unit "'.$curr_unit->name.'" has been added.');

              parent::successMessage('New unit has been added.',parent::getLogMessage());
               if($request->ajax())
              {

                 $data['id']   = Crypt::encrypt($curr_unit->id);
                 $data['name'] = $curr_unit->name;
                 parent::clearMessageLog(1);

                 return $data;
              }
                  }

        return redirect()->back();

     }



     public function viewProductDetail($id)
     {

       $id = decrypt($id);

       $branch = new Branch;
       $product = new Item;

       $product_list = $product->getItemById($id);
       $branch  =  $branch->getBranchList();
       $stock_list = ProjectStock::where('item_id',$id)->get();


      return view('inventory_module.item.item_detail',
        [
             'branch'                    => $branch,
             'product_list'       =>$product_list,
             'stock_list'       =>$stock_list,
           ]
       );

     }
}
