<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
global $configverssion_id; global $configapp_version; global $userID; global $server; global $LANG; $resellerID = getReseller();
//=== List page stuffs =============
$page = 1; $setLimit = 30;
if(isset($_GET["page"])) $page = (int)$_GET["page"];
$pageLimit = ($page * $setLimit) - $setLimit; 
$pageurl=$_SERVER['REQUEST_URI']."?";
if(count($_GET)) { $pageurl = $_SERVER['REQUEST_URI'].'&'; }
$trans = array("s=d_o" => "", "s=d_n" => "", "s=p_h" => "", "s=p_l" => "", "s=s_r" => "", "s=s_u" => "");
$pageurl = strtr($pageurl,$trans);
$pageurl = str_replace('&&','&',$pageurl);
//====End ==============
define('TITLE','Contacts');
if(!isAdmin(getUser()) && (userData(getUser(),'phone') == '' || userData(getUser(),'first_name') == '') ) {
	header('location: profile?setting'); exit();
}
if(!isAdmin(getUser()) && userData($userID,'email_verified') != 0) {
	showVerify();
}
if(isResold($userID)) {
	header('location: phonebook'); exit();	
}
$today = date('Y-m-d'); $time = strtotime($today.'-1 months'); $lastMonth = date("Y-m", $time); $time = strtotime($today.'-1 years'); $lastYear = date("Y", $time);
?>
<?php
if(isset($_POST['buy'])) { 
	$list = mysqli_real_escape_string($server,$_POST['id']); 
	$cost = marketinglistData($list,'cost')*userExchangeRate($userID);
	$isPublic = marketinglistData($list,'is_public');
	$userbalance = userWalletBalance($userID);
	if(canAccessList($list,$userID)) {
		$_SESSION['message'] = $LANG['You have already purchased this Marketing List. No need to buy it again'];
		header('location: buycontact?err=1');	
		exit;
	}
	if($cost > $userbalance) {
		$_SESSION['message'] = $LANG['You do not have sufficient credits to buy this list. Please fund your account'];
		header('location: buycontact?err=1');	
		exit;
	}
	if($isPublic < 1) {
		$_SESSION['message'] = $LANG['Sorry but this list is no longer available for sale.'];
		header('location: buycontact?err=1');	
		exit;
	}
	//All is good... Lets do business
	mysqli_query($server, "INSERT INTO marketinglist_owners (`marketinglist_id`,`customer_id`, `is_owner`)	VALUES ('$list','$userID', '0');") or die (mysqli_error($server));
	
	$date = date('Y-m-d H:i:s', time());										$user_id = $userID;
	$description = 'Purchase of '.marketinglistData($list,'title');				$credits = 0-$cost;
	$description = mysqli_real_escape_string($server,$description);
	$method = 'system';															$cost = 0;
	$reference = genRandomPassword(6).time();	$gateway_response = '';
	$approved_by = 'System';					$is_earned = '0';
	$status = 'completed';						$validity = 0;
	
	mysqli_query($server, "INSERT INTO transactions (`date`,`customer_id`, `description`, `credits`, `cost`,`method`,`transaction_reference`,`approved_by`,`status`, `gateway_response`, `is_earned`, `validity`)	VALUES ('$date','$user_id', '$description', '$credits', '$cost','$method','$reference','$approved_by','$status', '$gateway_response', '$is_earned', '$validity');") or die (mysqli_error($server));
	mysqli_query($server, "UPDATE `transactions` SET `paid_on` =  '".date('Y-m-d H:i:s')."' WHERE `transaction_reference` = '$reference'");
	logEvent(getUser(),'Purchased marketing list #'.$list);
	createNotice($userID,"Congratulations! You have just purchased ".marketinglistData($list,'title'));
	$_SESSION['message'] = $LANG['You have successfully purchased'].' '.marketinglistData($list,'title').'. '.$LANG['You now have access to send messages to this marketing list.'];
	header('location: buycontact?err=0');
}

	$added = '';	
	if(isset($_GET['sc'])) {
		$keywords = mysqli_real_escape_string($server,$_GET['sc']);
		$ser = explode(' ', $keywords);
		$clauses = array();
		foreach($ser as $look){
			$term = trim(preg_replace('/[^a-z0-9]/i', '', $look));   
			if (!empty($term)){
				 $clauses[] = "title LIKE '%$term%' OR description = '%$term%'  OR id = '%$term%'";
			} else {
				 $clauses[] = " id LIKE '%%' ";
			}
		}
		$added .= ' AND ('.implode(' OR ', $clauses).') ';		
	}
	if(isset($_GET['s'])) {
		switch($_GET['s']) {
			case 'd_o': $added .= " order by id ASC ";
			break;
			case 'd_n': $added .= " order by id DESC ";
			break;
			case 's_r': $added .= " order by title DESC ";
			break;
			case 's_u': $added .= " order by title ASC ";
			break;
		}
	} else {
		$added .= " order by id DESC ";	
	}

    $query="SELECT * FROM marketinglist WHERE is_public = '1' $added limit $pageLimit,$setLimit";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));
	$x = mysqli_num_rows($result);
 ?>
<!-- Quick Navs ::::: You can customize this -->
 <div class="row no-m-t no-m-b">
 	<div class="col s12 m12 l12">
        <div class="card blue">
            <div class="card-content white-text"><?=$LANG['buycontact_tip']?></div>
        </div>
    </div>
 </div>
<div class="row no-m-t no-m-b">
 	<div class="col s12 m12 l12">
        <div class="card card-transparent">
            <div class="card-content">
            	<div class="col s12 m4 l4">
                	<h5><?=$LANG['Buy Contacts']?></h5>
                </div>
                <div class="col s12 m8 l8">
                  <div class="col s12 m12 l12">
                    <div class="row no-m-t no-m-b">
                     <form action="buycontact" method="get">
                     <div class="input-field col s12">
                        <i class="material-icons prefix">search</i>
                        <input type="text" name="sc" value="<?=@$_GET['sc']?>" placeholder="<?=$LANG['Search...']?>">
                     </div>
                     </form>  
                    </div>
                  </div> 
                </div>
            </div>
        </div>
    </div>
 </div>
 
	<div class="row no-m-t no-m-b">
       <div class="col s12 m12 l12">
         <div class="card card-white">
            <div class="card-content">
            <div class="card-title">
            	<a class='dropdown-button btn btn-flat' href='#' data-activates='filter' data-beloworigin='true' data-constrainwidth='false'><?=$LANG['Sort']?></a>
                <ul id='filter' class='dropdown-content'>
                    <li><a href="<?=$pageurl?>s=d_o" ><?=$LANG['Oldest First']?></a></li>
                    <li><a href="<?=$pageurl?>s=d_n" ><?=$LANG['Newest First']?></a></li>
                    <li><a href="<?=$pageurl?>s=s_r" ><?=$LANG['Title ID Z-A']?></a></li>
                    <li><a href="<?=$pageurl?>s=s_u" ><?=$LANG['Title ID A-Z']?></a></li>
                    <li><a href="<?=$pageurl?>s=p_l" ><?=$LANG['Price Lowest']?></a></li>
                    <li><a href="<?=$pageurl?>s=p_h" ><?=$LANG['Price Highest']?></a></li>
                </ul>
            </div>
            <span class="card-title"><a class='btn light-blue darken-4' href='marketinglist'><?=$LANG['My Marketing Lists']?></a></span>
       		<table class="highlight responsive-table">
            <?php if($x>0) { ?>
                <thead>
                	<tr>
                        <th data-field="to"><?=$LANG['List']?></th>
                        <th data-field="from"><?=$LANG['Description']?></th>
                        <th data-field="to"><?=$LANG['Contacts']?></th>
                        <th data-field="message"><?=$LANG['Price']?></th>
                        <th data-field="act"></th>
                    </tr>
                 </thead>
               <?php } ?>  
                 <tbody>
<?php $xf=0; while ($rows = mysqli_fetch_assoc($result)) { $xf+=1; ?>
                    <form action="buycontact" method="post" id="inbox-form" onsubmit="return confirm('<?=$LANG['contactbuy_confirm']?>');">
						<input type="hidden" name="id" value="<?=$rows['id']?>"/>
						<tr class="">
                             <td><?=ucfirst($rows['title'])?></td>
                             <td><?=$rows['description']?></td>
                             <td><?=countContacts($rows['id'],'marketing')?> <?=$LANG['Contacts']?></td>
                             <td><?=userCurrencySymbol($userID).number_format((userExchangeRate($userID)*$rows['cost']),userCurrencyZero($userID))?></td>
                             <td>
                             <?php if(canAccessList($rows['id'],$userID)) { ?>
                             <span class="green-text"><?=$LANG['Purchased']?></span>
                             <?php } else { ?>
                             <button type="submit" name="buy" class="btn blue"><i class="fa fa-money"></i> <?=$LANG['Buy']?></button>
                             <?php } ?>
                             </td>
                        </tr>
					</form>
<?php } ?>
<?php if($xf<1) echo '<tr class="orange lighten-5"><td colspan=10><h5 class="center-align">'.$LANG['No records found!'].'</h5></td></tr>' ?>	
                 </tbody>
            </table>  
          </div>
        </div>          
     </div>
  </div>
 <div class="row">
 	<div class="col s12 m12 l12" style="margin-top: 5px;">
        <?php displayPagination($setLimit,$page,$query);  ?>
    </div>
 </div>                       
