<?php 
define('DOCUMENT_ROOT_CLASS','../');
define('DOCUMENT_ROOT_INC_FOLDER','');
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call"){
    require "../inc/ajax_header.php";
    $country_id = $_POST["country_id"];
    $getData = $commonFunctions->getData('sys_erp_adm_countries_states'," WHERE country_id = '".$country_id."' and active = 1 ");
    $html = "";
    foreach ($getData as $rw) {
        $html .= "<option value='".$rw['rowid']."'>".$rw['label']."</option>";
    }
    echo json_encode(array("option"=>$html));
    exit();
}
if(!empty($_GET["action"]) and $_GET["action"] == "ajax_call1"){
    require "../inc/ajax_header.php";
    $country_id = $_GET["country_id"];
    $state_id = $_GET["state_id"];
    $keyword = $_GET["keyword"]; 
    $getData = $commonFunctions->getData('sys_erp_adm_countries_states_cities'," WHERE country_id = '".$country_id."' and state_id = '".$state_id."' and name LIKE '%".$keyword."%' ");
    $html = "";
    $skillData = array(); 
    foreach ($getData as $rw) {
        $data['id'] = $rw['name']; 
        $data['value'] = $rw['name']; 
        array_push($skillData, $data); 
    } 
    echo json_encode($skillData);
    exit();
}
require "../inc/header.php";
Session::CheckSession(); 
$msg = Session::get('msg');
Session::set("msg", NULL);?>

    <!-- Page-Title -->
    <div class="row">
        <div class="col-sm-12">
            <div class="page-title-box">
                <div class="row">
                    <div class="col">
                        <h4 class="page-title">Address Book</h4>
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="javascript:void(0);">CRM</a></li>
                            <li class="breadcrumb-item"><a href="javascript:void(0);">Address Book</a></li>
                        </ol>
                    </div><!--end col-->
                    <!-- <div class="col-auto align-self-center">
                        <a href="#" class="btn btn-sm btn-outline-primary" id="Dash_Date">
                            <span class="day-name" id="Day_Name">Today:</span>&nbsp;
                            <span class="" id="Select_date">Jan 11</span>
                            <i data-feather="calendar" class="align-self-center icon-xs ml-1"></i>
                        </a>
                        <a href="#" class="btn btn-sm btn-outline-primary">
                            <i data-feather="download" class="align-self-center icon-xs"></i>
                        </a>
                    </div> --><!--end col-->  
                </div><!--end row-->                                                              
            </div><!--end page-title-box-->
        </div><!--end col-->
    </div><!--end row-->
    <?php if($_GET['state'] == 'list'){ ?>
        <div class="row">
            <div class=" col-sm-12">
                <div class="card">
                    <div class="card-header">
                        <div class="form-row">
                            <div class="form-group searchForm col-md-6">
                        <!-- <h4 class="card-title">Address Book -->
                                <a class="btn btn-sm btn-soft-primary" href="address-book.php?state=add" role="button"><i class="fas fa-plus mr-2"></i> Add New Address Book</a>
                            </div>    
                            <div class="form-group searchForm col-md-6">
                                <?php if(empty($_GET['state']) OR (!empty($_GET['state']) and $_GET['state'] == "list")): ?>
                                <form action="" id="searchForm" method="GET">
                                    <div class="form-row">
                                        <div class="form-group searchForm col-md-8">
                                            <input type="text" name="search" id="search" placeholder="Search" class="form-control" value="<?php echo @$_GET['search']; ?>">
                                            <input type="hidden" name="state" value="<?php echo @$_GET['state']; ?>">
                                            <input type="hidden" name="page" value="<?php echo @$_GET['page']; ?>">
                                        </div>
                                        <div class="form-group searchForm col-md-4">
                                            <button type="submit" id="searchbtn" class="btn btn-primary"> <i class="fa fa-search"></i> Search</button>
                                            <button type="button" id="clearbtn" class="btn btn-danger"> <i class="fa fa-trash"></i> Clear</button>
                                        </div>
                                    </div>
                                </form>
                                <?php endif; ?>
                            </div>
                        </div>
                        <!-- </h4> -->
                    </div><!--end card-header-->
                    <div class="card-body">
                        <?php $targetpage = "address-book.php?state=list"; 
                            $limit = 50;
                            $total_pages = $commonFunctions->getData('crm_add_bk','');
                            $total_pages = count($total_pages);
                            $stages = 3;
                            $page = @$_GET['page'];
                            if($page){
                                $start = ($page - 1) * $limit; 
                            }else{
                                $start = 0; 
                            } 
                            
                            $search_con = "";
                            if(!empty($_GET['search'])){
                                $countryArr = $commonFunctions->getIDs('sys_erp_adm_countries','rowid'," WHERE label LIKE '%".$_GET['search']."%' ");
                                $sys_erp_adm_countries_statesArr = $commonFunctions->getIDs('sys_erp_adm_countries_states','rowid'," WHERE label LIKE '%".$_GET['search']."%' ");
                                $country_ids = @$countryArr["ids"];
                                $state_ids = @$sys_erp_adm_countries_statesArr["ids"];
                                $search_con = " AND first_name LIKE '%".$_GET['search']."%' OR last_name LIKE '%".$_GET['search']."%' OR title LIKE '%".$_GET['search']."%' OR job_position LIKE '%".$_GET['search']."%' OR address LIKE '%".$_GET['search']."%' OR postcode LIKE '%".$_GET['search']."%' OR prof_phone LIKE '%".$_GET['search']."%' OR pers_phone LIKE '%".$_GET['search']."%' OR email LIKE '%".$_GET['search']."%' OR city LIKE '%".$_GET['search']."%' ";
                                if(!empty($country_ids)){ $search_con .= "  OR country_id IN(".$country_ids.") "; }
                                if(!empty($state_ids)){ $search_con .= "  OR state_id IN(".$state_ids.") "; }
                            }
                            $where = " WHERE id ".$search_con." ORDER BY id DESC LIMIT $start, $limit ";
                            
                            // Initial page num setup
                            if ($page == 0){ $page = 1; }
                            $prev = $page - 1;  
                            $next = $page + 1;  
                            $lastpage = ceil($total_pages/$limit);  
                            $LastPagem1 = $lastpage - 1;    
                            $paginate = '';
                            if($lastpage > 1)
                            {       
                                $paginate .= "<div class='paginate'>";
                                // Previous

                                if ($page > 1){
                                    $paginate.= "<a href='$targetpage&page=$prev'>Previous</a>";
                                }else{
                                    $paginate.= "<span class='disabled'>Previous</span>";   }
                                // Pages    
                                if ($lastpage < 7 + ($stages * 2))  // Not enough pages to breaking it up
                                {   
                                    for ($counter = 1; $counter <= $lastpage; $counter++)
                                    {
                                        if ($counter == $page){
                                            $paginate.= "<span class='current'>$counter</span>";
                                        }else{
                                            $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                    }
                                }
                                elseif($lastpage > 5 + ($stages * 2))   // Enough pages to hide a few?
                                {
                                    // Beginning only hide later pages
                                    if($page < 1 + ($stages * 2))   
                                    {
                                        for ($counter = 1; $counter < 4 + ($stages * 2); $counter++)
                                        {
                                            if ($counter == $page){
                                                $paginate.= "<span class='current'>$counter</span>";
                                            }else{
                                                $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                        }
                                        $paginate.= "...";
                                        $paginate.= "<a href='$targetpage&page=$LastPagem1'>$LastPagem1</a>";
                                        $paginate.= "<a href='$targetpage&page=$lastpage'>$lastpage</a>";
                                    }
                                    // Middle hide some front and some back
                                    elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2))
                                    {
                                        $paginate.= "<a href='$targetpage&page=1'>1</a>";
                                        $paginate.= "<a href='$targetpage&page=2'>2</a>";
                                        $paginate.= "...";
                                        for ($counter = $page - $stages; $counter <= $page + $stages; $counter++)
                                        {
                                            if ($counter == $page){
                                                $paginate.= "<span class='current'>$counter</span>";
                                            }else{
                                                $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                        }
                                        $paginate.= "...";
                                        $paginate.= "<a href='$targetpage&page=$LastPagem1'>$LastPagem1</a>";
                                        $paginate.= "<a href='$targetpage&page=$lastpage'>$lastpage</a>";
                                    }
                                    // End only hide early pages
                                    else
                                    {
                                        $paginate.= "<a href='$targetpage&page=1'>1</a>";
                                        $paginate.= "<a href='$targetpage&page=2'>2</a>";
                                        $paginate.= "...";
                                        for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++)
                                        {
                                            if ($counter == $page){
                                                $paginate.= "<span class='current'>$counter</span>";
                                            }else{
                                                $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}
                                        }
                                    }       
                                }       
                                        // Next
                                if ($page < $counter - 1){ 
                                    $paginate.= "<a href='$targetpage&page=$next'>Next</a>";
                                }else{
                                    $paginate.= "<span class='disabled'>Next</span>";
                                    }
                                $paginate.= "</div>";   
                            }
                            $resultData = $commonFunctions->getData('crm_add_bk',$where);
                        ?>
                        <table style="width: 100%;" class="table datatable_t table-hover table-striped table-bordered">
                            <thead>
                                <tr>
                                    <th  class="text-center">First Name</th>
                                    <th  class="text-center">Last Name</th>
                                    <th  class="text-center">Title</th>
                                    <th  class="text-center">Job Position</th>
                                    <th  class="text-center">Address</th>
                                    <th  class="text-center">City</th>
                                    <th  class="text-center">State / Province</th>
                                    <th  class="text-center">Country</th>
                                    <th  class="text-center">Postcode</th>
                                    <th  class="text-center">Prof Phone</th>
                                    <th  class="text-center">Pers Phone</th>
                                    <th  class="text-center">Email</th>
                                </tr>

                            </thead>
                            <tbody>
                                <?php foreach ($resultData as $rw) { ?>
                                    <tr>
                                        <td><?php echo $rw['first_name'];?></td>
                                        <td><?php echo $rw['last_name'];?></td>
                                        <td><?php echo $rw['title'];?></td>
                                        <td><?php echo $rw['job_position'];?></td>
                                        <td><?php echo $rw['address'];?></td>
                                        <td><?php echo $rw['city'];?></td>
                                        <td><?php echo @$commonFunctions->getname($rw['state_id'],"sys_erp_adm_countries_states","label",'rowid');?></td>
                                        <td><?php echo @$commonFunctions->getname($rw['country_id'],"sys_erp_adm_countries","label",'rowid');?></td>
                                        <td><?php echo $rw['postcode'];?></td>
                                        <td><?php echo $rw['prof_phone'];?></td>
                                        <td><?php echo $rw['pers_phone'];?></td>
                                        <td><?php echo $rw['email'];?></td>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                        <?php echo "<center>".$paginate."</center>";?>
                    </div><!--end card-body-->
                </div><!--end card-->
            </div><!--end col-->
                       
        </div><!-- end row -->
    <?php }else{ 
        if(!empty($_POST)){
            if(empty($_POST['last_name'])){
		        Session::set('msg', '<div class="alert alert-danger alert-dismissible mt-3" id="flash-msg"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Error !</strong> Please enter last name !</div>');
		    }
		    if(empty($_POST['first_name'])){
		        Session::set('msg', '<div class="alert alert-danger alert-dismissible mt-3" id="flash-msg"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Error !</strong> Please enter first name !</div>');
		    }

		    if(!empty($_POST['last_name']) and !empty($_POST['first_name']) ){
		        if($_GET['action'] == "add"){
		            $column = $fileName = "";
		            $category_id = @implode(',', $_POST['category_id']);
		            $commonFunctions->addData('crm_add_bk'," (first_name,last_name,title,job_position,address,postcode,city,country_id,state_id,prof_phone,pers_phone,mobile,fax,email,refuse_mass_emailings,instant_messaging,visibility,category_id,third_party_id) VALUES ('".$_POST['first_name']."','".$_POST['last_name']."','".$_POST['title']."','".$_POST['job_position']."','".$_POST['address']."','".$_POST['postcode']."','".$_POST['city']."','".$_POST['country_id']."','".$_POST['state_id']."','".$_POST['prof_phone']."','".$_POST['pers_phone']."','".$_POST['mobile']."','".$_POST['fax']."','".$_POST['email']."','".$_POST['refuse_mass_emailings']."','".$_POST['instant_messaging']."','".$_POST['visibility']."','".$category_id."','".$_POST['third_party_id']."' ) ",'address-book.php?state=form');
		        }
		        if($_GET['action'] == "edit"){
		            
		            $commonFunctions->updateData('crm_add_bk'," WHERE first_name = '".$_POST['first_name']."' ", " last_name='".$_POST['last_name']."', title='".$_POST['title']."' , job_position='".$_POST['job_position']."' , address='".$_POST['address']."' , postcode='".$_POST['postcode']."' , city='".$_POST['city']."' , country_id='".$_POST['country_id']."', state_id='".$_POST['state_id']."', prof_phone='".$_POST['prof_phone']."', pers_phone='".$_POST['pers_phone']."', mobile='".$_POST['mobile']."', fax='".$_POST['fax']."', email='".$_POST['email']."', refuse_mass_emailings='".$_POST['refuse_mass_emailings']."', instant_messaging='".$_POST['instant_messaging']."', visibility='".$_POST['visibility']."', category_id='".$_POST['category_id']."', third_party_id='".$_POST['third_party_id']."' ",'address-book.php?state=form');
		        }
		    }else{
		        echo "<script>location.href='address-book.php?state=form';</script>";
		    }
        }?>
        <div class="row">
            <div class=" col-sm-12">
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">Address Book</h4>
                        <?php echo !empty($msg)?$msg:''; ?>        
                        <?php echo !empty($msg1)?$msg1:''; ?>
                    </div>
                    <!--end card-header-->                                
                    <div class="card-body">
                        <form enctype="multipart/form-data" action="address-book.php?state=form&action=add" method="post" name="formsoc" autocomplete="off">      
                            <div class="form-row">
                                <input type="hidden" name="action" value="add">

                                <div class="position-relative form-group col-md-4">
                                    <label for="last_name" class="">Last Name <span class="error">*</span></label>
                                    <input type="text" maxlength="128" name="last_name" id="last_name" value="" autofocus="autofocus" class="form-control">
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="first_name" class="">First Name <span class="error">*</span></label>
                                    <input type="text" maxlength="128" name="first_name" id="first_name" value="" autofocus="autofocus" class="form-control">
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="third_party_id" class=""> Third Party </label>
                                    <?php $ThirdPartyData = $commonFunctions->getData('crm_cust_details',' '); ?>
                                    <select name="third_party_id" id="third_party_id" class="select2 form-control" >
                                        <option value="0">Select</option>
                                        <?php foreach ($ThirdPartyData as $rw) { ?>
                                            <option value="<?php echo $rw['id'];?>" <?php echo (@$_GET["customer_id"] == $rw['id'])?"selected":"";?> ><?php echo $rw['name']; ?></option>     
                                        <?php } ?>
                                    </select>
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="title" class=""> Title </label>
                                    <select class="flat form-control" name="title" id="title">
                                        <option value="">&nbsp;</option>
                                        <option value="MME">Mrs.</option>
                                        <option value="MR">Mr.</option>
                                        <option value="MLE">Ms.</option>
                                        <option value="MTRE">Master</option>
                                        <option value="DR">Doctor</option>
                                    </select>
                                </div>
                                
                                <div class="position-relative form-group col-md-4">
                                    <label for="job_position" class=""> Job Position </label>
                                    <textarea name="job_position" class="form-control"></textarea>
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="address" class=""> Address </label>
                                    <textarea name="address" class="form-control"></textarea>
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="postcode" class=""> Postcode </label>
                                    <input type="text" class="form-control" name="postcode" value="">
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="country_id" class=""> Country </label>
                                    <?php $countryData = $commonFunctions->getData('sys_erp_adm_countries',' WHERE active = 1 '); ?>
                                    <select name="country_id" id="country" class="select2 form-control" >
                                        <option value="0">Select Country</option>
                                        <?php foreach ($countryData as $rw) { ?>
                                            <option value="<?php echo $rw['rowid'];?>" ><?php echo $rw['label']."(".$rw['code'].")"; ?></option>     
                                        <?php } ?>
                                    </select>
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="state_id" class=""> State / Province </label>
                                    <?php $stateData = $commonFunctions->getData('sys_erp_adm_countries_states',' WHERE active = 1 '); ?>
                                    <select name="state_id" id="state" class="select2 form-control" >
                                        <option value="0">Select State / Province</option>
                                        <?php foreach ($stateData as $rw) { ?>
                                            <option value="<?php echo $rw['rowid'];?>" ><?php echo $rw['label']."(".$rw['region_code'].")"; ?></option>     
                                        <?php } ?>
                                    </select>
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="city" class=""> City</label>
                                    <input type="text" class="form-control" name="city" id="city" value="">
                                </div>

                                <div class="position-relative form-group col-md-4">
                                    <label for="prof_phone" class="">Prof. Phone</label>
                                    <input type="text" class="form-control" name="prof_phone" value="">
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="pers_phone" class="">Pers. Phone </label>
                                    <input type="text" class="form-control" name="pers_phone" value="">
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="mobile" class=""> Mobile </label>
                                    <input type="text" class="form-control" name="mobile" value="">
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="fax" class=""> Fax </label>
                                    <input type="text" class="form-control" name="fax" value="">
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="email" class=""> Email </label>
                                    <input type="email" class="form-control" name="email" value="">
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="refuse_mass_emailings" class=""> Refuse Mass eMailings</label>
                                    <select class="flat form-control" id="refuse_mass_emailings" name="refuse_mass_emailings">
                                        <option value="0">Yes</option>
                                        <option value="1" selected="">No</option>
                                    </select>
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="instant_messaging" class="">Instant Messaging</label>
                                    <input type="text" class="form-control" name="instant_messaging" value="">
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="visibility" class=""> Visibility</label>
                                    <select class="flat form-control" id="visibility" name="visibility">
                                        <option value="0">Shared</option>
                                        <option value="1" selected="">Private</option>
                                    </select>
                                </div>
                                <div class="position-relative form-group col-md-4">
                                    <label for="category_id" class=""> Cust./Prosp. Tags / Categories </label>
                                    <select id="category_id" name="category_id[]" class="flat category_id form-control">
                                        <option value="0"></option>
                                    </select>
                                </div>
                                
                                <div class="position-relative form-group col-md-12">
                                    <button type="submit" class="btn btn-success">Create</button>
                                    <a href="address-book.php?state=list"><button type="button" class="btn btn-danger">Back to Address Book List</button></a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    <?php } ?>    


<?php require "../inc/footer.php"; ?>
<script type="text/javascript">
$("#clearbtn").click(function(){
    $("#search").val('');
    $("#searchForm").submit();
});
$("#country").change(function(){
    var country = $("#country option:selected").val();
    $.ajax({
        type: 'POST',
        url: "",
        data: {"country_id":country,"action":"ajax_call"},
        success: function(response) { 
            obj = JSON.parse(response);
            $("#state").html("<option value=''>Select State / Province</option>"+obj.option);
        }
    });
})
$(function() {
    $("#city").autocomplete({
        source: function(request, response) {
            $.getJSON("", { country_id: $('#country option:selected').val(),state_id: $('#state option:selected').val(),keyword: request.term,action:"ajax_call1" }, response);
        },
        minLength: 2,
    });
});
</script>