<?php
session_start();
// if don't have session user..then
if(!isset($_SESSION["memid"])){
    die("<script>alert('Please login first to purchase in our shop!');
    window.location.href='login.html';
    </script>");

    session_write_close();
}
?>
<?php 
//shop.php
include("conn.php");
$message = '';

if(isset($_POST["add_to_cart"]))
{   
    //check for buyamount to stock availability
    $buyamount = $_POST['quantity'];
    $stock = $_POST['hidden_stock'];

    if($buyamount > $stock)
    {
        die("<script>alert('Sorry, there is no enough stock for number of desired item you want to buy!');
            window.history.go(-1);
            </script>");
    }

    if(isset($_COOKIE["shopping_cart"]))
    {
        $cookie_data = stripslashes($_COOKIE['shopping_cart']);

        $cart_data = json_decode($cookie_data, true);
    }
    else
    {
        $cart_data = array();
    }

    $item_id_list = array_column($cart_data, 'item_id');

    if(in_array($_POST["hidden_id"], $item_id_list))
    {
        foreach($cart_data as $keys => $values)
        {
            if($cart_data[$keys]["item_id"] == $_POST["hidden_id"])
            {
                $cart_data[$keys]["item_quantity"] = $cart_data[$keys]["item_quantity"] + $_POST["quantity"];
            }
        }
    }
    else
    {
        $item_array = array(
        'item_id'   => $_POST["hidden_id"],
        'item_name'   => $_POST["hidden_name"],
        'item_price'  => $_POST["hidden_price"],
        'item_quantity'  => $_POST["quantity"]
        );
        $cart_data[] = $item_array;
    }

    
    $item_data = json_encode($cart_data);
    setcookie('shopping_cart', $item_data, time() + (86400 * 30));
    header("location:shop.php?success=1");
}

if(isset($_GET["action"]))
{
    if($_GET["action"] == "delete")
    {
        $cookie_data = stripslashes($_COOKIE['shopping_cart']);
        $cart_data = json_decode($cookie_data, true);
        foreach($cart_data as $keys => $values)
        {
            if($cart_data[$keys]['item_id'] == $_GET["id"])
            {
                unset($cart_data[$keys]);
                $item_data = json_encode($cart_data);
                setcookie("shopping_cart", $item_data, time() + (86400 * 30));
                header("location:shop.php?remove=1");
            }
        }
    }
    if($_GET["action"] == "clear")
    {
        setcookie("shopping_cart", "", time() - 3600);
        header("location:shop.php?clearall=1");
    }
}

if(isset($_GET["success"]))
{
    $message = '
    <div class="alert alert-success alert-dismissible">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
        Item Added into Cart
    </div>
    ';
}

if(isset($_GET["remove"]))
{
    $message = '
    <div class="alert alert-success alert-dismissible">
    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
    Item removed from Cart
    </div>
    ';
}

if(isset($_GET["clearall"]))
{
    $message = '
    <div class="alert alert-success alert-dismissible">
    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
    Your Shopping Cart has been clear...
    </div>
    ';
}
?>

<!DOCTYPE html>
<html>
    <head>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap -->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
        
        <link rel="shortcut icon" href="images/logo.png" type="image/x-icon" />
        <link rel="stylesheet" href="style.css">
        <link rel="stylesheet" href="shopStyle.css">
        <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
        <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Courgette&display=swap" rel="stylesheet">
        <script src="https://kit.fontawesome.com/0c641bf868.js" crossorigin="anonymous"></script>
        <link href="https://fonts.googleapis.com/css?family=Acme&display=swap" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Teko:700&display=swap" rel="stylesheet">

        <title>Supreme Sports Shop</title>

        <style>
        html{
            scroll-behavior: smooth;
        }
        #btnScrollToTop{
            position:fixed;
            right: 20px;
            bottom: 20px;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: #e62739;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.25);
            color: #ffffff;
            border: none;
            outline: none;
            cursor: pointer;
            z-index: 99;
        }
        #btnScrollToTop:active{
            background: #cc2333;
        }
        .curved{
            background:linear-gradient( rgba(0, 0, 250, 0.25), rgba(125, 250, 250, 0.45)),url(images/shop_svg.jpg);
            background-size: cover;
            background-attachment: fixed;
            color:white !important;
            text-align: center;
        }
        .curved h1{
            padding-top: 70px;
            font-family: 'Teko', sans-serif;
            font-size: 55px;
        }
        .curved svg{
            display: block;
            margin-top: -200px;
        }
        @media only screen and (min-width: 1101px) and (max-width: 1320px) {
            .productborder{
                margin-left: 65px;
            }
        }
        @media only screen and (min-width: 888px) and (max-width: 1100px) {
            .curved h1{
                padding-top: 60px;
                font-family: 'Teko', sans-serif;
                font-size: 55px;
            }
            .curved svg{
                display: block;
                margin-top: -150px;
            }
            .productborder{
                margin-left: 45px;
            }
        }
        @media only screen and (min-width: 670px) and (max-width: 887px) {
            .curved h1{
                padding-top: 45px;
                font-family: 'Teko', sans-serif;
                font-size: 45px;
            }
            .curved svg{
                display: block;
                margin-top: -100px;
            }
            .productborder{
                margin-left: 35px;
            }
        }
        @media only screen and (max-width: 669px) {
            .curved h1{
                padding-top: 35px;
                font-family: 'Teko', sans-serif;
                font-size: 40px;
            }
            .curved svg{
                display: block;
                margin-top: -50px;
            }
            #btnScrollToTop{
                right: 10px;
                bottom:10px;
            }
        }
        @media only screen and (min-width: 576px) and (max-width: 669px) {
            .productborder{
                margin-left: 15px;
            }
        }
        @media only screen and (max-width: 575px) {
            .productborder{
                margin-left: 0px;
            }
        }
        </style>
    </head>


<body>

<!--Navigation Bar-->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark sticky-top">
    <a class="navbar-brand" href="home.php"><img alt="Brand" src="images/logo.png" style="width: 80px; height: 80px;"></a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav ml-auto" style="padding-right: 50px;">
            <li class="nav-item">
                <a class="nav-link" href="home.php">Home <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
                    aria-haspopup="true" aria-expanded="false">
                    Arena
                </a>
                <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                    <a class="dropdown-item" href="arena_facilities.php">Arena Facilities</a>
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item" href="badminton_court_booking.php">Badminton Court Booking</a>
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item" href="volleyball_court_booking.php">Volleyball Court Booking</a>
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item" href="squash_court_booking.php">Squash Court Booking</a>
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item" href="futsal_court_booking.php">Futsal Court Booking</a>
                    <div class="dropdown-divider"></div>
                </div>
            </li>
            </li>
            <li class="nav-item active">
                <a class="nav-link" href="shop.php">Shop</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="about_us.php">About Us</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="faq.php">FAQ</a>
            </li>
            <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
                        aria-haspopup="true" aria-expanded="false">
                        Extras
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                        <a class="dropdown-item" href="member_profile.php">Profile</a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="booking_history.php">Booking</a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="my_purchases.php">My Purchase</a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="logout.php">Logout</a>
                        <div class="dropdown-divider"></div>
                    </div>
            </li>
        </ul>
    </div>
</nav>
    <div class="curved">
            <h1>Supreme Sports Shop</h1>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 319">
                <path fill="rgb(210, 210, 210)" fill-opacity="1"
                    d="M0,128L80,154.7C160,181,320,235,480,266.7C640,299,800,309,960,298.7C1120,288,1280,256,1360,240L1440,224L1440,320L1360,320C1280,320,1120,320,960,320C800,320,640,320,480,320C320,320,160,320,80,320L0,320Z">
                </path>
            </svg>
        </div>
    <div class="container-fluid">
    
        <!--Pull back to top button-->
        <button onclick="topFunction()" id="btnScrollToTop">
            <i class="material-icons">arrow_upward</i>
        </button>
    
        <!--categories filter-->
        <h5> Categories: </h5>
        <!--  form for the Filter function -->
        <form action="shop.php" method="GET">
            <ul class="list-group list-group-horizontal-md">
                <li class="list-group-item list-group-item-success">
                    <label for="Badminton">
                        <input type="radio" id="Badminton" name="sports"  value="Badminton">
                        Badminton
                    </label>
                </li>
                <li class="list-group-item list-group-item-success">
                    <label for="Volleyball">
                        <input type="radio" id="Volleyball" name="sports" value="Volleyball">
                        Volleyball
                    </label>
                </li>
                <li class="list-group-item list-group-item-success">
                    <label for="Squash">
                        <input type="radio" id="Squash" name="sports" value="Squash">
                        Squash
                    </label>
                </li>
                <li class="list-group-item list-group-item-success">
                    <label for="Futsal">
                        <input type="radio" id="Futsal" name="sports" value="Futsal">
                        Futsal
                    </label>
                </li>                
                <input type="reset" value="Clear" class="btn btn-outline-dark btn-md">
                <input type="submit" value="Filter" class="btn btn-outline-success btn-md">
            </ul>
            <p style="color:red;">*** Untick all and click Filter to show all products again</p>
        </form>

    <br />
    <h3 align="center" style="font-family: 'Acme', sans-serif;color:black;">Sport Accesories</h3><br />
    

    
    <?php

    if(!isset($_GET["sports"])){
        $sql = "SELECT * FROM item ORDER BY Item_Name ASC";
        $result = mysqli_query($conn, $sql);
    }
    else{
        $sql = "SELECT * FROM item WHERE Item_Category='".$_GET["sports"]."' ORDER BY Item_Name ASC";
        $result = mysqli_query($conn, $sql);
    }
    if(mysqli_num_rows($result) > 0)  
    {
        while($row = mysqli_fetch_array($result))
        {
    ?>
    
    
    <div class="col-sm-5 col-md-3 productborder" align="center" >
        <form method="post">
            <div class="products">
                <img src="<?php echo $row["Item_Image"]; ?>" class="img-fluid"/><br />

                <h5 class="text-info"><?php echo $row["Item_Name"]; ?></h5>

                <h5 class="text-danger">RM <?php echo number_format($row["Item_Price"],2); ?></h5>
                <p>Stock : <?php echo $row["Item_Stock"]; ?></p>

                <input type="text" name="quantity" value="1" class="form-control" />
                <input type="hidden" name="hidden_name" value="<?php echo $row["Item_Name"]; ?>" />
                <input type="hidden" name="hidden_price" value="<?php echo $row["Item_Price"]; ?>" />
                <input type="hidden" name="hidden_stock" value="<?php echo $row["Item_Stock"]; ?>" />
                <input type="hidden" name="hidden_id" value="<?php echo $row["Item_ID"]; ?>" />
                <input type="submit" name="add_to_cart" class="btn btn-success" value="Add to Cart" />
            </div>
        </form>
    </div>


    <?php
        }
    }
    ?>
   
   
        <div style="clear:both"></div>
        <br />
        <h4>Order Details</h4>
        <div class="table-responsive">
        <?php echo $message; ?>
        <div align="right">
            <a href="shop.php?action=clear" style="text-decoration:none;"><b>Clear Cart</b></a>
        </div>
        <table class="table table-bordered">
            <tr class="thead-dark">
            <th width="40%">Item Name</th>
            <th width="10%">Quantity</th>
            <th width="20%">Price</th>
            <th width="15%">Total</th>
            <th width="5%">Action</th>
            </tr>
        <?php


        if(isset($_COOKIE["shopping_cart"]))
        {
            $total = 0;
            $cookie_data = stripslashes($_COOKIE['shopping_cart']);
            $cart_data = json_decode($cookie_data, true);          
            foreach($cart_data as $keys => $values)
            {
        ?>
            <tr>
            <td><?php echo $values["item_name"]; ?></td>
            <td><?php echo $values["item_quantity"]; ?></td>
            <td>RM <?php echo number_format($values["item_price"],2); ?></td>
            <td>RM <?php echo number_format($values["item_quantity"] * $values["item_price"], 2);?></td>
            <td><a href="shop.php?action=delete&id=<?php echo $values["item_id"]; ?>"><span class="text-danger">Remove</span></a></td>
            </tr>
        <?php 
            $total = $total + ($values["item_quantity"] * $values["item_price"]);
            }
            $tax = $total * 0.06;
            $subtotal = $total * 1.06;
            ?>
            <tr style="background-color:#333; color:whitesmoke;">
            <td colspan="3" align="right">Total</td>
            <td align="left">RM <?php echo number_format($total, 2); ?></td>
            <td></td>
            </tr>
            <tr style="background-color:#333; color:whitesmoke;">
            <td colspan="3" align="right">Tax</td>
            <td align="left">RM <?php echo number_format($tax, 2); ?></td>
            <td></td>
            </tr>
            <tr style="background-color:#333; color:whitesmoke;">
            <td colspan="3" align="right">Subtotal</td>
            <td align="left">RM <?php echo number_format($subtotal, 2); ?></td>
            <td></td>
            </tr>
    <!-- Payment Method! ! ! ! ! !-->
            <tr class="payment_method">
            <td align="right">
               <strong>Payment Method: </strong> 
            </td>
            <td colspan="4">
            <form action="payment.php" method="POST">
            <?php 
                foreach($cart_data as $keys => $values) 
                {
            ?>
                <input type="hidden" name="itemID[]" value="<?php echo $values['item_id']; ?>" />
                <input type="hidden" name="itemAmount[]" value="<?php echo $values["item_quantity"]; ?>" />
            <?php 
                }
            ?>
                <input type="hidden" name="total" value="<?php echo $total; ?>" />
                <select name="payment" required>
                    <option value="Visa Card">
                        Visa Card
                    </option>
                    <option value="Master Card">
                        Master Card
                    </option>
                    <option value="Online Banking">
                        Online Banking
                    </option>
                </select>
            </td>
        </tr>
        <tr>
            <td colspan="5">
                <input type="submit" class="btn btn-success"name="checkout" value="Checkout" style="width: 98.5%">
            </td>
        </tr>

        </form>
        <?php
        }
        else
        {
            echo '
            <tr>
            <td colspan="5" align="center">No Item in Cart</td>
            </tr>
            ';
        }
        ?>
            </table>
            </div>
        </div>
        <br />
</body>

<!--Footer-->
<footer>
    <div class="footer-top">
        <div class="container">
            <div class="row">
                <div class="col-md-4 col-sm-6 col-xs-12 segment-one md-mb-30 sm-mb-30">
                    <h3><font style="color: red;">Supreme</font> Sports Arena</h3>
                    <p>Supreme Sports Arena is a newly built sports arena which include badminton, squash, volleyball and futsal. The Arena is provided with high quality facilities for the sports enthusiasts.</p>
                </div>
                <div class="col-md-4 col-sm-6 col-xs-12 segment-two md-mb-30 sm-mb-30">
                    <h2>Quick Links</h2>
                    <ul>
                        <li><a href="home.php">Home</a></li>
                        <li><a href="arena_facilities.php">Arena Facilities</a></li>
                        <li><a href="shop.php">Shop</a></li>
                        <li><a href="about_us.php">About Us</a></li>
                        <li><a href="faq.php">FAQ</a></li>
                    </ul>
                </div>
                <div class="col-md-4 col-sm-6 col-xs-12 segment-three md-mb-30 sm-mb-30">
                    <h2>Contact Us</h2>
                    <p><i class="fa fa-phone"></i> &nbsp; 012-3456789 (John Siena)</p>
                    <p><i class="fas fa-envelope"></i> &nbsp; supremesportsarena@gmail.com</p>
                    <a href="https://www.facebook.com/Supreme-Sports-Arena-113298846750542/?modal=admin_todo_tour" target="_blank"><i
                            class="fab fa-facebook-square"></i></a>
                    <a href="https://www.instagram.com/supreme_sports_arena/" target="_blank"><i class="fab fa-instagram"></i></a>
                    <a href="https://twitter.com/ArenaSupreme" target="_blank"><i class="fab fa-twitter"></i></a>
                </div>
            </div>
        </div>
    </div>
    <p class="footer-bottom-text">All Right reserved by &copy;Supreme Sports Arena 2020</p>
</footer>

    <!--Bootstrap js-->
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
    <!--To make dropdown menu become hover accross-->
    <script>
        const $dropdown = $(".dropdown");
        const $dropdownToggle = $(".dropdown-toggle");
        const $dropdownMenu = $(".dropdown-menu");
        const showClass = "show";

        $(window).on("load resize", function() {
            if (this.matchMedia("(min-width: 768px)").matches) {
                $dropdown.hover(
                    function() {
                        const $this = $(this);
                        $this.addClass(showClass);
                        $this.find($dropdownToggle).attr("aria-expanded", "true");
                        $this.find($dropdownMenu).addClass(showClass);
                    },
                    function() {
                        const $this = $(this);
                        $this.removeClass(showClass);
                        $this.find($dropdownToggle).attr("aria-expanded", "false");
                        $this.find($dropdownMenu).removeClass(showClass);
                    }
                );
            } else {
                $dropdown.off("mouseenter mouseleave");
            }
        });

        //let the nvbar stick on top
        // When the user scrolls the page, execute myFunction
        window.onscroll = function() {
            myFunction()
        };

        // Get the navbar
        var navbar = document.getElementById("navbar");

        // Get the offset position of the navbar
        var sticky = navbar.offsetTop;

        // Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
        function myFunction() {
            if (window.pageYOffset >= sticky) {
                navbar.classList.add("sticky")
            } else {
                navbar.classList.remove("sticky");
            }
        }

        //Get the button:
        mybutton = document.getElementById("btnScrollToTop");

        // When the user scrolls down 20px from the top of the document, show the button
        window.onscroll = function() {scrollFunction()};

        function scrollFunction() {
        if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
            mybutton.style.display = "block";
        } else {
            mybutton.style.display = "none";
        }
        }

        // When the user clicks on the button, scroll to the top of the document
        function topFunction() {
        document.body.scrollTop = 0; // For Safari
        document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
        }
    </script>

    </html>