<?php
/*
|--------------------------------------------------------------------------
| Controller
|--------------------------------------------------------------------------
|
*/
_auth();
$ui->assign('_application_menu', 'ps');
$ui->assign('_title', $_L['Products n Services'].'- '. $config['CompanyName']);
$ui->assign('_st', $_L['Products n Services']);
$action = $routes['1'];
$user = User::_info();
$ui->assign('user', $user);

if (!has_access($user->roleid, 'products_n_services', 'view')) {
    permissionDenied();
}

switch ($action) {

    case 'modal-list':


        if (!has_access($user->roleid, 'products_n_services', 'view')) {
            permissionDenied();
        }


        $d = ORM::for_table('sys_items')->order_by_asc('name')->find_array();

        echo '


<div class="modal-header">
	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
	<h3>'.$_L['Products n Services'].'</h3>
</div>
<div class="modal-body">
<input type="text" id="myInput" onkeyup="filterPS()" placeholder="Search for Product Name..">
<table class="table table-striped" id="items_table">
      <thead>
        <tr>
          <th width="10%">#</th>
          <th width="20%">'.$_L['Item Code'].'</th>
          <th width="55%">'.$_L['Item Name'].'</th>

          <th width="15%">'.$_L['Price'].'</th>
        </tr>
      </thead>
      <tbody>
       ';

        foreach($d as $ds){
            $price = number_format($ds['sales_price'],2,$config['dec_point'],$config['thousands_sep']);
            echo ' <tr>
          <td><input type="checkbox" class="si"></td>
          <td>'.$ds['id'].'</td>
          <td>'.$ds['name'].'</td>

          <td class="price">'.$price.'</td>
        </tr>';
        }

        echo '

      </tbody>
    </table>

</div>
<div class="modal-footer">

	<button type="button" data-dismiss="modal" class="btn">'.$_L['Close'].'</button>
	<button class="btn btn-primary update">'.$_L['Select'].'</button>
</div>
<style type="text/css">
#myInput {
    width: 100%; /* Full-width */
    font-size: 16px; /* Increase font-size */
    padding: 12px 20px 12px 40px; /* Add some padding */
    border: 1px solid #ddd; /* Add a grey border */
    margin-bottom: 12px; /* Add some space below the input */
}
</style>
<script type="text/javascript">
function filterPS() {
  // Declare variables 
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("items_table");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don\'t match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[2];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    } 
  }
}
</script>
';

        break;



        case 'c-new':

        if (!has_access($user->roleid, 'products_n_services', 'create')) {
            permissionDenied();
        }

        $units = ORM::for_table('sys_units')->order_by_asc('sorder')->find_array();
        $ui->assign('units',$units);

        $ui->assign('type','Product');
        $ui->assign('xheader', Asset::css(array('modal','dropzone/dropzone','redactor/redactor')));
        $ui->assign('xfooter', Asset::js(array('modal','dropzone/dropzone','redactor/redactor.min','numeric')));

        $max = ORM::for_table('sys_items')->max('id');
        $nxt = $max+1;
        $ui->assign('nxt',$nxt);

        view('crmadd-category');


    
    
    
            break;   

            case 'c-list':
                if (!has_access($user->roleid, 'products_n_services', 'view')) {
                    permissionDenied();
                }
        
        
        
                $paginator = Paginator::bootstrap('sys_item_cats');
                $d = ORM::for_table('sys_item_cats')->where('status','Active')->offset($paginator['startpoint'])->limit($paginator['limit'])->order_by_desc('id')->find_many();
                $ui->assign('d',$d);
               
                $ui->assign('paginator',$paginator);
        
                $ui->assign('xheader', Asset::css(array('modal','dropzone/dropzone','redactor/redactor')));
                $ui->assign('xfooter', Asset::js(array('clipboard.min','modal','dropzone/dropzone','redactor/redactor.min','numeric')));
        
                view('crmcategory-list');
                break;
            break;




    case 'add-post':

        if (!has_access($user->roleid, 'products_n_services', 'edit')) {
            permissionDenied();
        }

        $msg = '';

        $data = $request->all();


        $name = _post('name');
        $description = _post('description');
        $type = _post('type');
      
        // other variables

        // check Category already exist

        //if($item_number != ''){
            $check = ORM::for_table('sys_item_cats')->where('name',$name)->find_one();
            if($check){
                $msg .= 'Category already exist <br>';
            }
       // }



        if($name == ''){
            $msg .= 'Category Name is required <br>';
        }

        if($type == '0'){
            $msg .= 'Please choose the type <br>';
        }

        if($msg == ''){


            $d = ORM::for_table('sys_item_cats')->create();
            $d->name = $name;
            $d->description = $description;
            $d->type = $type;
            // other variables
             
               $d->img = _post('file_link');
           
            $d->status = 'Active';
            $d->save();
           
            _msglog('s', 'Category Added Successfully');

            echo $d->id();
        }
        else{
            echo $msg;
        }
        break;







    case 'edit-post':

        if (!has_access($user->roleid, 'products_n_services', 'edit')) {
            permissionDenied();
        }

        $msg = '';

        $data = $request->all();

        $id = _post('id');

        $name = _post('name');
        $description = _post('description');
        $type = _post('type');

        // other variables

       // echo $name.'-'.$type; die();




        $msg = '';

        if($name == ''){
            $msg .= 'Category name is required <br>';
        }



        if($msg == ''){
            $d = ORM::for_table('sys_item_cats')->find_one($id);
            if($d){

                if($name != '' && $name != $d->name){  
                    $check = ORM::for_table('sys_item_cats')->where('name',$name)->find_one();
                    if($check){
                        i_close('Category already exist.');
                    }
                }
               

                $d->name = $name;
                $d->description = $description;
                $d->type = $type;
                
               $d->img = _post('file_link');
                $d->type =

                
                // other variables

                $d->save();
                echo $d->id();
            }
            else{
                echo 'Not Found';
            }


        }
        else{
            echo $msg;
        }


        break;




        case 'category-list':

            $can_edit = has_access($user->roleid, 'products_n_services', 'edit');
            $can_delete = has_access($user->roleid, 'products_n_services', 'delete');
    
    ///$type = _post('stype');
    $name = _post('txtsearch');
            $d = ORM::for_table('sys_item_cats')->where_like('name',"%$name%")->where('status', 'Active')->order_by_asc('name')->find_array();
    if($d){
        echo '<table class="table table-hover">
            <tbody>
            
            <tr>
     
     <td>
     '.$_L['Image'].'
    </td>
    
                    <td class="project-title">
                        '.$_L['Name'].'
                    </td>
                   
                    <td class="project-actions">
    
                        '.$_L['Manage'].'
                    </td>
                </tr>
            
            
            
            ';
    
   
        foreach ($d as $ds){
    
            if($ds['img'] == ''){
                $img = '<img src="'.APP_URL.'/ui/lib/imgs/item_placeholder.png">';
            }
            else{
                $img = '<img src="'.APP_URL.'/storage/items/thumb'.$ds['img'].'">';
            }
    
      
            $cost_price = '';
            $price = '';
            $txt_available = $ds['status'];
            $tax_code_line = '';
            if($ds['type']==1){
                $type = "Product";
            }
            else if($ds['type']==2){
                $type = "Service";
            }
            else{
                $type = "Package";
            }
            
    
            $edit_button = '';
            $delete_button = '';
    
            if($can_edit)
            {
                $edit_button = '<a href="#" class="btn btn-primary btn-sm cedit" id="e'.$ds['id'].'"><i class="fa fa-pencil"></i> '.$_L['Edit'].' </a>';
            }
    
            if($can_delete)
            {
                $delete_button = '<a href="#" class="btn btn-danger btn-sm cdelete" id="pid'.$ds['id'].'"><i class="fa fa-trash"></i> '.$_L['Delete'].' </a>';
            }
    
    
    
    
            echo '
    
    
     <tr>
     
     <td>
     '.$img.'
    </td>
    
                    <td class="project-title">
                        <a href="#" class="cedit"  id="t'.$ds['id'].'">'.$ds['name'].'</a>
                        <br>
                        <small>Type : </small> '.$type.'
                        
                        
                    </td>
                    
                  
    
                    <td class="project-actions">
    
                        '.$edit_button.'
                        '.$delete_button.'
                    </td>
                </tr>';
        }
    
    
        echo '
            <tr>
     
     <td colspan="3">
    &nbsp;
    </td>
    
                    
                </tr>
            </tbody>
        </table>';
    }
    else{
        echo '<h4>Nothing Found</h4>';
    }
    
            
    
            break;
    
    
      




            case 'delete':

                if(!has_access($user->roleid,'products_n_services','delete')){
        
                    permissionDenied();
        
                }
        
                $id = $routes['2'];
                $id = str_replace('pid','',$id);
                $d = ORM::for_table('sys_item_cats')->find_one($id);
                if($d){
                    $d->status= "Inactive";
                    $r = 'crmps/c-list';
                    $type = $d->type == "1"? "Product": "Service";
                    _log($type.' Deleted: '.$d['name'].' [ID: '.$d['id'].']','Admin',$user->id);
        
                    $d->save();
        
                    r2(U.$r,'s', $type. ' ' .$_L['Deleted Successfully']);
        
                }
                else{
                    echo 'not found';
                }
                break;
        

    case 'edit-form':



        if(!has_access($user->roleid,'products_n_services','edit')){


            exit;

        }

        $id = $routes['2'];
        $d = ORM::for_table('sys_item_cats')->find_one($id);

        if($d){
            $price = '';//number_format(($d->sales_price),2,$config['dec_point'],$config['thousands_sep']);
            $has_img = '';
            if($d->img != ''){
                $has_img = '<hr>
<img src="'.APP_URL.'/storage/items/'.$d->img.'" class="img-responsive">
';
            }
            $type = $d->type;
            echo '
<div class="modal-header">
	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
	<h3>'.$_L['Edit'].'</h3>
</div>
<div class="modal-body">

<div class="row">
<div class="col-md-8">
<form class="form-horizontal" role="form" id="edit_form" method="post">
  <div class="form-group">
    <label for="name" class="col-sm-2 control-label">'.$_L['Name'].'</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" value="'.$d->name.'" name="name" id="name">
    </div>
  </div>

  
  <div class="form-group"><label class="col-lg-2 control-label" for="name">Type*</label>

  <div class="col-lg-10">
    <select class="form-control" id="type" name="type">
      <option  '.($type=="0"?"selected":"").' value="0">Select</option>
        <option '.($type=="1"?"selected":"").' value="1">Product</option>
        <option  '.($type=="2"?"selected":"").' value="2">Service</option>
        <option '.($type=="3"?"selected":"").' value="3">Package</option>

        

    </select>
  </div>
</div>

  
  
    <div class="form-group">
    <label for="description" class="col-sm-2 control-label">'.$_L['Description'].'</label>
    <div class="col-sm-10">
      <textarea id="description" name="description" class="form-control" rows="3">'.$d->description.'</textarea>
    </div>
  </div>
  
  
  

  
  
  
  

  
  <input type="hidden" name="id" value="'.$d->id.'">
  <input type="hidden" name="file_link" id="file_link" value="'.$d->img.'">
</form>
</div>
<div class="col-md-4">
<form action="" class="dropzone" id="upload_container">

                        <div class="dz-message">
                            <h3> <i class="fa fa-cloud-upload"></i>  '.$_L['Drop File Here'].'</h3>
                            <br />
                            <span class="note">'.$_L['Click to Upload'].'</span>
                        </div>
                        
                        <hr>
                        
                        

                    </form>
                 
                    '.$has_img.'
                    
</div>

</div>
<div class="row">
<div class="col-md-12">



  

</div>
</div>

</div>
<div class="modal-footer">

	<button type="button" data-dismiss="modal" class="btn">'.$_L['Close'].'</button>
	<button id="update" class="btn btn-primary">'.$_L['Update'].'</button>
</div>';
        }
        else{
            echo 'not found';
        }



        break;




    case 'json_get':

        if (!has_access($user->roleid, 'products_n_services', 'view')) {
            permissionDenied();
        }

        header('Content-Type: application/json');

        $pid = route(2);

        $d = ORM::for_table('sys_items')->find_one($pid);

        if($d){

            $i = array();
            $i['sales_price'] = $d->sales_price;

            echo json_encode($i);

        }


        break;

    case 'cats':




        break;


    case 'upload':

        if (!has_access($user->roleid, 'products_n_services', 'create')) {
            permissionDenied();
        }

        if(APP_STAGE == 'Demo'){
            exit;
        }

        $uploader   =   new Uploader();
        $uploader->setDir('storage/items/');
        $uploader->sameName(false);
        $uploader->setExtensions(array('jpg','jpeg','png','gif'));  //allowed extensions list//
//        $uploader->allowAllFormats();  //allowed extensions list//
        if($uploader->uploadFile('file')){   //txtFile is the filebrowse element name //
            $uploaded  =   $uploader->getUploadName(); //get uploaded file name, renames on upload//

            $file = $uploaded;
            $msg = $_L['Uploaded Successfully'];
            $success = 'Yes';

            // create thumb

            $image = new Img();

            // indicate a source image (a GIF, PNG or JPEG file)
            $image->source_path = 'storage/items/'.$file;

            // indicate a target image
            // note that there's no extra property to set in order to specify the target
            // image's type -simply by writing '.jpg' as extension will instruct the script
            // to create a 'jpg' file
            $image->target_path = 'storage/items/thumb'.$file;

            // since in this example we're going to have a jpeg file, let's set the output
            // image's quality
            $image->jpeg_quality = 100;

            // some additional properties that can be set
            // read about them in the documentation
            $image->preserve_aspect_ratio = true;
            $image->enlarge_smaller_images = true;
            $image->preserve_time = true;

            // resize the image to exactly 100x100 pixels by using the "crop from center" method
            // (read more in the overview section or in the documentation)
            //  and if there is an error, check what the error is about
            if (!$image->resize(100, 100, ZEBRA_IMAGE_CROP_CENTER)) {



                // if no errors
            } else {

                // echo 'Success!';

            }

            //


        }else{//upload failed
            $file = '';
            $msg = $uploader->getMessage();
            $success = 'No';
        }

        $a = array(
            'success' => $success,
            'msg' =>$msg,
            'file' =>$file
        );

        header('Content-Type: application/json');

        echo json_encode($a);




        break;




        case 'package-new':

            if (!has_access($user->roleid, 'products_n_services', 'create')) {
                permissionDenied();
            }
    
            $units = ORM::for_table('sys_units')->order_by_asc('sorder')->find_array();
            $ui->assign('units',$units);
            $category = ORM::for_table('sys_item_cats')->where('type', "3")->where('status', 'Active')->order_by_asc('id')->find_array();
            $ui->assign('category',$category);
    
    
            $ui->assign('type','Package');
            $ui->assign('xheader', Asset::css(array('modal','dropzone/dropzone','redactor/redactor')));
            $ui->assign('xfooter', Asset::js(array('modal','dropzone/dropzone','redactor/redactor.min','numeric')));
    
            $max = ORM::for_table('sys_items')->max('id');
            $nxt = $max+1;
            $ui->assign('nxt',$nxt);
    
            view('crmadd-package');
        break;
        
            case 'package-list':

                if (!has_access($user->roleid, 'products_n_services', 'view')) {
                    permissionDenied();
                }
        
        
        
                $paginator = Paginator::bootstrap('sys_items','type','Package');
                $d = ORM::for_table('sys_items')->where('type','Package')->offset($paginator['startpoint'])->limit($paginator['limit'])->order_by_desc('id')->find_many();
                $ui->assign('d',$d);
                $ui->assign('type','Package');
                $ui->assign('paginator',$paginator);
        
                $ui->assign('xheader', Asset::css(array('modal','dropzone/dropzone','redactor/redactor')));
                $ui->assign('xfooter', Asset::js(array('clipboard.min','modal','dropzone/dropzone','redactor/redactor.min','numeric')));
        
                view('crmpackage-list');
                break;
        
        
    default:
        echo 'action not defined';
}