<?php ob_start();
require_once("controller/RestController.php");
require_once("controller/dbConnection.php");
require_once("controller/SimpleRest.php");

require "vendor/autoload.php";
use Aws\S3\S3Client;

$view = "";
if (isset($_GET["view"]))
    $view = $_GET["view"];

$sampleRest = new SimpleRest();
/*
controls the RESTful services
URL mapping
*/

$authToken = $_SERVER['Authorization'];
switch ($view) {

    case "all":
        // to handle REST Url /mobile/list/
        $table = new tables();
        $method = $_SERVER['REQUEST_METHOD'];
        $requestParts = explode('/', $_GET['request']);
        $auth = $table->verifyToken($connection->CONNECTION,$authToken);
        if($auth== 'Authorise'){
            switch ($method) {
            case "GET":
                if ($requestParts[0] === 'checkDB') {
                    $table->listTablesFromDB($connection);
                } else {
                    isset($requestParts[1]) ? $column = $requestParts[1] : $column = '';
                    isset($requestParts[2]) ? $value = $requestParts[2] : $value = '';
                    echo json_encode($table->selectQuery($requestParts[0], $connection->CONNECTION, $column, $value));
                }


                break;
            case "POST":
                $postData = file_get_contents("php://input");
                $payload = json_decode($postData, true);
                //echo $postData;
                if (!empty($payload)) {
                    $table->insertQuery($requestParts[0], $payload, $connection->CONNECTION);
                } else {
                    $statusCode = 204;
                    $queryData = array('error' => 'No Content');
                    $requestContentType = $_SERVER['HTTP_ACCEPT'];
                    $sampleRest->setHttpHeaders($requestContentType, $statusCode);
                    $response = json_encode($queryData);
                    echo $response;
                }
                break;
            case "PUT":
                $postData = file_get_contents("php://input");
                $payload = json_decode($postData, true);

                isset($requestParts[1]) ? $column = $requestParts[1] : $column = '';
                isset($requestParts[2]) ? $value = $requestParts[2] : $value = '';
                if (!empty($payload)) {
                    $table->updateQuery($requestParts[0], $payload, $connection->CONNECTION, $column, $value);
                } else {
                    $statusCode = 204;
                    $queryData = array('error' => 'No Content');
                    $requestContentType = $_SERVER['HTTP_ACCEPT'];
                    $sampleRest->setHttpHeaders($requestContentType, $statusCode);
                    $response = json_encode($queryData);
                    echo $response;
                }
                break;
            case "DELETE":
                isset($requestParts[1]) ? $column = $requestParts[1] : $column = '';
                isset($requestParts[2]) ? $value = $requestParts[2] : $value = '';
                $queryData = $table->deleteQuery($requestParts[0], $connection->CONNECTION, $column, $value);
                if ($queryData == 'Record Successfully Deleted') {
                    $statusCode = 200;
                } else {
                    $statusCode = 404;
                }
                $requestContentType = $_SERVER['HTTP_ACCEPT'];
                $sampleRest->setHttpHeaders($requestContentType, $statusCode);
                $response = json_encode($queryData);
                echo $response;
                break;
        }
        }else {
            
        }
        
        break;

    case "single":
        // to handle REST Url /mobile/show/<id>/
        $mobileRestHandler = new MobileRestHandler();
        $mobileRestHandler->getMobile($_GET["id"]);
        break;

    case "login":
        // to handle REST Url /mobile/show/<id>/
        $postData = file_get_contents("php://input");
        $payload = json_decode($postData, true);
        $table = new tables();
        $table->loginValidate($connection->CONNECTION, $payload);
        break;

    case "logout":
        // to handle REST Url /mobile/show/<id>/
         $requestParts = explode('/', $_GET['request']);
            if (isset($requestParts[0])) {
                $table = new tables();
                $table->logout($connection->CONNECTION, $requestParts[0]);
                // echo "Successfully Logout";
            }
        
        break;
        
    case "changepassword":
        // to handle REST Url /mobile/show/<id>/
        
        $table = new tables();
        $auth = $table->verifyToken($connection->CONNECTION,$authToken);
        if($auth== 'Authorise'){
            $postData = file_get_contents("php://input");
            $payload = json_decode($postData, true);
            $table->loginValidate($connection->CONNECTION, $payload);
                
        }else {
        }
        break;

    case "customSearch":
        
        $table = new tables();
        $auth = $table->verifyToken($connection->CONNECTION,$authToken);
        if($auth== 'Authorise'){
            $requestParts = explode('/', $_GET['request']);
            if (isset($requestParts[0])) {
                $query = base64_decode($requestParts[0]);
                $queryData = $table->selectMultiConditionalQuery($connection->CONNECTION, $query);
                $statusCode = 200;
            } else {
                $queryData = array('error' => 'Invalid Query !...');
                $statusCode = 401;
    
            }
    
            $response = json_encode($queryData);
            echo $response;
            
        }else {
            
        }
        


        break;
    
    case "checkdb": 
        $table = new tables();
        $table->listTablesFromDB($connection);
        break;
    
    case "signin": 
        $conn = $connection->CONNECTION;
        $postData = file_get_contents("php://input");
        $payload = json_decode($postData, true);
        $username = $payload['username'];
        $password = md5($payload['password']);
        
        $selectSql = mysqli_query($conn, "SELECT * FROM users WHERE username LIKE '${username}' AND password LIKE '${password}'");
            $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;
            }
            echo json_encode($queryData);
        break;
    case "video_feeds": 
        $conn = $connection->CONNECTION;
        $postData = file_get_contents("php://input");
        $payload = json_decode($postData, true);
        foreach ($payload as $key => $value) {
            $column_name[] = $key;
            $insertData[] = "'" . $value . "'";
        }
        // echo "INSERT INTO video_feeds " . "(" . join(',', $column_name) . ") VALUES (" . join(',', $insertData) . ")";
        $selectSql = "INSERT INTO video_feeds " . "(" . join(',', $column_name) . ") VALUES (" . join(',', $insertData) . ")";
        if ($conn->query($selectSql) === TRUE) {

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

            echo json_encode($queryData);
        } else {
            echo "Error: " . $selectSql . "<br>" . $conn->error;
        }
        $conn->close();
        

        break;
        
    case "uploadImage": 
         $postData = file_get_contents("php://input");
         $payload = json_decode($postData, true);
         $attachment = $payload['image'];
        //  echo $attachment;
          $a = $attachment;
            $s3 = new S3Client([
                'version' => 'latest',
                'region'  => 'ap-south-1',
                'credentials' => [
                    'key'    => 'AKIAQE7GKDPRXGUKASVY',
                    'secret' => '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'
                ],
            ]);
            $bytes = md5(uniqid());
            $bucket = 'jaisheo-advertising';
            $filename = "2024/${bytes}.png";
            $image = explode(",", $a);
            $imageData = base64_decode(end($image));
            $upload = $s3->upload($bucket, $filename, $imageData, 'public-read');
            $url = $upload->get('ObjectURL');
            $res['status']=200;
            $res['response']= $url;
            echo json_encode($res);
        break;

    case "" :
        echo "Not Found";
        break;
}
ob_end_flush();
?>
