<?php
ob_start();
include_once('dbConnection.php');
include_once('SimpleRest.php');
// require 'vendor/autoload.php';

/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 10/6/2017
 * Time: 11:06 AM
 */
class tables extends SimpleRest
{
    public function tableColumns($tableJson)
    {
        $schema = array();
        foreach ($tableJson as $key => $value) {
            $schema[] = $key . ' ' . $value;
        }
        return $schema;
    }

    public function listTablesFromDB($connection){
        $selectQuery = mysqli_query($connection->CONNECTION, 'SHOW TABLES');
        $tablesInDB = mysqli_fetch_assoc($selectQuery);
        if(!empty($selectQuery)){
            foreach ($selectQuery as $key=>$value){
                $connection->TABLE_LIST_IN_DB[] = $value['Tables_in_jaisheoconstruction'];
            }
            $this->createTable($connection);
        }
        else{
            $this->createTable($connection);
        }

    }

    public function createTable($conn)
    {
        echo json_encode($conn->TABLE_LIST_IN_DB);
        foreach ($conn->TABLE_LIST as $key){
            if(in_array($key, $conn->TABLE_LIST_IN_DB ) <= 0){
                echo "CREATE  TABLE " . $key . "(" . join(', ',$this->tableColumns($conn->TABLES_STRUCTURE[$key])) . " , PRIMARY KEY (`srl_no`))";
                $query = "CREATE  TABLE " . $key . "(" . join(', ',$this->tableColumns($conn->TABLES_STRUCTURE[$key])) . " , PRIMARY KEY (`srl_no`))";
                mysqli_query($conn->CONNECTION, $query);
            }
        }
    }

    public function insertQuery($tableName, $payload, $conn)
    {
        $column_name = array();
        $insertData = array();
        foreach ($payload as $key => $value) {
            $column_name[] = $key;
            if ($key === 'password') {
                $value = md5($value);
                $insertData[] = "'" . $value . "'";
            }else if ($key === 'updatedOn') {
                $str = trim($value,"+05:30");
                $str1 = strtr($str,"T", " ");
                $insertData[] = "'" . $str1 . "'";
            } else {
                $insertData[] = "'" . $value . "'";
            }
        }
        $sql = "INSERT INTO " . $tableName . "(" . join(',', $column_name) . ") VALUES (" . join(',', $insertData) . ")";
        if ($conn->query($sql) === TRUE) {

            $queryData = array();
            $queryData = array('success'=> 'New record created successfully');

            echo json_encode($queryData);
            if($tableName== 'campaigns'){
                mkdir("../../feedsData/".mysqli_insert_id($conn), 0777);
            }
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
        $conn->close();
    }

    public function updateQuery($tableName, $payload, $conn, $column,$searchParams)
    {
        $updateData = array();

        $condition = '';
        if($column && $searchParams){
            if($column == 'srl_no'){
                $condition = " WHERE ". $column." LIKE ".$searchParams;
            }else{
                $condition = " WHERE ". $column." LIKE '".$searchParams."'";
            }
        }
        foreach ($payload as $key => $value) {
//            $column_name[] = $key;
            if($key === 'password'){
                $value = md5($value);
                $updateData[] = $key."= '" . $value ."'";
            }
            else{
                $updateData[] = $key."= '" . $value ."'";
            }
        }
        $sql = "UPDATE " . $tableName . " SET " .join(',', $updateData) . $condition;
        if ($conn->query($sql) === TRUE) {
            echo "Record successfully Updated";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
        $conn->close();
    }

    public function selectQuery($tableName, $conn, $column,$searchParams)
    {
        $condition = '';
        if($column && $searchParams){
            $condition = " WHERE ". $column." LIKE '".$searchParams."'";
        }
        $selectSql = mysqli_query($conn, "SELECT * FROM " . $tableName. $condition);
        $queryData = array();
//        echo json_encode(mysqli_fetch_assoc($selectSql));
        while ($data = mysqli_fetch_assoc($selectSql)) {
            $queryData[] = $data;
        }
        return $queryData;
    }

    public function selectMultiConditionalQuery($conn, $query)
    {
        $selectSql = mysqli_query($conn, "SELECT ".$query);
        $queryData = array();
//        echo json_encode(mysqli_fetch_assoc($selectSql));
        while ($data = mysqli_fetch_assoc($selectSql)) {
            $queryData[] = $data;
        }
        return $queryData;
    }

    public function deleteQuery($tableName, $conn, $column,$searchParams){
        $condition = '';
        if($column && $searchParams){
            $condition = " WHERE ". $column." LIKE ".$searchParams;
        }
        mysqli_query($conn, "DELETE FROM " . $tableName. $condition);
        if (mysqli_affected_rows($conn) > 0) {
            return "Record Successfully Deleted";
        }
        else {
            return "Record not matched..";
        }
    }
    public function loginValidate($conn, $payload)
    {
        $queryParams = array();
        foreach ($payload as $key => $value) {
            if($key === 'password'){
                $value = md5($value);
                $queryParams[] = $key ." LIKE '" . $value ."'";
            }else{
                $queryParams[] = $key ." LIKE '" . $value ."'";
            }

        }
        if(empty($queryParams)){
            $statusCode = 204;
            $queryData = array('error' => 'No Content');
        }
        else{
            $selectSql = mysqli_query($conn, "SELECT * FROM users WHERE " . join(' AND ', $queryParams));
            $queryData = array();
            $username = '';
            $token = bin2hex(mt_rand(40, 64));
            while ($data = mysqli_fetch_assoc($selectSql)) {
                $queryData = array('id' => $data['srl_no'] , 'username' => $data['username'] , 'permission' => $data['permission'], 'userType'=> $data['userType'], 'campaignId'=> $data['campaign'], 'token'=> $token);
                $username = $data['username'];
//                $queryData[] = $data;
            }
            mysqli_query($conn, "UPDATE `users` SET `authToken` = '".$token."' WHERE `users`.`username` = '".$username."'");

            if(empty($queryData)) {
                $statusCode = 401;
                $queryData = array('error' => 'Invalid Username / Password !...');
            } else {
                $statusCode = 200;
            }
        }

        $requestContentType = $_SERVER['HTTP_ACCEPT'];
        $this ->setHttpHeaders($requestContentType, $statusCode);

        if(strpos($requestContentType,'*/*') !== false){
            $response = json_encode($queryData);
            echo $response;
        }
    }

    public function verifyToken($conn, $authKey){
        $condition = '';
        if($authKey){
            $key = base64_decode($authKey);
            $data =explode(":",$key);
            $condition = " WHERE username LIKE '".$data[0]."' AND authToken LIKE '".$data[1]."'";
        }
        if($condition != ''){
            $queryResult = mysqli_query($conn, "SELECT * FROM users". $condition);
            if (mysqli_num_rows($queryResult) > 0) {
                return 'Authorise';
            }
            else {
                $this->errorResponse();
            }
        }else {
            echo "OK";
        }
        
    }

    public function logout($conn, $user){
        mysqli_query($conn, "UPDATE `users` SET `authToken` = NULL WHERE `users`.`username` = '".$user."'");
        $statusCode = 200;
        $queryData = array('success' => 'Successfully Logout');
        $requestContentType = $_SERVER['HTTP_ACCEPT'];
        $this ->setHttpHeaders($requestContentType, $statusCode);

        if(strpos($requestContentType,'*/*') !== false){
            $response = json_encode($queryData);
            echo $response;
        }
    }
    
    public function errorResponse(){
        $statusCode = 401;
        $queryData = array('error' => 'Invalid Username / Password !...');
        $requestContentType = $_SERVER['HTTP_ACCEPT'];
        $this ->setHttpHeaders($requestContentType, $statusCode);

        if(strpos($requestContentType,'*/*') !== false){
            $response = json_encode($queryData);
            echo $response;
        }
    }
    public function uploadTos3Bucket($attachment, $folder) {
        // if (filter_var($attachment, FILTER_VALIDATE_URL)) { 
        //     return $attachment;
        // } else {
            // $a = $attachment;
            // $s3 = new S3Client([
            //     'version' => 'latest',
            //     'region'  => 'ap-south-1',
            //     'credentials' => [
            //         'key'    => 'AKIAIGNBBN73HZGZUPXA',
            //         'secret' => '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'
            //     ],
            // ]);
            // $bytes = md5(uniqid());
            // $bucket = 'jaisheo-advertising';
            // $filename = "${folder}/${bytes}.png";
            // $image = explode(",", $a);
            // $imageData = base64_decode(end($image));
            echo $attachment;
            // $upload = $s3->upload($bucket, $filename, $imageData, 'public-read');
            // $url = $upload->get('ObjectURL');
            // echo $url;
        // }
        
    }
}

//echo json_encode($connection->TABLES_STRUCTURE);
//echo json_encode($connection->TABLE_LIST);
//$table = new tables();
//echo join(', ',$table->tableColumns($connection->TABLES_STRUCTURE['employee']));


//$postData = file_get_contents("php://input");
//$data = json_decode($postData, true);
//$method = $_SERVER['REQUEST_METHOD'];
//switch ($method) {
//    case 'GET':
//        echo json_encode($table->selectQuery($_REQUEST['tableName'], $connection->CONNECTION));
//        break;
//    case 'POST':
//        $postData = file_get_contents("php://input");
//        $payload = json_decode($postData, true);
//        $table->insertQuery($_REQUEST['tableName'], $payload, $connection->CONNECTION);
//        break;
//}

ob_end_flush();
?>