<?php

session_start();


/* * **************How this page work******************
 *
 * Login section search for the first user matchable with $_POST['username']/['password'],
 * then pass some of his info to $_SESSION.
 * Redirect section pass an js to redirect user,it may also update the user last login time in db,
 * or terminate current process if no match return in login section.
 *
 * The program walk down to the cart modify section if it hasn't terminated,where it will look for the
 * $_SESSION['Tusername'](a string of datetime created for  table `cart`=>column `username`)
 * It will try to match a `cart` row with the Tusername,if the logged user has another cart with the same product name,
 * the section will increase the amount of the original cart(the one that with the actul username).
 * However,if no cart with the same user and product was found,this section will reassign the temporary 
 * cart(with the Tusername) under current username.
 *
 * I rewrite the database connect method but not the logic.
 *
 */



if (@$_GET['action'] == "logout") {
    session_unset();
    $url = "../e-shop.php";
    echo "<script language='javascript' 
	type='text/javascript'>";
    echo "window.location.href='$url'";
    echo "</script>";
    exit();
}

if (!isset($_POST['submit'])) {
    exit('Fail!');
}
include('../../conf/conn.php');

$username = mysqlSecurity($conn, $_POST['username']);
$password = base64_encode($_POST['password']);
$_SESSION['page'] = "0";

//Login section
$query = "SELECT `username`,`id`,`email`,`phone`,`first name`,`last name`,`address` FROM `clients`
			WHERE (`username` COLLATE utf8_bin = ? OR `email` COLLATE utf8_bin = ?) 
			AND `password`= ? AND `status` != 'delete' LIMIT 1";
$sqlStmt = mysqli_stmt_init($conn);
if (mysqli_stmt_prepare($sqlStmt, $query)) {
    mysqli_stmt_bind_param($sqlStmt, "sss", $username, $username, $password);
    mysqli_stmt_execute($sqlStmt);
    mysqli_stmt_bind_result($sqlStmt, $_SESSION['username'], $_SESSION['id'], 
            $_SESSION['email'], $_SESSION['phone'], $_SESSION['first_name'], 
            $_SESSION['last_name'], $_SESSION['address']
    );
    $loginResponse = mysqli_stmt_fetch($sqlStmt);
    mysqli_stmt_close($sqlStmt);
}

//Redirect section
if ($loginResponse == true && is_numeric($_SESSION['id'])) {
    $now = date("Y-m-d H:i:s");
    $updateLogin = mysqli_stmt_init($conn);
    $updateLoginSyntax = "UPDATE `clients` SET `logintime` = ? WHERE `id`= ?";
    mysqli_stmt_prepare($updateLogin, $updateLoginSyntax);
    mysqli_stmt_bind_param($updateLogin, "ss", $now, $_SESSION['id']);
    mysqli_stmt_execute($updateLogin);
    mysqli_stmt_close($updateLogin);
    $url = "../e-shop.php";
    echo "<script language='javascript' 
	type='text/javascript'>";
    echo "window.location.href='$url'";
    echo "</script>";
} else {
    $_SESSION["page"] = 5;
    $_SESSION["fail"] = 1;
    $url = "../e-shop.php";
    echo "<script language='javascript' 
    type='text/javascript'>";
    echo "window.location.href='$url'";
    echo "</script>";
    exit("Login failed.");
}


//Cart modify section
if (isset($_SESSION["Tusername"])) {
    $tCratQuery = "SELECT `product_name`,`amount` FROM `cart` WHERE `username` = ?";
    $tCartSelected = mysqli_stmt_init($conn);
    if (mysqli_stmt_prepare($tCartSelected, $tCratQuery)) {
        mysqli_stmt_bind_param($tCartSelected, "s", $_SESSION["Tusername"]);
        mysqli_stmt_execute($tCartSelected);
        mysqli_stmt_bind_result($tCartSelected, $tProductName, $tAmount
        );
        $tCartResponse = mysqli_stmt_fetch($tCartSelected);
        mysqli_stmt_close($tCartSelected);
    }
    if ($tCartResponse) {
        $cartQuery = "SELECT `amount` FROM `cart` WHERE `username` = ? AND `product_name` = ?";
        $cartSelected = mysqli_stmt_init($conn);
        mysqli_stmt_prepare($cartSelected, $cartQuery);
        mysqli_stmt_bind_param($cartSelected, "ss", $_SESSION["username"], $tProductName);
        mysqli_stmt_execute($cartSelected);
        mysqli_stmt_bind_result($cartSelected, $amount);
        $cartResponse = mysqli_stmt_fetch($cartSelected);
        mysqli_stmt_close($cartSelected);
        if ($cartResponse) {
            $amount = $tAmount + $amount;
            $updateCartSyntax = "UPDATE `cart` SET `amount` = ? WHERE `username` = ? AND `product_name` = ?";
            $updateCart = mysqli_stmt_init($conn);
            mysqli_stmt_prepare($updateCart, $updateCartSyntax);
            mysqli_stmt_bind_param($updateCart, "sss", $amount, $_SESSION['username'], $tProductName);
            $updateResponse = mysqli_stmt_execute($updateCart);
            mysqli_stmt_close($updateCart);
            $_SESSION["page"] = 2;
            unset($_SESSION["Tusername"]);
        } else {
            $updateCart = mysqli_stmt_init($conn);
            $updateCartSyntax = "UPDATE `cart` SET `username` = ? WHERE `username` = ?";
            mysqli_stmt_prepare($updateCart, $updateCartSyntax);
            mysqli_stmt_bind_param($updateCart, "ss", $_SESSION['username'], $_SESSION['Tusername']);
            $updateResponse = mysqli_stmt_execute($updateCart);
            mysqli_stmt_close($updateCart);
            $_SESSION["page"] = 2;
            unset($_SESSION["Tusername"]);
        }
    }
}
?>