<?php include("_config/dbconfig.php");
include("_includes/head.php");
error_reporting(0);
function removeComma($string){
    return substr($string, 0, strlen($string)-2 );
}

$total_person_contacts = 0;
echo '<title>Import Client</title>'; 
$categories = $obj_category_class->getAllCategories();
 

if(isset($_SESSION['user_session'])){
$agent_id = $_SESSION['user_session'];
}else {
$agent_id = 0;	
}


$all_clients  =  $obj_clients_class->getClients();
$old_clients = array();
$already_added  = '';

foreach($all_clients as $aaa){
	$old_clients[] = trim( strtolower($aaa['company_name']))	;
 	}

//echo '<pre>'; print_r($old_clients); 	echo '</pre>';
function change2($string){
            $tmp = preg_replace("/[\n\r]/","",$string);
            $string = str_replace('-', '*', $string);
            $string = preg_replace('/[^(\x20-\x7F)]*/','', $tmp);
            
            $string = strip_tags($string);
            $string = str_replace('*', '-', $string);
            return trim($string);
	}
        

function change($string){
            $tmp = preg_replace("/[\n\r]/","-",$string);
            $string = preg_replace('/[^(\x20-\x7F)]*/','', $tmp);
            $string = str_replace('-', '<br>', $string);
            $string = strip_tags($string);
            return trim($string);
	}
        
if(isset($_POST['import_submit'])){
    
/*    echo '<pre>';
print_r($_FILES);
echo '</pre>'; */


    $msg = '';
    
   if(isset($_FILES['import_file']) && !empty($_FILES['import_file']['name'])){
        // settings
        $thumb_img = $_FILES['import_file'];
        $max_file_size = 1024*3000; // 900kb 3mb
        $valid_exts = array('csv');
        // thumbnail sizes
        $sizes = array(900 => 400);
        // get file extension
        $ext = strtolower(pathinfo($thumb_img['name'], PATHINFO_EXTENSION));

            if (in_array($ext, $valid_exts)) {
                    /* resize image */
                    $uniqId  = "import_".uniqid(5).".".$ext;
                    $fPath 	 = 'uploads/import/'.$uniqId;
                    $filename = $uniqId;
                    $thumb_name = $uniqId;
                    $aa = "uploads/import/".$uniqId;
                    move_uploaded_file($thumb_img['tmp_name'], $aa);
            } else {
              $msg = 'Unsupported file';
            }
        }
        
        
        if(empty($msg)){
             $filename.'____';
        try{
            
            $truncate = $conn->prepare("TRUNCATE `client_import_temp`" );
            $truncate->execute();

         } catch (PDOException $e) {
            echo $e->getMessage();
        }
        
        
        $filename.'____*********';
        
	$file = fopen("uploads/import/".$filename,"r");
	$i = 0;
	
	while(!feof($file)) {
		$arr_1 = fgetcsv($file);
		if($i>0 && !empty($arr_1[1])){
			
$arr_1=str_replace("'",'',$arr_1);
        
		
		if(!empty($arr_1[1]) && !empty($arr_1[2])){ 
		$stmt = $conn->prepare("INSERT INTO client_import_temp(category, company, product, address, fax, website, city, first, last, designation, mobile, phone, extension,email,lead_source, member_of)
                                VALUES(:category, :company, :product, :address, :fax, :website, :city, :first, :last, :designation, :mobile, :phone, :extension, :email,:lead_source, :member_of)");

        $stmt->bindparam(":category", change($arr_1[1]));
        $stmt->bindparam(":company", change($arr_1[2]));
        $stmt->bindparam(":product", change($arr_1[3]));
        $stmt->bindparam(":address", change($arr_1[4]));
        $stmt->bindparam(":fax", change($arr_1[5]));
        
        $stmt->bindparam(":lead_source", change($arr_1[8]));
        $stmt->bindparam(":member_of", change($arr_1[9]));
        
        $stmt->bindparam(":website", change2($arr_1[6]));
        $stmt->bindparam(":city", change($arr_1[7]));
        
        $stmt->bindparam(":first", change($arr_1[10]));
        $stmt->bindparam(":last", change($arr_1[11]));
        $stmt->bindparam(":designation", change($arr_1[12]));
        $stmt->bindparam(":mobile", change($arr_1[13]));
        $stmt->bindparam(":phone", change($arr_1[14]));
        $stmt->bindparam(":extension", change($arr_1[15]));
        $stmt->bindparam(":email", change2($arr_1[16]));
        
        $stmt->execute();
        $all[] = $arr_1;
       	
            }
      }
      $i++;
    }
	 
	$stmt = $conn->prepare("SELECT distinct(`company`) FROM client_import_temp" );
	$stmt->execute();
	$return = array();
	while($Row = $stmt->fetch(PDO::FETCH_ASSOC)){
		  $com = $Row['company'];
		  $stmt2 = $conn->prepare("SELECT * FROM client_import_temp where company = '".$com."'" );
		  $stmt2->execute();
		  while($Row2 = $stmt2->fetch(PDO::FETCH_ASSOC)){
			$return[] = array('company'=> $com, 'details'=> $Row2);
		  }
	}

	$allCom = $return;
 
	$companies = array();
	$clientId = ''; 
	$not      = '';
	$line_no = 2;        
	
	foreach($allCom as $det){
        
            $test_com = trim(strtolower($det['details']['company']));
            if(!in_array($test_com, $old_clients)) {

            if(!in_array($det['company'], $companies)){
		
                $cat_ids = '';	 
                $companies[] = $det['company'];
                
                if(!empty($det['details']['category'])){
                    
                    $cats = explode(",", $det['details']['category']);
                    foreach($cats as $ct){
                            $tmp_cat = ""; 
                            $tmp_cat = $obj_category_class->getCategoryByName(trim($ct));
                        if(!empty($tmp_cat)){
                            $cat_ids .= $tmp_cat.',';
                        }
                    }
                     
                    $cat_ids = trim($cat_ids);
                    $cat_ids = substr($cat_ids,0 , strlen($cat_ids)-1 );
                    
					
		if(!empty($cat_ids)){
                        
                        $clientId = $obj_clients_class->addClient($det['details']['company'], '', $cat_ids, $det['details']['website'],  $det['details']['product'] , $det['details']['address'] ,$det['details']['city'], 'Pakistan', $det['details']['fax'], $agent_id, $det['details']['lead_source'], $det['details']['member_of']); 
                
                $obj_clients_class->addClientPerson($clientId, $det['details']['first'], $det['details']['last'], $det['details']['designation'],$det['details']['email'], $det['details']['mobile'], $det['details']['phone'], $det['details']['extension']);
                    }
		else {
                        $not.= '<tr><td>'.$line_no.'</td><td>'.$det['details']['company'].'</td><td>'. $det['details']['category'].'</td><td>'.$det['details']['website'].'</td><td>'.$det['details']['product'].'</td><td>'.$det['details']['city'].'</td><td>'.'Pakistan'.'</td><td>'.$det['details']['fax'].'</td><td>'.$det['details']['lead_source'].'</td><td>'.$det['details']['member_of'].'</td>';
                        
            }
                }else {
                    $not.= '<tr><td>'.$line_no.'</td><td>'.$det['details']['company'].'</td><td>'. $det['details']['category'].'</td><td>'.$det['details']['website'].'</td><td>'.$det['details']['product'].'</td><td>'.$det['details']['city'].'</td><td>'.'Pakistan'.'</td><td>'.$det['details']['fax'].'</td><td>'.$det['details']['lead_source'].'</td><td>'.$det['details']['member_of'].'</td></tr>';
                } 

        }else{ 
            
            if(!empty($clientId)){
                $obj_clients_class->addClientPerson($clientId, $det['details']['first'], $det['details']['last'], $det['details']['designation'],$det['details']['email'], $det['details']['mobile'], $det['details']['phone'], $det['details']['extension']);
                }
            }
            
            }else { 
                
                $already_added .= '<tr><td>'.$line_no.'</td><td>'.$det['details']['company'].'</td><td>'. $det['details']['category'].'</td><td>'.$det['details']['website'].'</td><td>'.$det['details']['product'].'</td><td>'.$det['details']['city'].'</td><td>'.'Pakistan'.'</td><td>'.$det['details']['fax'].'</td><td>'.$det['details']['lead_source'].'</td><td>'.$det['details']['member_of'].'</td>';
                
                 
                    }
				 
	 $line_no++; 
				 
}
             
			
            $cols = '<tr class="head"><td>Line No</td><td>Company</td><td>Category</td><td>website</td><td width="10%">Product</td><td>City</td><td>Country</td><td>Fax</td><td>Lead Source</td><td>Member of</td></tr>';
            $collast = '<tr><td> </td><td> </td><td></td><td> </td><td width="10%"></td><td></td><td></td><td></td><td></td><td></td></tr>';
        
                if(isset($_SESSION['not_insert'])){
                    unset($_SESSION['not_insert']);
                }
                    
        if(!empty($not)){
                $not_insert =  '<table class="lisitng_table table first_small">'.$cols.$not.$collast.'</table>';
                $_SESSION['not_insert'] = $not_insert;    
	        }

		$already_insert =  '<table class="lisitng_table table first_small">'.$cols.$already_added.$collast.'</table>';
		$_SESSION['already_insert'] = $already_insert ;    
		
		
        //unlink("uploads/import/".$filename);
         
        echo "<script> window.location= 'client_import.php'</script>";
       die();
    }
}
?>
<style>
    .head td{
                background: #F7f7f7;
                font-size: 12px;
                border-top: 1px solid #ddd !important;
            }
</style>

<?php include("_includes/header.php"); ?>

<div class="col-sm-12 right_form">
        <div class="title">
            <div class="row">
                <div class="col-md-8 col-sm-12">
                    <h1>Import Clients</h1>
                </div>
            </div>
        </div>
    
     <ol class="breadcrumb white">
          <li><a href="dashboard.php">Dashboard</a></li>
          <li><a href="clients.php">Clients</a></li>
          <li class="active">Import Client</li>
    </ol>
</div>


<div class="col-sm-12 form_inner">
    <form class="col-sm-12 form-box" id="_form" method="post" action="" enctype="multipart/form-data">
                <div class="row">
		
                        <div class="col-md-2 col-sm-2 form-group">
                                <label for="CompanyName">Upload CSV</label>
                        </div>
                        <div class="col-md-4 col-sm-6 form-group">
                                <input type="file" name="import_file" required ="required" class="form-control" >    
                        </div>
                        <div class="clearfix"></div>
                        
                        <div class="col-md-2 col-sm-2 form-group">
                                <label for=""> </label>
                        </div>
                        <div class="col-md-4 col-sm-6 form-group">
                            <input type="submit" name="import_submit" class="btn btn-default" >    
                        </div>  
                                       
            <div class="clearfix"></div> 
             
		</div>
            </form>
      <div class="clearfix"></div> 
    <div style="padding-top: 30px;">
                     <?php if(isset($_SESSION['not_insert'])){ ?>
                     	<h4> Category not found in: </h4>
        			 	<br>   
                     <?php          echo $_SESSION['not_insert'];
                    }
                        
                        ?>    
                        
                        
                    </div>
    
          <div class="clearfix"></div> 
    <div style="padding-top: 30px;">
                     <?php if(isset($_SESSION['already_insert'])){ ?>
                     	<h4> Client Already inserted: </h4>
        			 	<br>   
                     <?php          echo $_SESSION['already_insert'];
                    }
                        
                        ?>    
                        
                        
                    </div>
    
		</div>

<?php include("_includes/footer.php"); ?>

<script>
    
    $(document).ready(function(){
           $("#_form").validate();
       });

function thumbImg(){
	
            var imgg = $("#profile_img").val();
            arr = imgg.split(".");
            imgg = arr[1].toLowerCase();

            if(imgg == "jpg" || imgg =="jepg"  ||  imgg =="png"  || imgg =="gif"){
                $("#old_img").fadeOut(300);                    
            }
            else {
                    alert('Please select the valid file or format!');
                    $("#thumb_img").focus();
                    $("#thumb_img").val('');
            }
	}

var roww = <?= $total_person_contacts; ?>;

function addMoreContact(no_contact){
        var ro_val   = '';
        var ro_val11 = '';
        roww = roww+1;
        var ro_val11 = $("#person_"+no_contact+"_contact").val();
        
        console.log(ro_val11+"****************");
        
        var ro_val = parseInt(ro_val11)+1;
        $("#person_"+no_contact+"_contact").val(ro_val);
        
        var content =  '<div id="row_'+roww+'_" class="  form-group"><div class="col-md-3 col-sm-12 form-group"><label>Email</label><input class="form-control" type="email" name="person_'+no_contact+'_email'+ro_val+'" value="" ></div><div class="col-md-3 col-sm-12 form-group"><label>Mobile #</label><input class="form-control digits  " maxlength="10"  type="text" name="person_'+no_contact+'_mobile'+ro_val+'" value="" ></div><div class="col-md-3 col-sm-12 form-group"><label>Land Line #</label><input class="form-control digits  " maxlength="10" type="text" name="person_'+no_contact+'_contact'+ro_val+'" value="" ></div><div class="col-md-2 col-sm-12 form-group"><label>Ext # </label><input class="form-control " type="text digits  " maxlength="4" minlength="3"   name="person_'+no_contact+'_ext'+ro_val+'" value="" ></div><a class="col-md-1" style="float: right; font-size: 16px; cursor: pointer; padding: 5px;" onclick="remove_contact('+roww+', '+no_contact+');"><br><i class="fa fa-times"></i></a> <div class="clearfix"></div></div>';
        $( "#more_contact_"+no_contact+"_" ).append(content);
        if(ro_val>2){
            $("#person_"+no_contact+"_row #add_more").fadeOut(500);
        }
}


function remove_contact(row_id, person_row){
            
            $( "#person_"+person_row+"_row #row_"+row_id+"_" ).fadeOut(500, function(){
                        $( "#row_"+row_id+"_" ).html('');
            })

        var ro_val11 = $("#person_"+person_row+"_contact").val();
        console.log(ro_val11);
        
        ro_val= parseInt(ro_val11)-1;
        $("#person_"+person_row+"_contact").val(ro_val);
        
        if(ro_val<3){
            $("#person_"+person_row+"_row #add_more").fadeIn(500);
        }
}


function addPerson(){
    
    person  = $("#total_person").val();
    person_row = parseInt(person) + 1;
    $("#total_person").val(person_row);
        
    var new_content = '<div id="person_'+person_row+'_row" class="client_border" ><div class="col-md-5 col-sm-12 form-group"><div class="col-md-4 col-sm-12 form-group no-padds"><label >First Name</label><input class="form-control required" type="text" name="person'+person_row+'_f_name" value=""  ></div><div class="col-md-4 col-sm-12 form-group " style="padding-right: 0px;"><label for="">Last Name</label><input class="form-control required" type="text" name="person'+person_row+'_l_name" value="" ></div><div class="col-md-4 col-sm-12 form-group " style="padding-right: 0px;"><label for="">Designation</label><input class="form-control required" type="text" name="person'+person_row+'_designation" value="" ></div></div><div class="col-md-7 col-sm-12 form-group"><div class="col-md-3 col-sm-12 form-group"><label>Email</label><input class="form-control required" type="email" name="person_'+person_row+'_email1" value="" ></div><div class="col-md-3 col-sm-12 form-group"><label>Mobile #</label><input class="form-control required  digits" maxlength="10" type="text" name="person_'+person_row+'_mobile1" value="" ></div><div class="col-md-3 col-sm-12 form-group"><label>Land Line #</label><input class="form-control digits" maxlength="10" type="text" name="person_'+person_row+'_contact1" value="" ></div><div class="col-md-2 col-sm-12 form-group"><label>Ext </label><input class="form-control digits" maxlength="4"  minlength="3" type="text" name="person_'+person_row+'_ext1" value="" ></div><div class="clearfix"></div><div id="more_contact_'+person_row+'_"></div><div class="clearfix"></div><a id="add_more" style="float: right; font-size: 12px; cursor: pointer; padding: 5px;" onclick="addMoreContact('+person_row+');">Add More</a><div class="clearfix"></div></div><input type="hidden" id="person_'+person_row+'_contact" value="1"><div class="clearfix"></div> <a class="remove-btn" onclick="removePerson('+person_row+');">Remove Person</a></div>';
    
    $( "#more_persons").append(new_content);
}

function removePerson(remId){
        
            //alert(remId);
            $("#person_"+remId+"_row").remove();
            /*person  = $("#total_person").val();
            person_row = parseInt(person) - 1;
            $("#total_person").val(person_row);*/
            
}

function delPerson(remId, idd){ 
    
        var aaaa = confirm("Are you sure you want to Delete!"); 
        console.log(aaaa);
        if(aaaa == true){
            $.post('ajax.php?del_person='+idd+'&a=1', function(data){
                    $("#person_"+remId+"_row").remove();
                    console.log(data);
            })
        }
        
}

</script>
<?php  /* ?>
<div id="person_'+person_row+'_row"><div class="col-md-5 col-sm-12 form-group"><div class="col-md-4 col-sm-12 form-group no-padds"><label >First Name</label><input class="form-control required" type="text" name="person'+person_row+'_f_name" value=""  ></div><div class="col-md-4 col-sm-12 form-group " style="padding-right: 0px;"><label for="">Last Name</label><input class="form-control required" type="text" name="person'+person_row+'_l_name" value="" ></div><div class="col-md-4 col-sm-12 form-group " style="padding-right: 0px;"><label for="">Designation</label><input class="form-control required" type="text" name="person'+person_row+'_designation" value="" ></div></div><div class="col-md-7 col-sm-12 form-group"><div class="col-md-3 col-sm-12 form-group"><label>Email</label><input class="form-control required" type="email" name="person_'+person_row+'_email" value="" ></div><div class="col-md-3 col-sm-12 form-group"><label>Mobile #</label><input class="form-control required" type="text" name="person_'+person_row+'_mobile" value="" ></div><div class="col-md-3 col-sm-12 form-group"><label>Contact #</label><input class="form-control " type="text" name="person_'+person_row+'_contact" value="" ></div><div class="col-md-2 col-sm-12 form-group"><label>Ext </label><input class="form-control" type="text" name="person_'+person_row+'_fax" value="" ></div><div class="clearfix"></div><div id="more_contact_'+person_row+'_"></div><div class="clearfix"></div><a id="add_more" style="float: right; font-size: 12px; cursor: pointer; padding: 5px;" onclick="addMoreContact('+person_row+');">Add More</a><div class="clearfix"></div></div><input type="hidden" id="person_'+person_row+'_contact" value="1"><div class="clearfix"></div> </div>
<?php */ ?>

<?php if(isset($_GET['view']) && !empty($_GET['view'])){ ?>
<script>
$(document).ready(function(){ 
        $('.form-control').attr('readonly', 'readonly'); 
   });
</script>
<?php } ?>