<?php 
include 'check.php';
include '../db.inc.php';
include 'check_msg.php';




// print_r($_POST);
// exit;
if(isset($_POST['importSubmit'])) {
    
  // Allowed mime types
  $csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
  
  // Validate whether selected file is a CSV file
  if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $csvMimes)) {
      
      // If the file is uploaded
      if(is_uploaded_file($_FILES['file']['tmp_name'])){


          
          // Open uploaded CSV file with read-only mode
          $csvFile = fopen($_FILES['file']['tmp_name'], 'r');
          
          // Skip the first line
          fgetcsv($csvFile);
          
          // Parse data from CSV file line by line
          while(($line = fgetcsv($csvFile)) !== FALSE) {

        

              // Get row data
              $accid   = $line[0];
              $tid  = $line[1];
              $dt = str_replace("/","-",$line[2]);
              $date  = date('Y-m-d h:i:s',strtotime($dt));
              $type = $line[3];
              $amount = number_format(str_replace(",","",$line[4]),2,".","");;
              $notes = $line[5];
              $status = $line[6];

              $acc_number = $_POST['account_id'];
              $userss  =mysqli_fetch_array(mysqli_query($connectionString,"SELECT * FROM users WHERE number=$acc_number LIMIT 1"),MYSQLI_ASSOC);



              // // Check whether member already exists in the database with the same email
              // $prevQuery = "SELECT id FROM members WHERE email = '".$line[1]."'";
              // $prevResult = $db->query($prevQuery);
              // if($prevResult->num_rows > 0){
              //     // Update member data in the database
              //     $db->query("UPDATE members SET name = '".$name."', phone = '".$phone."', status = '".$status."', modified = NOW() WHERE email = '".$email."'");
              // }else{
                // Insert member data in the database
                $us_id = $userss['id'];
                $sql="INSERT INTO `history` (`tid` ,`number`,`other_import_number`,`user_id` ,`date` ,`amount` ,`type` ,`details` ,`status`)VALUES ( '$tid', '$acc_number','$accid',$us_id, '$date' , '$amount', '$type', '$notes', '$status')";

                if(!mysqli_query($connectionString,$sql)) {
                  echo("Error description: " . mysqli_error($connectionString));exit;
                }

                $a = strtolower($type);
                if (strpos($a, 'credit') !== false) {
                  $bal=$userss['balance'] + $amount;
                  $bal2=$userss['balance2'] + $amount;
                } else if(strpos($a, 'payin') !== false) {
                  $bal=$userss['balance'] + $amount;
                  $bal2=$userss['balance2'] + $amount;
                }
                // if($type=="Credit" || $type=="Payin") {
                //   $bal=$userss['balance'] + $amount;
                //   $bal2=$userss['balance2'] + $amount;
                // }
                else {
                  $bal=$userss['balance'] - $amount;
                  $bal2=$userss['balance2'] - $amount;
                }

                if(!mysqli_query($connectionString,"UPDATE users SET balance='$bal', balance2='$bal2' WHERE number='$acc_number' LIMIT 1")) {
                  echo("Error description: " . mysqli_error($connectionString));exit;
                }

              //}
          }
          
          // Close opened CSV file
          fclose($csvFile);
          
          $qstring = '?status=succ';
      } else {
          $qstring = '?status=err';

          //exit("exit");
      }
  } else {

      //exit("Wrong");
      $qstring = '?status=invalid_file';
  }
?>


  <script>
    alert('Transaction import successfully!');
    window.location.href = 'viewact.php?number=<?php echo $_POST['account_id']?>';
  </script>
<?php
  // Redirect to the listing page
  //header("Location: index.php".$qstring);

}









if(isset($_POST['submit'])) {
	$accid=$_POST['accid'];
	$date=$_POST['date'];
	$type=$_POST['type'];
	$amount=$_POST['amount'];
	$notes=addslashes($_POST['notes']);
	$status=$_POST['status'];
	$tid=rand(100000,999999);
	$sql="INSERT INTO `history` (`id` ,`tid` ,`number` ,`date` ,`amount` ,`type` ,`details` ,`status`)VALUES ('' , '$tid', '$accid', '$date' , '$amount', '$type', '$notes', '$status')";
	mysqli_query($connectionString,$sql);
	
	if($status == "Successful") {
		$user=mysqli_fetch_array(mysqli_query($connectionString,"SELECT * FROM users WHERE number='$accid' LIMIT 1"),MYSQLI_ASSOC);
		if($type=="Account Credit" || $type=="Direct Payin") {
			$bal=$user['balance'] + $amount;
			$bal2=$user['balance2'] + $amount;
		}
		else {
			$bal=$user['balance'] - $amount;
			$bal2=$user['balance2'] - $amount;
		}
	
		mysqli_query($connectionString,"UPDATE users SET balance='$bal', balance2='$bal2' WHERE number='$accid' LIMIT 1");



$user=mysqli_fetch_array(mysqli_query($connectionString,"SELECT * FROM users WHERE $accid=number LIMIT 1"),MYSQLI_ASSOC);

             $recipient=$user['email'];
		$mob_tel=$user['phone'];
		$first_name=$user['firstname'];
		$last_name=$user['lastname'];
                $senderName = "HNV Private Bank";

$fromEmailAddress = "no-reply-accountdept@hnvpb.com";

$emailSubject = "Transaction Alert";

$comments = "\n Hello $first_name $last_name \n \n This is to inform you that a transaction has occurred in your account. \n\n TRANSACTION DETAILS \n\n TRANSACTION TYPE: $type \n TRANSACTION STATUS: $status \n TRANSACTION ID: $tid \n AMOUNT: $amount \n DATE: $date \n DESCRIPTION: $notes \n NEW BALANCE: $bal \n \n \n \n Best regards, \n Account Support Team \n For HNV Private Bank.";


/* mail($recipient, $emailSubject, $comments, "From: $senderName <$fromEmailAddress>\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: 8bit"); */


	}
?>
<script>
alert('Activity successfully inserted');
location.replace('viewact.php');
</script>
<?php
exit;
}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Administrator</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>

<body>
<table width="96%" height="421" border="0" cellspacing="5">
  <tr>
    <td width="14%" height="274" valign="top" style="border:#003399 1px solid;"><table width="100%" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td height="21" bgcolor="#FF0000" class="headers">Navigation</td>
      </tr>
      <tr>
        <td><table width="100%" border="0" cellspacing="1">
          <tr>
            <td bgcolor="#E8FFF8"><p><font size="2" face="Arial, Helvetica, sans-serif"><strong><a href="./">Home</a></strong></font></p></td>
          </tr>
           <tr>
            <td bgcolor="#E8FFF8"><p><font size="2" face="Arial, Helvetica, sans-serif"><strong><a href="smssender.php">SMS 
              Sender</a></strong></font></p></td>
          </tr>
          <tr>
            <td bgcolor="#E8FFF8"><p><font size="2" face="Arial, Helvetica, sans-serif"><strong><a href="add.php">Add 
              User</a></strong></font></p></td>
          </tr>

          <tr>
            <td bgcolor="#E8FFF8"><a href="viewact.php"><font size="2" face="Arial, Helvetica, sans-serif"><strong>View Activities </strong></font></a></td>
          </tr>
          <tr>
            <td bgcolor="#E8FFF8"><a href="messages.php"><font size="2" face="Arial, Helvetica, sans-serif"><strong>View Messages (<?php echo $umsg; ?>)</strong></font></a></td>
          </tr>
          <tr>
            <td bgcolor="#E8FFF8"><a href="alerts.php"><font size="2" face="Arial, Helvetica, sans-serif"><strong>View Alerts</strong></font></a></td>
          </tr>
          
          <tr>
            <td bgcolor="#E8FFF8"><a href="sql.php"><font size="2" face="Arial, Helvetica, sans-serif"><strong>SQL</strong></font></a></td>
          </tr>
		  
          <tr>
            <td bgcolor="#E8FFF8"><font size="2" face="Arial, Helvetica, sans-serif"><strong><a href="logout.php">Log 
              Out</a></strong></font></td>
          </tr>
        </table>
        <p>&nbsp;</p>
          </td>
      </tr>
    </table>      
      <p>&nbsp;</p>
    </td>
    <td width="86%" valign="top" style="border:#003399 1px solid;"><table width="100%" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td height="21" bgcolor="#FF0000" class="headers">Add Activity </td>
      </tr>
      <tr>
        <td>
          <form action="import.php"  method="post" enctype="multipart/form-data">
            <table width="100%" border="0" cellspacing="1">
              <tr>
                <td width="14%" bgcolor="#E8FFF8">Add File </td>
                <td width="86%" bgcolor="#E8FFF8">
                  <input name="account_id" type="hidden" value="<?php echo $_GET['number'] ?>" />
                  <input name="file" type="file" />
                </td>
              </tr>
              <tr>
                <td valign="top" bgcolor="#E8FFF8">&nbsp;</td> 
                <td bgcolor="#E8FFF8"><input name="importSubmit" type="submit" id="submit" value="Save"></td>
              </tr>
            </table>
          </form>
          </td>
      </tr>
    </table>      
      <p>&nbsp;</p>
    </td>
  </tr>
</table>


</body>
</html>
