<?php


require_once('config.php');





if(($response["error"] == true))
{
    echo(json_encode($response));
}


if((!isset($_SESSION["GOLDFAYRE"])))
{
    $response["error"]          =   true;
    $response["error_msg"]      =   "An Error Occurred. You are requested to login first ";
}


if(($response["error"] == false))
{
    if((isset($_POST["request"])) && ($_POST["request"] == "add_product"))
    {
        $logs               =   array();
        $title              =   "";
        $description        =   "";
        $category           =   "";
        $price              =   "";
        $discount_price     =   "";
        $status             =   "";
        $images             =   array();


        if((!isset($_POST["title"])) || (empty($_POST["title"])))
        {
            $response["error"]      =   true;
            $response["error_msg"]  =   "An Error Occurred. Title is required";
        }
        else
        {
            $title   =   $_POST["title"];
        }


        if(($response["error"] == false))
        {
            if((!isset($_POST["description"])) || (empty($_POST["description"])))
            {
                $response["error"]      =   true;
                $response["error_msg"]  =   "An Error Occurred. Description is required";
            }
            else
            {
                $description   =   $_POST["description"];
            }

        }

        if(($response["error"] == false))
        {
            if((!isset($_POST["category"])) || (empty($_POST["category"])))
            {
                $response["error"]      =   true;
                $response["error_msg"]  =   "An Error Occurred. Category is required";
            }
            else
            {
                $category   =   $_POST["category"];
            }
        }

        if(($response["error"] == false))
        {
            if((!isset($_POST["price"])) || (empty($_POST["price"])))
            {
                $response["error"]      =   true;
                $response["error_msg"]  =   "An Error Occurred. Price is required";
            }
            else
            {
                $price   =   $_POST["price"];
            }
        }


        if(($response["error"] == false))
        {
            if((!isset($_POST["discountprice"])) || (empty($_POST["discountprice"])))
            {
                $discount_price     =   null;
            }
            else
            {
                $discountprice   =   $_POST["discountprice"];
            }
        }

        if(($response["error"] == false))
        {
            if((!isset($_POST["status"])) || (empty($_POST["status"])))
            {
                $response["error"]      =   true;
                $response["error_msg"]  =   "An Error Occurred. The product status is required";
            }
            else
            {
                $status   =   $_POST["status"];
            }
        }

        if(($response["error"] == false))
        {
            if((!isset($_FILES["images"])) || (empty($_FILES["images"])))
            {
                $response["error"]      =   true;
                $response["error_msg"]  =   "An Error Occurred. The product image is required";
            }
            else
            {
                $images     =   $_FILES["images"];
            }
        }

        if(($response["error"] == false))
        {
            $sql    = " INSERT INTO product_mst(title, description, category_id, price, discount_price, product_status) 
                        VALUES (?, ?, ?, ?, ?, ?)";
            $stmt = $db->prepare($sql); 
            $stmt->bind_param("ssssss", $title, $description, $category, $price, $discount_price, $status);
            $result     =   $stmt->execute();
            if(($result))
            {
                $logs["PRODUCT_MST_ID"]     =   $db -> insert_id;
            }
            else
            {
                $response["error"]          =   true;
                $response["error_msg"]      =   "An Error Occurred while adding the product to the system. Please try again later";
            }
        }

        if(($response["error"] == false))
        {
            for($i = 0; $i < count($images["name"]); $i ++)
            {
                $acceptable     =   array( 'jpg', 'jpeg', 'png');
                $uploaded       =   strtolower(substr(strrchr($images["name"][$i], '.') , 1)) ;
                if (in_array($uploaded, $acceptable)) 
                {
                    $uniquename     =   substr(base_convert(time(), 10, 36).md5(microtime()), 0, 16).".".$uploaded;     
                    $name       =   "../uploads/products/".$uniquename."";
	                if((move_uploaded_file($images['tmp_name'][$i], $name)))
                    {
                        $logs["uploaded_images"][]     =   $uniquename;
                    }
                    else
                    {
                        $response["error"]      =   true;
                        $response["error_msg"]  =   "An Error Occurred while uploading the image. Please try again later";
                    }
	            } 
                else 
                {
                    $response["error"]      =   true;
                    $response["error_msg"]  =   "An Error Occurred. Only Jpg, Jpeg and Png images are accepted."; 
                }

            }
        }


        if(($response["error"] == false))
        {
            foreach($logs["uploaded_images"] as $k => $v)
            {
                $sql    = " INSERT INTO product_images(product_mst_id, image_name, primary_image) 
                            VALUES (?, ?, null)";
                $stmt = $db->prepare($sql); 
                $stmt->bind_param("ss", $logs["PRODUCT_MST_ID"], $v);
                $result     =   $stmt->execute();
            }
        }


        if(($response["error"] == false))
        {
            $response["message"]    =   "The product has been added in the system successfully";
        }
        echo(json_encode($response));
    }



    if((isset($_POST["request"])) && ($_POST["request"] == "get_products"))
    {
        $products       =   array();
        $sql            =   "   SELECT M.id ID, M.title TITLE, M.description DESCRIPTION, M.category_id CATEGORY_ID, 
                                M.price PRICE, M.discount_price DISCOUNT_PRICE, M.product_status PRODUCT_STATUS, 
                                M.register_on REGISTER_ON, D.image_name IMG FROM product_mst M, product_images D
                                WHERE M.id = D.product_mst_id
                                AND D.primary_image = 'Y'";
        $stmt = $db->prepare($sql); 
        $stmt->execute();
        $result     =   $stmt->get_result();
        while($row = mysqli_fetch_assoc($result))
        {
            $products[]   =   $row;
        }
        $html   =   '';
        if((count($products) === 0))
        {
            $html   .=   '<p>No products found in the system.</p>';
        }
        else
        {
            $html  .=   '<div class="row" style="margin-top: 20px;">';
            $html  .=   '<div class="col-lg-12">';
            $html  .=   '<div class="card">';
            $html  .=   '<div class="card-body" style="background-color: white">';
            $html  .=   '<table id="ProductsTable" class="table table-bordered">';
            $html  .=   '<thead>';
            $html  .=   '<tr>';
            $html  .=   '<th>SNo</th>';
            $html  .=   '<th>Image</th>';
            $html  .=   '<th>Title</th>';
            $html  .=   '<th>Description</th>';
            $html  .=   '<th>Status</th>';
            $html  .=   '<th>Price</th>';
            $html  .=   '<th>Register On</th>';
            $html  .=   '<th>Operations</th>';
            $html  .=   '</tr>';
            $html  .=   '</thead>';
            $html  .=   '<tbody>';
            foreach($products as $k => $v)
            {
                $html   .=  '<tr>';
                $html   .=  '<td><strong>'.($k + 1).'</strong></td>';
                $html   .=  '<td><img src="'.$base_url.'uploads/products/'.$v["IMG"].'" class="img-thumbnail" style="max-height: 50px"  /></td>';
                $html   .=  '<td>'.$v["TITLE"].'</td>';
                $html   .=  '<td>'.$v["DESCRIPTION"].'</td>';
                if(($v["PRODUCT_STATUS"] == "P"))
                {
                    $html   .=  '<td><span class="badge bg-success">Published</span></td>';
                }
                if(($v["PRODUCT_STATUS"] == "D"))
                {
                    $html   .=  '<td><span class="badge bg-dark">Draft</span></td>';
                }
                $html   .=  '<td>'.$v["PRICE"].'</td>';
                $html   .=  '<td>'.$v["REGISTER_ON"].'</td>';
                $html   .=  '<td>';
                $html   .=  '<div class="d-flex flex-row bd-highlight mb-3">';
                $html   .=  '<div class="p-2 bd-highlight">';
                $html   .=  '<button id="CTDR_'.$v["ID"].'" class="btn btn-danger btn-sm">DELETE</button>';
                $html   .=  '</div>';
                $html   .=  '</div>';
                $html   .=  '</td>';
                $html   .=  '</tr>';

            }
            $html  .=   '</tbody>';
            $html  .=   '</table>';
            $html  .=   '</div>';
            $html  .=   '</div>';
            $html  .=   '</div>';
            $html  .=   '</div>';
            $response["html"]   =   $html;
        }



        echo(json_encode($response));
    }


    if((isset($_POST["request"])) && ($_POST["request"] == "get_products_home"))
    {
        $records        =   array();
        $sql            =   "   SELECT M.id ID, M.title TITLE, M.description DESCRIPTION, M.category_id CATEGORY_ID, C.category_name CATEGORY_NAME, 
                                M.price PRICE, M.discount_price DISCOUNT_PRICE, M.product_status PRODUCT_STATUS, M.register_on REGISTER_ON, 
                                M.quantity QUANTITY, D.image_name IMAGE, REPLACE(LOWER(M.title), ' ', '-') PRODUCT_KEYWORD, 
                                REPLACE(LOWER(C.category_name), ' ', '-') CATEGORY_KEYWORD 
                                FROM product_mst M, product_images D, category C
                                WHERE M.id = D.product_mst_id
                                AND M.category_id = C.id
                                AND D.primary_image = 'Y'";
        $stmt = $db->prepare($sql); 
        $stmt->execute();
        $result     =   $stmt->get_result();
        while($row = mysqli_fetch_assoc($result))
        {
            $records[]   =   $row;
        }

        if((count($records) === 0))
        {
            $html   =   '<p>No Product found in the system</p>';
        }
        else
        {
            $html   =   '';
            foreach($records as $k)
            {
                $html  .=   '<div class="col-xl-4 col-md-6">';
                $html  .=   '<div class="post-item position-relative h-100" data-aos="fade-up" data-aos-delay="100">';
                $html  .=   '<div class="post-img position-relative overflow-hidden">';
                $html  .=   '<img src="assets/img/product_1.jpg" class="img-fluid" alt="">';
                $html  .=   '<span class="post-date">NEW ARRIVALS</span>';
                $html  .=   '</div>';
                $html  .=   '<div class="post-content d-flex flex-column">';
                $html  .=   '<h3 class="post-title">Wheat Flour</h3>';
                $html  .=   '<p style="color: #f0474e; font-weight: 600;">25,000 PKR</p>';
                $html  .=   '<hr>';
                $html  .=   '<a href="blog-details.html" class="readmore stretched-link"><span>Shop Now</span><i class="bi bi-arrow-right"></i></a>';
                $html  .=   '</div>';
                $html  .=   '</div>';
                $html  .=   '</div>';
            }
            $response["html"]    =  $html;
        }
        echo(json_encode($response));
    }

}












































?>