<?php 
include '../backend/db/db.php';
session_start();

date_default_timezone_set('Asia/Colombo');
$date = date('Y-m-d H:i:s');

require("../PHPMailer/class.phpmailer.php");

/***************************** New User Reg ****************************/

if (isset($_POST['reg_btn'])) {
	$fname = htmlspecialchars(strip_tags(trim($_POST['fname'])), ENT_QUOTES, 'UTF-8');
	$lname = htmlspecialchars(strip_tags(trim($_POST['lname'])), ENT_QUOTES, 'UTF-8');
	$address_1 = htmlspecialchars(strip_tags(trim($_POST['address_1'])), ENT_QUOTES, 'UTF-8');
	$address_2 = htmlspecialchars(strip_tags(trim($_POST['address_2'])), ENT_QUOTES, 'UTF-8');
	$city = htmlspecialchars(strip_tags(trim($_POST['city'])), ENT_QUOTES, 'UTF-8');
	$email = htmlspecialchars(strip_tags(trim($_POST['email'])), ENT_QUOTES, 'UTF-8');
	$tel_no = htmlspecialchars(strip_tags(trim($_POST['tel_no'])), ENT_QUOTES, 'UTF-8');
	$pw = htmlspecialchars(strip_tags(trim($_POST['password'])), ENT_QUOTES, 'UTF-8');
	
	$password = hash('sha256', $pw);
	$sql = "INSERT INTO customer_reg SET userID='$email', passWord='$password', order_id=1, f_name='$fname', l_name='$lname', tel_no='$tel_no', address_1='$address_1', address_2='$address_2', city='$city', email='$email', val=1, reg_date=now()";
	
	$sql_u = mysqli_query($conn, "SELECT userID FROM customer_reg WHERE userID='$email'");
	if(mysqli_num_rows($sql_u) == 0) {
	  
	  if (mysqli_query($conn, $sql)) {
	  	$sql_uid = mysqli_fetch_assoc(mysqli_query($conn, "SELECT cusID FROM customer_reg WHERE userID='$email' AND val=1"));
		$uid = $sql_uid['cusID'];
		
		if (isset($_SESSION['temp_user_bb'])) {
			$tmp_id = htmlspecialchars(strip_tags(trim($_SESSION['temp_user_bb'])), ENT_QUOTES, 'UTF-8');
			$sqlt = mysqli_query($conn, "SELECT
live_cart.inv_no
FROM
live_cart
Inner Join order_details_temp ON order_details_temp.inv_no = live_cart.inv_no
WHERE
live_cart.temp_id = $tmp_id");
			if(mysqli_num_rows($sqlt) == 0) {
				
			} else {
				$row_inv = mysqli_fetch_assoc($sqlt);
				$inv = $row_inv['inv_no'];
			}			
			
			$sql_up = "UPDATE live_cart SET User_ID=$uid, temp_id=0 WHERE temp_id=$tmp_id";
			
			if (mysqli_query($conn, $sql_up)) {
				if(mysqli_num_rows($sqlt) == 0) {
					
				} else {
					mysqli_query($conn, "UPDATE order_details_temp SET user_id=$uid, guest=0 WHERE user_id=$tmp_id AND inv_no='$inv'");
				}
				
				unset($_SESSION['temp_user_bb']);
				unset($_SESSION['guest_user_bb']);
				
				$_SESSION['normal_user_bb'] = $uid;
							
				$response['status'] = '1'; // log in
				$response['tel_no'] = $tel_no;
				$response['email'] = $email;
				$response['message'] = 'Sucessfully Registered.';				
			}
		
		} else {
			$_SESSION['normal_user_bb'] = $uid;
			
			$response['status'] = '2'; // log in
			$response['tel_no'] = $tel_no;
			$response['email'] = $email;
			$response['message'] = 'Sucessfully Registered.';			
		}
		
		/***************** Customer Email ******************/
		  
		$message = '<!DOCTYPE html>';
		$message .= '<html><head><title></title></head><body>';
		$message .= '<p style="margin-bottom: 20px;">Thank you for registered on buddhistbooksonline.com <br>Your Account Details</p>';
		$message .= '<table style = "width: 100%;margin-top: 10px;" border="0">';
		$message .= '<tr><td style = "width: 15%;"><b>Name:</b> </td><td>'.$fname.' '.$lname.'</td></tr>';
		$message .= '<tr><td><b>Address:</b> </td><td>'.$address_1.' '.$address_2.' '.$city.'</td></tr>';
		$message .= '<tr><td><b>Contact No:</b> </td><td>'.$tel_no.'</td></tr>';
		$message .= '<tr><td><b>Username:</b> </td><td>'.$email.'</td></tr>';
		$message .= '<tr><td><b>Date:</b> </td><td>'.date('Y-m-d H:i:s').'</td></tr>';
		$message .= '</table><br>
				<img src="https://buddhistbooksonline.com/images/logo/logo.png" style = "margin : 20px 0;" width="250">
				<br>Samudra Book Shop<br>
				Contact No: (+94) 37 223 4446<br>
				Website: www.samudrabooks.com<br>
				</body></html>';
		
		//echo $message;
		try {
			$mail = new PHPMailer();
			$mail->IsSMTP(); // set mailer to use SMTP
			$mail->Host = $email_host;  // specify main and backup server
			$mail->SMTPAuth = true;     // turn on SMTP authentication
			$mail->Username = $server_email_add;  // SMTP username
			$mail->Password = $server_email_pw; // SMTP password
			$mail->SMTPSecure = 'ssl';
			$mail->Port = 465;
			$mail->From = $server_email_from;
			$mail->FromName = "buddhistbooksonline.com";
			$mail->AddAddress($email, $fname.' '.$lname);
			$mail->AddReplyTo("info@buddhistbooksonline.com", "buddhistbooksonline.com");
			$mail->IsHTML(true); // set email format to HTML
			$mail->Subject = "User Account Details";
			$mail->Body    = $message;

			if($mail->Send())
			{

			} else {
			   //echo "Message could not be sent.";
			   //echo "Mailer Error: " . $mail->ErrorInfo;
			}
		
		} catch(phpmailerException $ex) {
			//$err_msg = $ex->errorMessage();
		}
		
		/***************** Company Email ********************/

		$message1 = '<!DOCTYPE html>';
		$message1 .= '<html><head><title></title></head><body>';
		$message1 .= '<p style="margin-bottom: 20px;">User Registration Details</p>';
		$message1 .= '<table style = "width: 100%;margin-top: 20px;" border="0">';
		$message1 .= '<tr><td style = "width: 15%;"><b>Name:</b> </td><td>'.$fname.' '.$lname.'</td></tr>';
		$message1 .= '<tr><td><b>Address:</b> </td><td>'.$address_1.' '.$address_2.' '.$city.'</td></tr>';
		$message1 .= '<tr><td><b>Contact No:</b> </td><td>'.$tel_no.'</td></tr>';
		$message1 .= '<tr><td><b>Email:</b> </td><td>'.$email.'</td></tr>';
		$message1 .= '<tr><td><b>Date:</b> </td><td>'.date('Y-m-d H:i:s').'</td></tr>';
		$message1 .= '</table><img src="https://buddhistbooksonline.com/images/logo/logo.png" style = "margin : 20px 0 20px 0;" width="250"></body></html>';
		//echo $message1;
		
		try {
			$mail1 = new PHPMailer();
			$mail1->IsSMTP(); // set mailer to use SMTP
			$mail1->Host = $email_host;  // specify main and backup server
			$mail1->SMTPAuth = true;     // turn on SMTP authentication
			$mail1->Username = $server_email_add;  // SMTP username
			$mail1->Password = $server_email_pw; // SMTP password
			$mail1->SMTPSecure = 'ssl';
			$mail1->Port = 465;
			$mail1->From = $server_email_from;
			$mail1->FromName = "buddhistbooksonline.com";
			$mail1->AddAddress("nirmal@samudrabooks.com", "Nirmal Ranasinghe");
			//$mail1->AddAddress("nuwanthi@cyclomax.net", "nuwa");
			$mail1->AddReplyTo($email, $fname.' '.$lname);
			$mail1->IsHTML(true); // set email format to HTML
			$mail1->Subject = "New User Registration";
			$mail1->Body    = $message1;

			if(!$mail1->Send())
			{
			   //echo "Message could not be sent.";
			   //echo "Mailer Error: " . $mail->ErrorInfo;
			   exit;
			}
		
		} catch(phpmailerException $ex) {
			//$err_msg = $ex->errorMessage();
		}
		
		/****************** // ********************/
  
	  } else {
		  $response['status'] = 'error';
		  // wrong details
		  $response['message'] = 'Something went wrong, please try again.';
	  }		
		
	} else {
	  $response['status'] = 'error';
	  $response['message'] = 'Provided Email is already in use. Please Try Again';		
	}
	echo json_encode($response);
}

/***************************** User Login *****************************/

if (isset($_POST['login_btn'])) {
    $email = htmlspecialchars(strip_tags(trim($_POST['username'])), ENT_QUOTES, 'UTF-8');
    $pass = htmlspecialchars(strip_tags(trim($_POST['password'])), ENT_QUOTES, 'UTF-8');
    $password = hash('sha256', $pass);
	
    $sql = mysqli_query($conn, "SELECT cusID, passWord, order_id FROM customer_reg WHERE userID='$email' AND val=1");
    $row = mysqli_fetch_assoc($sql);

    if (mysqli_num_rows($sql) == 1 && $row['passWord'] == $password) {
		$uid = $row['cusID'];
		$oid = $row['order_id'];
		
		if (isset($_SESSION['temp_user_bb'])) {
			$tmp_id = htmlspecialchars(strip_tags(trim($_SESSION['temp_user_bb'])), ENT_QUOTES, 'UTF-8');
			
			$sql_invo = mysqli_query($conn, "SELECT inv_no FROM live_cart WHERE User_ID=$uid AND temp_id=0");
			if(mysqli_num_rows($sql_invo) == 0) {
				$sql_up = "UPDATE live_cart SET User_ID=$uid, order_id=$oid, temp_id=0 WHERE temp_id=$tmp_id";			
			
			} else {
				$row_invo = mysqli_fetch_assoc($sql_invo);
				$inv_cart = $row_invo['inv_no'];
				$sql_up = "UPDATE live_cart SET User_ID=$uid, inv_no='$inv_cart', order_id=$oid, temp_id=0 WHERE temp_id=$tmp_id";				
			}
			
			$sqlt = mysqli_query($conn, "SELECT
live_cart.inv_no
FROM
live_cart
Inner Join order_details_temp ON order_details_temp.inv_no = live_cart.inv_no
WHERE
live_cart.temp_id = $tmp_id");
			if(mysqli_num_rows($sqlt) == 0) {
				
			} else {
				$row_inv = mysqli_fetch_assoc($sqlt);
				$inv = $row_inv['inv_no'];
			}
			
			if (mysqli_query($conn, $sql_up)) {
				if(mysqli_num_rows($sqlt) == 0) {
					
				} else {
					mysqli_query($conn, "UPDATE order_details_temp SET user_id=$uid, guest=0 WHERE user_id=$tmp_id AND inv_no='$inv'");
				}
				
				unset($_SESSION['temp_user_bb']);
				unset($_SESSION['guest_user_bb']);
				
				$_SESSION['normal_user_bb'] = $uid;
				$response['status'] = '1'; // log in to checkout
			}
		
		} else {
			$sql_invo = mysqli_query($conn, "SELECT inv_no FROM live_cart WHERE User_ID = $uid AND temp_id=0");
			if(mysqli_num_rows($sql_invo) == 0) {
			
			} else {
				$row_invo = mysqli_fetch_assoc($sql_invo);
				$inv = $row_invo['inv_no'];
				mysqli_query($conn, "UPDATE live_cart SET inv_no='$inv' WHERE User_ID = $uid");
			}
			
			$_SESSION['normal_user_bb'] = $uid;
			$response['status'] = '2'; // log in to website
		}
		    
	} else {
        $response['status'] = 'error';
        // wrong details
        $response['message'] = 'Incorrect Username or Password.';
    }

	echo json_encode($response);
}
?>