<?php
    include("config.php");
    $product_title = isset($_POST['product_title'])? $_POST['product_title']:'';
    $product_desc = isset($_POST['product_desc'])? $_POST['product_desc']:'';
    $product_amount = isset($_POST['product_amount'])? $_POST['product_amount']:'';
    
    $select = $conn->prepare("SELECT * FROM product WHERE product_title=?");
    $select->bind_param('s', $product_title);
    $select->execute();
    $select_result = $select->get_result();
    if($select_result->num_rows === 0){
        
        $name = $_FILES['file']['name'];
            $target_dir = "../img/";
            $target_file = $target_dir . basename($_FILES["file"]["name"]);
        
            // Select file type
            $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
        
            // Valid file extensions
            $extensions_arr = array("jpg","jpeg","png","gif");
        
        
        
        
            // Check extension
            if(in_array($imageFileType,$extensions_arr) ){
                
                $select_all = $conn->prepare("SELECT COUNT(*) AS product_num FROM product");
                $select_all->execute();
                $select_all_result = $select_all->get_result();
                $select_fetch = $select_all_result ->fetch_assoc();
                $product_num = $select_fetch['product_num'];
                
                if($product_num <= 10){
                    $product_page = 1;
                }elseif($product_num >= 10){
                    $product_page = 2;
                }elseif($product_num >= 20){
                    $product_page = 3;
                }elseif($product_num >= 40){
                    $product_page = 4;
                }elseif($product_num >= 50){
                    $product_page = 5;
                }elseif($product_num >= 60){
                    $product_page = 6;
                }elseif($product_num >= 70){
                    $product_page = 7;
                }elseif($product_num >= 80){
                    $product_page = 8;
                }elseif($product_num >= 90){
                    $product_page = 9;
                }elseif($product_num >= 100){
                    $product_page = 10;
                }
                
         
            move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
        
        $insert = $conn->prepare("INSERT INTO product(product_title,product_desc,product_amount,product_pic,product_page) values(?,?,?,?,?)");
        $insert->bind_param("sssss", $product_title,$product_desc,$product_amount,$name,$product_page);
        $insert->execute();
        if($insert == true){
             header("Location:product.php");
        }else{
            header("Location:index.php");
        }
            }else{
                echo "error!!!";
            }
    }else{
        echo "Product already exists, go back and use another name!!!";
    }
    
    
    
?>