<?php

namespace App\Http\Controllers\Admin;

use App\Attribute;
use App\AttributeTranslation;
use App\Category;
use App\Product;
use App\ProductImage;
use App\ProductDocument;
use Illuminate\Support\Facades\Storage; //Laravel Filesystem
use DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AjaxController extends Controller
{
    public function index(Request $request, $act){

        if(method_exists($this, $act)){
            return $this->{trim($act)}($request);
        } else {
            echo 'Method '.$act.' does not exist';
        }
    }

    // Get attribute id name for tags
    private function attributesidname($request){

        $trimpar = trim($request->term);
        $par = ($trimpar != '') ? '%'.$trimpar.'%' : '';

        $data = AttributeTranslation::where('atr_name', 'LIKE', $par)->select('atr_id as id', 'atr_name as label')->get();

        $output = '';
        if(count($data)) {

            $result = [];

            foreach ($data as $r) {
                $result[] = '{"id":"'.$r->id.'","label":"'.$r->label.'","value":"'.$r->label.'"}';
            }
            $output = "[".implode(',', $result)."]";
        }

        echo $output;


    }


    // Get products id name
    private function productsidname($request){

        $trimpar = trim($request->term);
        $par = ($trimpar != '') ? '%'.$trimpar.'%' : '';

        $data = Product::where('prod_name', 'LIKE', $par)->orWhere('prod_id',$par)->orWhere('prod_sku',$par)->select('prod_id as id', 'prod_name as label')->get();

        $output = '';
        if(count($data)) {

            $result = [];

            foreach ($data as $r) {
                $result[] = '{"id":"'.$r->id.'","label":"'.$r->label.'","value":"'.$r->label.'"}';
            }
            $output = "[".implode(',', $result)."]";
        }

        echo $output;


    }

    // Generating attribute selects
    private function getatrselects($request){ 

        $html = ''; // html polja za atribute

        if(isset($request->catid) && is_numeric($request->catid)){

            $catid = trim($request->catid);
            
            $attrids = Category::find($catid)->attributes->pluck('atr_id')->toArray();


            if(!empty($attrids)){

                foreach ($attrids as $atrid){

                    $data = Attribute::getAttributeWithValues($atrid);

                    $count = count($data);

                    if($count > 0) {

                        $html .= '';

                        $multiple      = '';
                        $multipleClass = '';
                        $multiplearr   = '';

                        $name          = 'atr_val_id';
                        $title         = __('adminforms.products.select_atr_s');

                        if($data[0]->atr_type == 'm'){
                            $multiple      = 'multiple="multiple"';
                            $multipleClass = 'multiple';
                            $multiplearr   = '[]';
                            $name          = 'm_atr_val_id';
                            $title         = __('adminforms.products.select_atr_m');
                        }



                        $html .= '<div class="form-group">
					      <label>'.$data[0]->atr_name.'</label>
					      <select name="'.$name.'['.$data[0]->atr_id.']'.$multiplearr.'" class="form-control input-sm atsel '.$multipleClass.'" '.$multiple.'>';
                        $html .=   ($data[0]->atr_type == 'm') ? '' : '<option value="">'.$title.'</option>';

                        foreach($data as $a):
                            $html .= '<option value="'.$a->atr_val_id.'">'.ucfirst($a->atr_value).'</option>';
                        endforeach;

                        $html .= '</select>
					      </div><!--form-group-->';



                    }


                } //end foreach

                // if($html != '') $html .= '<br clear="all"/>';

            } // if not empty attr array
            else { $html = '<div class="text-center"><strong>'.__('adminforms.products.cat_dnot_have_sttrs').'</strong></div>';}

            echo $html;


        } // kraj ukoliko ima posta

    } // kraj generisanje polja za unos atributa

    //Image deletion
    private function delimg($request){

        try{

            $html = '';

            $pid       = (is_numeric(trim($request->prodid))) ? trim($request->prodid) : -1;
            $imgid     = (is_numeric(trim($request->imgid)))  ? trim($request->imgid)  : -1;

            $img = ProductImage::where('prod_id',$pid )->where('prod_img_id',$imgid)->firstOrFail();

            $timg = public_path($img->prod_timg);
            $simg = public_path($img->prod_simg);
            $mimg = public_path($img->prod_mimg);
            $bimg = public_path($img->prod_bimg);

            $sucesst = false;
            $sucesss = false;
            $sucessm = false;
            $sucessb = false;

            if(file_exists($timg) && is_readable($timg)){ $sucesst =  unlink($timg);}
            if(file_exists($simg) && is_readable($simg)){ $sucesss =  unlink($simg);}
            if(file_exists($mimg) && is_readable($mimg)){ $sucessm =  unlink($mimg);}
            if(file_exists($bimg) && is_readable($bimg)){ $sucessb =  unlink($bimg);}

            if( $sucesst && $sucesss && $sucessm && $sucessb ) {

                $html .= 'sucess, '.__('adminforms.products.img_server_deleted').'; ';

            } else {

                $html .= 'error, '.__('adminforms.products.img_server_del_err').'; ';

            }


            if( $sucesst || $sucesss || $sucessm || $sucessb ) {

                $delres = $img->destroy($img->prod_img_id);

                $html .=  ($delres) ? __('adminforms.products.img_db_deleted') : __('adminforms.products.img_db_del_err');
            }

            echo $html;

        } catch (\Illuminate\Database\QueryException $e) {
            echo handle_error($e);
        } catch (\Exception $e) {
            echo handle_error($e);
        }



    } // delimg


    //Document deletion
    private function deldoc($request){

        try{

            $html = '';

            $pid       = (is_numeric(trim($request->prodid))) ? trim($request->prodid) : -1;
            $docid     = (is_numeric(trim($request->docid)))  ? trim($request->docid)  : -1;

            $document = ProductDocument::where('prod_id',$pid )->where('pd_id',$docid)->firstOrFail();

            $path  = public_path($document->pd_path);
            $docid = $document->pd_id;

            $result = false;

            if(file_exists($path) && is_readable($path)){ $result =  unlink($path);}

            if( $result ) {

                $html .= 'sucess, '.__('adminforms.products.doc_server_deleted').'; ';

                $delres = $document->destroy($docid);

                $html .=  ($delres) ? __('adminforms.products.doc_db_deleted') : __('adminforms.products.doc_db_del_err');

            } else {

                $html .= 'error, '.__('adminforms.products.doc_server_del_err').'; ';

            }

            echo $html;

        } catch (\Illuminate\Database\QueryException $e) {
            echo handle_error($e);
        } catch (\Exception $e) {
            echo handle_error($e);
        }



    } // deldoc

    // Setting default image
    private function setdefimg($request){

        try{

            DB::beginTransaction();

            $html = '';

            if(isset($request->defaultimg) &&  $request->defaultimg != '' ){

                $defImgData = (explode("-",$request->defaultimg));

                $defImgProdId = $defImgData[0];
                $defImgId     = $defImgData[1];

                if(is_numeric($defImgProdId) && is_numeric($defImgId)){


                    $prodid    = intval($defImgProdId);
                    $prodimgid = intval($defImgId);

                    // 1 . oznacavanje svih slika da nisu defoltne
                    ProductImage::where('prod_id', $prodid)->update(['prod_def_img' => 0]);


                    // 2. Oznacavanje slike kao podrazumevane
                    ProductImage::where('prod_id', $prodid)->where('prod_img_id', $prodimgid)->update(['prod_def_img' => 1]);


                    $rowCount = Product::updateImagesForListing($prodid);


                    $html .=  ($rowCount) ? __('adminforms.products.img_def_set') : __('adminforms.products.img_def_set_err');

                    DB::commit();



                }	else {

                    $html .=  __('adminforms.products.img_def_no_id');

                }

            }

            echo $html;



        } catch (\Illuminate\Database\QueryException $e) {
            // something went wrong with the transaction, rollback
            DB::rollback();
            echo handle_error($e);
        } catch (\Exception $e) {
            // something went wrong elsewhere, handle gracefully
            DB::rollback();
            echo handle_error($e);
        }



    } // setdefimg

    // Product search methods
    private function getinvoiceitems($request) {

        if($request->has('term')) {


            $qt = searchReplace($request->term);

            $data = collect(DB::select('SELECT c.cat_id, p.prod_id AS id, CONCAT(b.brand_name, " ", p.prod_name) AS name, 
                                             p.`prod_price` AS price, p.`prod_ifdisc` AS fix, c.cat_vat AS vat
                                             FROM `products`  p USE INDEX (`cat_id`, `prod_status`)
                                             INNER JOIN brands  b USE INDEX (`PRIMARY`) ON p.brand_id = b.brand_id 
                                             INNER JOIN categories c USE INDEX (`PRIMARY`) ON p.cat_id = c.cat_id
                                             WHERE  
                                             p.prod_id RLIKE :q OR 
                                             p.prod_name RLIKE :q OR 
                                             b.brand_name RLIKE :q OR 
                                             CONCAT(b.brand_name, " ", p.prod_name) RLIKE :q 
                                             ORDER BY name',
                [':q' => $qt]
            ));




            if(count($data)) {

                $result = array();

                foreach($data as $row){

                    $id    = $row->id;
                    $title = $row->name;
                    $fix   = $row->fix;
                    $price = $row->price;
                    $vat   = $row->vat;

                    $name = $id.'|'.$title.'|'.$price.'|'.$fix.'|'.$vat;
                    array_push($result, $name);

                }

                echo json_encode($result);exit;

            }
        }


    } // getinvoiceitems

    private function getinvoiceitemwithgifts($request) {


        if($request->has('prodid')) {

            $index = ($request->has('index')) ? trim($request->index): 1;

            $prodid = trim($request->prodid);

            $data = collect(DB::select('SELECT c.cat_id, p.prod_id AS id, CONCAT(b.brand_name, " ", p.prod_name) AS name, 
                                             p.`prod_price` AS price, p.`prod_ifdisc` AS fix, c.cat_vat AS vat, p.`prod_sku` AS sku
                                             FROM `products`  p USE INDEX (`cat_id`, `prod_status`)
                                             INNER JOIN brands  b USE INDEX (`PRIMARY`) ON p.brand_id = b.brand_id 
                                             INNER JOIN categories c USE INDEX (`PRIMARY`) ON p.cat_id = c.cat_id
                                             WHERE  
                                             p.prod_id  = :prodid',
                [':prodid' => $prodid]
            ));


            $html = "";

            if(count($data)) {


                $index = ($request->has('index')) ? trim($request->index): 0;


                foreach($data as $row){


                    $id      = $row->id;
                    $sku     = $row->sku;
                    $name    = $row->name;
                    $price   = number_format($row->price, 2, '.', '');
                    $qnt     = 1;
                    $uom     = 'kom';
                    $tot     = number_format(($row->price*$qnt), 2, '.', '');

                    $html .=  '<tr class="iitem" data-index="'.$index.'">
  
					<td>
					<input class="case" type="checkbox"/>
					<input name="item['.$index.'][prod_id]" class="pid" type="hidden" value="'.$id.'" />
					</td>
					
					<td><input name="item['.$index.'][prod_sku]" value="'.$sku.'" class="form-control input-sm sku" autocomplete="off" onkeypress="return false"  
					onkeydown="return false"  ondrop="return false;" onpaste="return false;"></td>
					
					<td><input type="text" data-type="poiDesc" name="item['.$index.'][poi_desc]"  value="'.$name.'"    
					class="form-control input-sm pn" autocomplete="off"></td>
					
					<td><input name="item['.$index.'][poi_qnt]" class="form-control input-sm qnt" value="'.$qnt.'" 
					 autocomplete="off" onkeypress="return IsNumeric(event);"></td>
					 
					<td><input type="text" name="item['.$index.'][poi_uom]"  value="'.$uom.'"    
					class="form-control input-sm pn" autocomplete="off"></td>
					
					<td><input name="item['.$index.'][poi_price]" class="form-control input-sm price"  value="'.$price.'" autocomplete="off" 
					onkeypress="return IsNumeric(event);"></td>
					
					<td><input name="item['.$index.'][total]" class="form-control input-sm tot"  value="'.number_format($tot, 2,".","").'" autocomplete="off"  
					onkeypress="return false"  onkeydown="return false"  ondrop="return false;" onpaste="return false;"></td>
					
					
					</tr>';

                } // foreach


            } // if data

        } // isset($_POST['prodid'])

        echo $html;


    } // getinvoiceitemwithgifts

    private function getnewinvoiceitemwithgifts($request) {


        if($request->has('prodid')) {

            $index = ($request->has('index')) ? trim($request->index): 1;

            $prodid = trim($request->prodid);

            $data = collect(DB::select('SELECT c.cat_id, p.prod_id AS id, CONCAT(b.brand_name, " ", p.prod_name) AS name, 
                                             p.`prod_price` AS price, p.`prod_ifdisc` AS fix, c.cat_vat AS vatrate, p.`prod_sku` AS sku
                                             FROM `products`  p USE INDEX (`cat_id`, `prod_status`)
                                             INNER JOIN brands  b USE INDEX (`PRIMARY`) ON p.brand_id = b.brand_id 
                                             INNER JOIN categories c USE INDEX (`PRIMARY`) ON p.cat_id = c.cat_id
                                             WHERE  
                                             p.prod_id  = :prodid',
                [':prodid' => $prodid]
            ));


            $html = "";

            if(count($data)) {


                $index = ($request->has('index')) ? trim($request->index): 0;


                foreach($data as $row){


                    $id      = $row->id;
                    $sku     = $row->sku;
                    $name    = $row->name;
                    $qnt     = 1;
                    $uom     = 'kom';
                    $price   = $row->price;
                    $vatrate = $row->vatrate;
                    $vat     = $row->price*($row->vatrate/100);
                    $tot     = ($price+$vat)*$qnt;

                    $html .=  '<tr class="iitem" data-index="'.$index.'">
  
					<td>
					<input class="case" type="checkbox"/>
					<input name="item['.$index.'][prod_id]" class="pid" type="hidden" value="'.$id.'" />
					</td>
					
					<td><input name="item['.$index.'][prod_sku]" value="'.$sku.'" class="form-control input-sm sku" autocomplete="off" onkeypress="return false"  
					onkeydown="return false"  ondrop="return false;" onpaste="return false;"></td>
					
					<td><input type="text" data-type="poiDesc" name="item['.$index.'][invi_desc]"  value="'.$name.'"    
					class="form-control input-sm pn" autocomplete="off"></td>
					
					<td><input name="item['.$index.'][invi_qnt]" class="form-control input-sm qnt" value="'.$qnt.'" 
					 autocomplete="off" onkeypress="return IsNumeric(event);"></td>
					 
					<td><input type="text" name="item['.$index.'][invi_uom]"  value="'.$uom.'"    
					class="form-control input-sm pn" autocomplete="off"></td>
					
					<td><input name="item['.$index.'][invi_price]" class="form-control input-sm price"  value="'.number_format($price, 2, '.', '').'" autocomplete="off" 
					onkeypress="return IsNumeric(event);"></td>
					
					<td><input name="item['.$index.'][invi_vrate]" class="form-control input-sm vr"  value="'.$vatrate.'" autocomplete="off"  
					onkeypress="return false"  onkeydown="return false"  ondrop="return false;" onpaste="return false;"></td>
					
					<td><input name="item['.$index.'][invi_vat]" class="form-control input-sm vat"  value="'.number_format($vat, 2,".","").'" autocomplete="off"  
					onkeypress="return false"  onkeydown="return false"  ondrop="return false;" onpaste="return false;"></td>
					
					<td><input name="item['.$index.'][total]" class="form-control input-sm tot"  value="'.number_format($tot, 2,".","").'" autocomplete="off"  
					onkeypress="return false"  onkeydown="return false"  ondrop="return false;" onpaste="return false;"></td>
					
					
					</tr>';

                } // foreach


            } // if data

        } // isset($_POST['prodid'])

        echo $html;


    } // getnewinvoiceitemwithgifts


}
