<?php

//helper functions

$uploads_directory = "uploads";

function last_id(){
    
    global $connection;
    
    return mysqli_insert_id($connection);
    
}


function set_message($msg){
    if(!empty($msg)){
        $_SESSION['message'] = $msg;
    } else {
        $msg = "";
    }
}


function display_message(){
    
    if(isset($_SESSION['message'])){
        
        echo $_SESSION['message'];
        unset($_SESSION['message']);
        
    }
    
}

/* pravi redirekciju */
function redirect($location){
    
    header("Location: $location");
    
}
/* konekcija sa bazom */
function query($sql){
    
    global $connection;
    
    return mysqli_query($connection, $sql);
}

function confirm($result){
    
    global $connection;
    
    if(!$result){
        die("QUERY FAILED" . mysqli_error($connection));
    }
    
}
/* da bi sprecio sql injection */
function escape_string($string){
    
    global $connection;
    
    return mysqli_real_escape_string($connection, $string);
    
}

function fetch_array($result){
    
    return mysqli_fetch_array($result);
        
}

// get products sa herodokom

/**************** FRONT END FUNCTIONS *****************/

function get_products(){
    
$query = query("SELECT * FROM products");
confirm($query);
    
$rows = mysqli_num_rows($query);
    
if(isset($_GET['page'])){
    
    $page = preg_replace('#[^0-9]#', '', $_GET['page']);
    //filter everything but numbers
    
} else {// If the page url variable is not present force it to be number
    
    $page = 1;
    
}   

$perPage = 3;
    
$lastPage = ceil($rows / $perPage);
    
if($page < 1){
    
    $page = 1;
    
} elseif($page > $lastPage){
    
    $page = $lastPage;
    
}
$middleNumbers = '';

$sub1 = $page - 1;
$sub2 = $page - 2;
$add1 = $page + 1;
$add2 = $page + 2;   

if($page == 1){

    $middleNumbers .= '<li class="page-item active"><a>' .$page. '</a></li>';

    $middleNumbers .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='.$add1.'">' .$add1. '</a></li>';

} elseif ($page == $lastPage){
    
    $middleNumbers .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='.$sub1.'">' .$sub1. '</a></li>';
    
    $middleNumbers .= '<li class="page-item active"><a>' .$page. '</a></li>';
    
} elseif($page > 2 && $page < ($lastPage -1)){
    
    $middleNumbers .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='.$sub2.'">' .$sub2. '</a></li>';
    
    $middleNumbers .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='.$sub1.'">' .$sub1. '</a></li>';
    
    $middleNumbers .= '<li class="page-item active"><a>' .$page. '</a></li>';
    
    $middleNumbers .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='.$add1.'">' .$add1. '</a></li>';
    
    $middleNumbers .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='.$add2.'">' .$add2. '</a></li>';
    
} elseif($page > 1 && $page < $lastPage){
    
    $middleNumbers .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='.$sub1.'">' .$sub1. '</a></li>';
    
    $middleNumbers .= '<li class="page-item active"><a>' .$page. '</a></li>';
    
    $middleNumbers .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='.$add1.'">' .$add1. '</a></li>';

    
}
    
$limit = 'LIMIT ' . ($page-1) * $perPage . ',' . $perPage;    
    
$query2 = query("SELECT * FROM products $limit");
confirm($query2);
    
$outputPagination = "";
    
//if($lastPage != 1){
//    
//    echo "Page $page of $lastPage";
//    
//}
    

if($page != 1){
    
    $prev = $page -1;
    
    $outputPagination .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='.$prev.'">Prošla</a></li>';
    
} 
    
$outputPagination .= $middleNumbers;   

if($page != $lastPage){
    
    $next = $page +1;
    
    $outputPagination .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='.$next.'">Sledeća</a></li>';
    
}
    
    
while($row = fetch_array($query2)){
    
$product_image = display_image($row['product_image']);  
    
$rest = substr($row['short_desc'], 0, 106);
        
$product = <<<DELIMETER

                
                    <div class="service-block">
                        <div class="inner-box">
                            <div class="image-box">
                                <figure class="image"><a href="item.php?id={$row['product_id']}"><img src="../resources/{$product_image}" alt=""></a></figure>
                            </div>
                            <div class="lower-content">
                                <h3><a href="item.php?id={$row['product_id']}"">{$row['product_title']}</a>
                                </h3>
                                <h3><a href="service-detail.html">rsd {$row['product_price']}</a></h3>
                                <div class="text">{$rest}...</div>
                                <div class="link-box">
                                    <a class="btn btn-primary" target="_blank" href="../resources/cart.php?add={$row['product_id']}">Dodaj u korpu</a>
                                </div>
                            </div>
                        </div>
                    </div>
                

DELIMETER;

echo $product;

    }

    echo "</div><div class='col-sm-12 col-lg-12 col-md-12 text-center'><ul class='pagination'>{$outputPagination}</ul></div>";
    
}

/**************** end FRONT END FUNCTIONS *****************/

function get_categories(){
    
$query = query("SELECT * FROM categories");
confirm($query);

while($row = fetch_array($query)){
$categories_link = <<<DELIMETER

    <a href='category.php?id={$row['cat_id']}' class=''>{$row['cat_title']}</a>

DELIMETER;

echo $categories_link;
            
}
    
}

function get_categories2(){
    
$query = query("SELECT * FROM categories");
confirm($query);

while($row = fetch_array($query)){
$categories_link = <<<DELIMETER
<div class="items">
<div class="dropdown-text d-flex align-items-center justify-content-between">
    <p class="text">
    <a href='category.php?id={$row['cat_id']}' class=''>{$row['cat_title']}</a>
    <p>
</div>
</div>
DELIMETER;

echo $categories_link;
            
}
    
}

function get_categories3(){
    
$query = query("SELECT * FROM categories");
confirm($query);

while($row = fetch_array($query)){
$categories_link = <<<DELIMETER
<ul class="pd-cat">
<li>
    <a href='category.php?id={$row['cat_id']}' class=''> {$row['cat_title']}&nbsp</a>
    </li>          
</ul>    
DELIMETER;

echo $categories_link;
          
}
    
}

function get_categoriesMobilni(){
    
$query = query("SELECT * FROM categories");
confirm($query);

while($row = fetch_array($query)){
$categories_link = <<<DELIMETER

    <li><a href='category.php?id={$row['cat_id']}' class=''>{$row['cat_title']}</a></li>

DELIMETER;

echo $categories_link;
            
}
    
}

// get cat products sa herodokom

/**************** FRONT END FUNCTIONS *****************/


function number_products(){

$query = query("SELECT COUNT(product_category_id) AS `count` FROM products WHERE product_category_id =" . escape_string($_GET['id']) . " " );

confirm($query);
    
$row = mysqli_fetch_array($query);
$count = $row['count'];
echo $count;

}

function get_cat_name(){
    
$query = query("SELECT product_category_id FROM products WHERE product_category_id =" . escape_string($_GET['id']) . " " );

confirm($query);

$row = mysqli_fetch_array($query); 

$categoryname = show_product_category_title($row['product_category_id']);

echo $categoryname;

}

function get_products_in_cat_page2(){
$query = query("SELECT * FROM products WHERE product_category_id =" . escape_string($_GET['id']) . " " );

confirm($query);

while($row = fetch_array($query)){ 

$product_image = display_image($row['product_image']); 

$categoryname = show_product_category_title($row['product_category_id']);

$rest1 = substr($row['short_desc'], 0, 106);


$product = <<<DELIMETER

              <div class="col-md-4 col-sm-6">
                <div class="recent-product-two">
                  <div class="recent-product-two-img">                  
                    <img alt="product" src="../resources/{$product_image}">
                  </div>
                  <div class="weekly-sellers-text">
                    <span>$categoryname</span>
                    <a href="item.php?id={$row['product_id']}"><h5>{$row['product_title']}</h5></a>
                   
                    <h6>{$row['product_price']} rsd </h6>
                  </div>
                </div>
              </div>


DELIMETER;


echo $product;

}

}

function get_products_in_cat_page(){
    
$query = query("SELECT * FROM products WHERE product_category_id =" . escape_string($_GET['id']) . " " );

confirm($query);

while($row = fetch_array($query)){ 

$product_image = display_image($row['product_image']); 

$categoryname = show_product_category_title($row['product_category_id']);

$rest1 = substr($row['short_desc'], 0, 106);


$product = <<<DELIMETER

    <ul>
              <li class="grid-list">
                <div class="d-flex align-items-center">
                  <img alt="product" src="../resources/{$product_image}">
                  <div class="weekly-sellers-text">
                    <span>$categoryname</span>
                    <a href="item.php?id={$row['product_id']}"><h5>{$row['product_title']}</h5></a>
                    <h6>{$row['product_price']} rsd</h6>
                  </div>
                </div>
                <div class="grid-list-text">
                
                  <span>Na stanju: {$row['product_quantity']} kom.</span>
                  <div class="add-to-cart two">
                    <a href="../resources/cart.php?add={$row['product_id']}" class="btn"><span>Dodaj u korpu</span></a>
                    <a href="item.php?id={$row['product_id']}" class="btn">
                      <span>Opširnije</span>
                    </a>
                  </div>
                </div>
              </li>
        </ul>


DELIMETER;


echo $product;

}

}


/**************** end product cat FRONT END FUNCTIONS *****************/

function get_products_in_shop_page(){
    
$query = query("SELECT * FROM products");

confirm($query);



while($row = fetch_array($query)){ 

$product_image = display_image($row['product_image']);     

$rest1 = substr($row['short_desc'], 0, 106);
    
$product = <<<DELIMETER

        <div class="col-md-4 col-sm-6 hero-feature">
            <div class="thumbnail">
                <a href="item.php?id={$row['product_id']}"><img src="../resources/{$product_image}" class="img-responsive" alt=""></a>
                <div class="caption">
                    <h3><a href="item.php?id={$row['product_id']}">{$row['product_title']}</a></h3>
                    <p>{$rest1}...</p>
                    <p>
                        <a href="../resources/cart.php?add={$row['product_id']}" class="btn btn-primary">Kupi sada!</a> <a href="item.php?id={$row['product_id']}" class="btn btn-default">Više detalja</a>
                    </p>
                </div>
            </div>
        </div>


DELIMETER;

echo $product;


}

}


function login_user(){
    
    if(isset($_POST['submit'])){
        
        $username = escape_string($_POST['username']);
        $password = escape_string($_POST['password']);
        
        $query = query("SELECT * FROM user WHERE username = '{$username}' AND password = '{$password}' ");
        confirm($query);
        
        if(mysqli_num_rows($query) == 0){
            set_message("Pogresno ime ili lozinka");
            redirect("login.php");
        } else {
            
            $_SESSION['username'] = $username;
            set_message("Dobrodošli na admin stranu {$username}");
            redirect("admin");
            
        }
        
    }
    
}

 
function send_message(){
    
    if(isset($_POST['submit'])){
        
        $to        = "milenko.milovanovic@gmail.com";
        $name = $_POST['name'];
        $subject   = $_POST['subject'];
        $email     = $_POST['email'];
        $message   = $_POST['message'];
        
        $headers = "Od: {$name} {$email}";
        
        $result = mail($to, $subject, $message, $headers); 
        
        if(!$result){
            
            set_message("Molimo Vas da probate ponovo.");
            redirect("contact.php");
            
        } else {
            
            set_message("Vaša poruka je poslata. Hvala!");
            redirect("contact.php");
            
        }
        
        
        
    }
    
    
}

function display_orders(){
    
    $query = query("SELECT * FROM orders");
    confirm($query);
    
    while($row = fetch_array($query)){
        
$orders = <<<DELIMETER

    <tr>    
        <td>{$row['order_id']}</td>
        <td>{$row['order_amount']}</td>
        <td>{$row['order_transaction']}</td>
        <td>{$row['order_currency']}</td>
        <td>{$row['order_status']}</td>
        <td>
            <a class="btn btn-danger" href="../../resources/templates/back/delete_order.php?id={$row['order_id']}">
                <span class="glyphicon glyphicon-remove"></span>
            </a>
        </td>
    </tr>    


DELIMETER;

echo $orders;        
        
    }
    
    
}

/************************** ADMIN PRODUCTS Page *****************/

function display_image($picture){ 
    
    global $uploads_directory;
    
    return $uploads_directory . DS . $picture;
    
}


function get_products_in_admin(){
    
   
$query = query("SELECT * FROM products");

confirm($query);

while($row = fetch_array($query)){
    
$category = show_product_category_title($row['product_category_id']);
    
$product_image = display_image($row['product_image']);    
        
$product = <<<DELIMETER

    <tr>
        <td>{$row['product_id']}</td>
        <td>{$row['product_title']}<br>
          <a href="index.php?edit_product&id={$row['product_id']}"><img width="150" src="../../resources/{$product_image}" alt=""></a>
        </td>
        <td>{$category}</td>
        <td>{$row['product_price']}</td>
        <td>{$row['product_quantity']}</td>
        <td>
            <a class="btn btn-danger" href="../../resources/templates/back/delete_product.php?id={$row['product_id']}">
                <span class="glyphicon glyphicon-remove"></span>
            </a>
        </td>
    </tr>

DELIMETER;

echo $product;

}  
    
}

function show_product_category_title($product_category_id){
    
    $category_query = query("SELECT * FROM categories WHERE cat_id = '{$product_category_id}' ");
    confirm($category_query);
    
    while($category_row = fetch_array($category_query)){
        
        return $category_row['cat_title'];
        
    }
    
}


/* add products */
    
function add_product() {


if(isset($_POST['publish'])) {


$product_title          = escape_string($_POST['product_title']);
$product_category_id    = escape_string($_POST['product_category_id']);
$product_price          = escape_string($_POST['product_price']);
$product_description    = escape_string($_POST['product_description']);
$short_desc             = escape_string($_POST['short_desc']);
$product_quantity       = escape_string($_POST['product_quantity']);
$product_image          = $_FILES['file']['name'];
$image_temp_location    = $_FILES['file']['tmp_name'];

move_uploaded_file($image_temp_location  ,  UPLOAD_DIRECTORY . DS . $product_image);


$query = query("INSERT INTO products(product_title, product_category_id, product_price, product_description, short_desc, product_quantity, product_image) VALUES('{$product_title}', '{$product_category_id}', '{$product_price}', '{$product_description}', '{$short_desc}', '{$product_quantity}', '{$product_image}')");
$last_id = last_id();
confirm($query);
set_message("Novi proizvod sa id: {$last_id} je dodat.");
redirect("index.php?products");


        }


}    
    
/* end ->  add products */

function show_categories_add_product_page(){
    
$query = query("SELECT * FROM categories");
confirm($query);

while($row = fetch_array($query)){
$categories_opions = <<<DELIMETER

    <option value="{$row['cat_id']}">{$row['cat_title']}</option>

DELIMETER;

echo $categories_opions;
            
}
    
}


/* update product  */

function update_product() {


if(isset($_POST['update'])) {


$product_title          = escape_string($_POST['product_title']);
$product_category_id    = escape_string($_POST['product_category_id']);
$product_price          = escape_string($_POST['product_price']);
$product_description    = escape_string($_POST['product_description']);
$short_desc             = escape_string($_POST['short_desc']);
$product_quantity       = escape_string($_POST['product_quantity']);
$product_image          = $_FILES['file']['name'];
$image_temp_location    = $_FILES['file']['tmp_name'];
    
if(empty($product_image)){
    
    $get_pic = query("SELECT product_image FROM products WHERE product_id =" . escape_string($_GET['id']) . " ");
    confirm($get_pic);
    
    while($pic = fetch_array($get_pic)){
        
        $product_image = $pic['product_image'];
        
    }
    
}    

move_uploaded_file($image_temp_location  ,  UPLOAD_DIRECTORY . DS . $product_image);

$query = "UPDATE products SET ";
$query .= "product_title = '{$product_title}', "; 
$query .= "product_category_id = '{$product_category_id}', ";
$query .= "product_price = '{$product_price}', ";
$query .= "product_description = '{$product_description}', ";
$query .= "short_desc = '{$short_desc}', ";
$query .= "product_quantity = '{$product_quantity}', ";
$query .= "product_image = '{$product_image}' ";
$query .= "WHERE product_id=" . escape_string($_GET['id']);
 
$send_update_query = query($query);    
confirm($send_update_query);
$last_id = last_id();
confirm($query);
set_message("Proizvod je izmenjen");
redirect("index.php?products");

        }

} 

/************************** END ADMIN PRODUCTS *****************/

/******************  Categories ADMIN  *****************/

function show_categories_in_cat(){
    
   $query = query("SELECT * FROM products WHERE product_category_id =" . escape_string($_GET['id']) . " LIMIT 1" );

confirm($query);

while($row = fetch_array($query)){ 

$product_image = display_image($row['product_image']); 

$categoryname = show_product_category_title($row['product_category_id']);

        
$category = <<<DELIMITER

<tr>
    <td>{$categoryname}</td>
</tr>

DELIMITER;
       
echo $category;        
    }
    
}


function show_categories_in_admin(){
    
    $category_query = query("SELECT * FROM categories");
    confirm($category_query);
    
    while($row = fetch_array($category_query)){
        
        $cat_id = $row['cat_id'];
        $cat_title = $row['cat_title'];
        
$category = <<<DELIMITER

<tr>
    <td>{$cat_id}</td>
    <td>{$cat_title}</td>
    <td>
        <a class="btn btn-danger" href="../../resources/templates/back/delete_category.php?id={$row['cat_id']}">
            <span class="glyphicon glyphicon-remove"></span>
        </a>
    </td>
</tr>

DELIMITER;
       
echo $category;        
    }
    
}

function add_category(){
    
    if(isset($_POST['add_category'])){
        
        $cat_title = escape_string($_POST['cat_title']);
        
        if(empty($cat_title) || $cat_title == " "){
        
        echo "<p class='bg-danger'>Polje ne sme biti prazno</p>";
        
    } else{
        
        $insert_cat = query("INSERT INTO categories(cat_title) VALUES('{$cat_title}') ");
        confirm($insert_cat); 
        set_message("Napravili ste novu kategoriju");
        
        }
        
    }
    
}

/******************  End category admin ***********************/

/***************** ADMIN USERS **********************/


function display_users(){
    
    $user_query = query("SELECT * FROM user");
    confirm($user_query);
    
    while($row = fetch_array($user_query)){
        
        $user_id = $row['user_id'];
        $username = $row['username'];
        $email = $row['email'];
        $password = $row['password'];
        
        
$users = <<<DELIMITER

<tr>
    <td>{$user_id}</td>
    <td>{$username}</td>
    <td>{$email}</td>
    <td>
        <a class="btn btn-danger" href="../../resources/templates/back/delete_user.php?id={$row['user_id']}">
            <span class="glyphicon glyphicon-remove"></span>
        </a>
    </td>
</tr>

DELIMITER;
       
echo $users;        
    }
    
}

function add_user(){
    
    if(isset($_POST['add_user'])){
        
        $username = escape_string($_POST['username']);
        $email = escape_string($_POST['email']);
        $password = escape_string($_POST['password']);
//        $user_photo = $_FILES['file']['name'];
//        $photo_temp = $_FILES['file']['tmp_name'];
        
        
//        move_uploaded_file($image_temp_location  ,  UPLOAD_DIRECTORY . DS . $user_photo);
        
        $query = query("INSERT INTO user(username,email,password) VALUES ('{$username}', '{$email}', '{$password}')");
        confirm($query);
        
        set_message("Dodat je korisnik");
        redirect("index.php?users");
        
    }
    
}



/***************** ADMIN USERS **********************/


/**************** REPORTS  ***************/

function get_reports(){
    
   
$query = query("SELECT * FROM reports");

confirm($query);

while($row = fetch_array($query)){
    
    
        
$report = <<<DELIMETER

    <tr>
        <td>{$row['report_id']}</td>
        <td>{$row['product_id']}</td>
        <td>{$row['order_id']}</td>
        <td>{$row['product_price']}</td>
        <td>{$row['product_title']}</td>
        <td>{$row['product_quantity']}</td>
        <td>
            <a class="btn btn-danger" href="../../resources/templates/back/delete_report.php?id={$row['report_id']}">
                <span class="glyphicon glyphicon-remove"></span>
            </a>
        </td>
    </tr>

DELIMETER;

echo $report;

}  
    
}

/**************** END REPORTS ***************/

/**************** SLIDES FUNCTIONS **************/

function add_slides(){
    
    if(isset($_POST['add_slide'])){
        
        $slide_title = escape_string($_POST['slide_title']);
        $slide_image = $_FILES['file']['name'];
        $slide_image_loc =$_FILES['file']['tmp_name'];
        
        if(empty($slide_title) || empty($slide_image)){
            
            echo "<p class='bg-danger'>This field cannot be empty</p>";
            
        }else {
            
            move_uploaded_file($slide_image_loc , UPLOAD_DIRECTORY . DS . $slide_image);
            
            $query = query("INSERT INTO slides(slide_title, slide_image) VALUES('{$slide_title}','{$slide_image}')");
            confirm($query);
            set_message("Dodat slajd");
            redirect("index.php?slides");
        }
        
    }
    
}

function get_current_slide_in_admin(){
    
    $query = query("SELECT * FROM slides ORDER BY slide_id DESC LIMIT 1");
    confirm($query);
    
    while($row = fetch_array($query)){
        
    $slide_image = display_image($row['slide_image']);       
        
$slide_active_admin = <<<DELIMETER


    <img class="img-responsive" src="../../resources/{$slide_image}" alt=""> 

DELIMETER;

echo $slide_active_admin;  
        
       
    }
    
}

function get_active_slide(){
    
    $query = query("SELECT * FROM slides ORDER BY slide_id DESC LIMIT 1");
    confirm($query);
    
    while($row = fetch_array($query)){
        
    $slide_image = display_image($row['slide_image']);       
        
$slide_active = <<<DELIMETER

<div class="item active">
    <img class="slide-image" src="../resources/uploads/{$row['slide_image']}" alt=""> 
</div> 

DELIMETER;

echo $slide_active;  
        
       
    }
    
}

function get_slides(){
    
    $query = query("SELECT * FROM slides");
    confirm($query);
    
    while($row = fetch_array($query)){
        
    $slide_image = display_image($row['slide_image']);       
        
$slides = <<<DELIMETER

<div class="item">
    <img class="slide-image" src="../resources/uploads/{$row['slide_image']}" alt=""> 
</div> 

DELIMETER;

echo $slides;
        
        
       
    }
    
}

function get_slide_thumbnails(){
    
     $query = query("SELECT * FROM slides ORDER BY slide_id ASC");
    confirm($query);
    
    while($row = fetch_array($query)){
        
    $slide_image = display_image($row['slide_image']);       
        
$slide_thumb_admin = <<<DELIMETER


    <div class="col-xs-6 col-md-3 image_containter">
        <a href="index.php?delete_slide_id={$row['slide_id']}">
            <img class="img-responsive slide-image" src="../../resources/{$slide_image}" alt="">
        </a>
        
        <div class="caption">
            
            <p>Naziv slajda: {$row['slide_title']}</p>
        
        </div>
        
    </div> 

DELIMETER;

echo $slide_thumb_admin;  
        
    }
    
}

/***************** PAGINATION ******************/

?>