<?php
// fashion.php- for storing / retrieving user fashion data

// required headers
header("Access-Control-Allow-Origin: http://localhost/rest-api-authentication-example/");
//header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
 
// files needed to connect to database
 $pathRoot = $_SERVER['DOCUMENT_ROOT'];
include_once  $pathRoot ."/saia/api/v1/config/database.php";
include_once $pathRoot ."/saia/api/v1/objects/fashionWoman.php";

// generate json web token
include_once $pathRoot ."/saia/api/v1/config/core.php";
include_once $pathRoot ."/saia/api/v1/libs/php-jwt-master/src/BeforeValidException.php";
include_once $pathRoot ."/saia/api/v1/libs/php-jwt-master/src/ExpiredException.php";
include_once $pathRoot ."/saia/api/v1/libs/php-jwt-master/src/SignatureInvalidException.php";
include_once $pathRoot ."/saia/api/v1/libs/php-jwt-master/src/JWT.php";
use \Firebase\JWT\JWT;

//----------------- Get JWT from Header ----------------------
$jwtAuth =  getBearerToken();
// get jwt
$jwt=isset($jwtAuth) ? $jwtAuth : "";
// if jwt is not empty
if($jwt){
 
    // if decode succeed, show user details
    try {
        // decode jwt
        $decoded = JWT::decode($jwt, $key, array('HS256'));

        // show user details
        $jwtDta = $decoded->data;
        $jwtUserId = $jwtDta -> id;

    }catch (Exception $e){
         http_response_code(401);
        // tell the user access denied
        echo json_encode(array("error" =>"Failed to Login"));
        return;
    }
    
   
}
 
// show error message if jwt is empty
else{
    http_response_code(401);
 
    // tell the user access denied
    echo json_encode(array("error" => "Failed to Login"));
    return;
}

//==============================================================================
 
// get database connection
$database = new Database();
$db = $database->getConnection();
 
//Check if it is a POST call


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // get posted data
    $jsonDataFashion = json_decode(file_get_contents("php://input"));
    $user_id =  $jsonDataFashion->user_id;

    if($jwtUserId == $user_id ){
        $results = populateFashionOpject($db, $jsonDataFashion);

        $resultsTrue="true";
        if(strcmp($results,$resultsTrue)==0){
            http_response_code(200);
            echo json_encode(array(
                "status" => "ok"
                
           ));
           return;
        }else{
            http_response_code(200);
            echo json_encode(array(
                "status" =>"err"
                
            ));
            return;
        }
    }
    else{
        echo json_encode(array("error" => "Failed to Login"));
        return;
    }
    
    
    
}else{
    $user_id = $_GET["user_id"];
    if($jwtUserId == $user_id ){
        getFashionData($db,$user_id);
    }
    else{
        echo json_encode(array("error" => "Failed to Login"));
        return;
    }

};

function getFashionData($db,$user_id){
    $fashion = new FashionWoman($db);
    $fashion->fkeyUserId =  $user_id;
    $num =  $fashion->selectFashion();
    if($num>0){
        echo json_encode(buildJson($fashion));
    }
    
    
}

function buildJson($fashion){
    $key1 = 0;
    $key2 = 2;
    
    $favouriteColors[0]->key = 0;
    $favouriteColors[0]->color = $fashion->favouriteColors1;  
     $favouriteColors[1]->key = 1;
    $favouriteColors[1]->color = $fashion->favouriteColors2;
     $favouriteColors[2]->key = 2;
    $favouriteColors[2]->color = $fashion->favouriteColors3;
     $favouriteColors[3]->key = 3;
    $favouriteColors[3]->color = $fashion->favouriteColors4;

    return array("user_id" => $fashion->fkeyUserId,
          "color" => array("selectedCategory" => $fashion->                                   colorSelectedCategory,
                            "selectedStyle" => $fashion->colorSelectedStyle,
                            "selectedColor" => $fashion->colorSelectedColor,
                            "favouriteColors" => $favouriteColors,
                            "selectedSummary"=> $fashion->colorSelectedSummary
                    ),
            "style" => array("bustSize"=>  $fashion->bustSize,
                             "waistSize" => $fashion->waistSize,
                             "hipSize"=> $fashion->hipSize,
                             "shapeType"=> $fashion->shapeType,
                             "neckLengthType"=> $fashion->neckLenghtType,
                             "height"=> $fashion->height,
                             "bottomSize"=> $fashion->bottomSize,
                             "segmentType"=> $fashion->segmentType,
                             "flaws"=> array("Saddle bags"=> $fashion->flawsSaddleBags,
                                "Hips"=> $fashion->flawsHips,
                                "Breasts: too small"=> $fashion->flawsBreastsTooSmall,
                                "Breasts: too large"=> $fashion->flawsBreastsTooLarge, 
                                "Lower legs"=> $fashion->flawsLowerLegs,
                                "Overweight"=> $fashion->flawsOverweight,
                                "Double chin"=> $fashion->flawsDoubleChin,
                                "Big buttocks"=> $fashion->flawsBigButtocks,
                                "Stomach/love handles"=> $fashion->flawsStomachLoveHandles,
                                "Hollow back"=> $fashion->flawsHollowBack,
                                "Arms"=> $fashion->flawsArms
                                        ),
                            "makeup"=> array( "Droopy Eyes" => $fashion               ->makeupDroopyEyes,
                                        "Wide Eyes" => $fashion->makeupWideEyes,
                                        "Small Eyes" => $fashion->makeupSmallEyes,
                                        "Accentuated Cheekbones" => $fashion->makeupAccentuatedCheekbones,
                                        "Dark Circles" => $fashion->makeupDarkCircles,
                                        "Small Lips" => $fashion->makeupSmallLips,
                                        "Large Forehead" => $fashion->makeupLargeForehead,
                                        "More Youthful Look" => $fashion->makeupMoreYouthfullLook,
                                        "When you wear black" => $fashion->makeupWhenYouWearBlack
                                        ),
                            "fashionQuiz"=> array(
                                            "currentQuestion" => $fashion               ->fashionQuizCurrentQuestion,
                                            "q1" => $fashion -> fashionQuizQ1,
                                            "q2" => $fashion -> fashionQuizQ2,
                                            "q3" => $fashion -> fashionQuizQ3,
                                            "q4" => $fashion -> fashionQuizQ4,
                                            "q5" => $fashion -> fashionQuizQ5,
                                            "q6" => $fashion -> fashionQuizQ6,
                                            "q7" => $fashion -> fashionQuizQ7,
                                            "q8" => $fashion -> fashionQuizQ8,
                                            "q9" => $fashion -> fashionQuizQ9,
                                            "q10" => $fashion -> fashionQuizQ10,
                                            "result1" => $fashion -> fashionQuizResults1,
                                            "result2" => $fashion -> fashionQuizResults2
                                            ),
                            "myFace"=> array(
                                              "length" => $fashion ->myFaceLength,
                                              "side" => $fashion->myFaceSide,
                                              "suggestionType" => $fashion->myFaceSuggestionType
                                            )
                                        
                        )
    );
    

    
    
}
 


function populateFashionOpject($db, $jsonDataFashion){
    $fashion = new FashionWoman($db);
    $userId = $jsonDataFashion->user_id;
    $color = $jsonDataFashion->color;
    $style = $jsonDataFashion->style;
    $flaws = $style ->flaws;
    $makeup = $style->makeup;
    $fashionQuiz = $style->fashionQuiz;
    $myFace = $style->myFace;
     
    // set fashionWife property values
    $fashion->fkeyUserId = $userId;
    $fashion->colorSelectedCategory = $color->selectedCategory;
    $fashion->colorSelectedStyle = $color->selectedStyle;
    $fashion->colorSelectedColor = $color->selectedColor;
    $favouriteColors = $color->favouriteColors;
    $fashion->favouriteColors1 = $favouriteColors[0]->color;
    $fashion->favouriteColors2 = $favouriteColors[1]->color;
    $fashion->favouriteColors3 = $favouriteColors[2]->color;
    $fashion->favouriteColors4 = $favouriteColors[3]->color;
    $fashion->colorSelectedSummary = $color->selectedSummary;
    $fashion->bustSize = $style->bustSize;
    $fashion->waistSize = $style->waistSize;
    $fashion->hipSize = $style->hipSize;
    $fashion->shapeType = $style->shapeType;
    $fashion->neckLenghtType = $style->neckLengthType;
    $fashion->height = $style->height;
    $fashion->bottomSize = $style->bottomSize;
    $fashion->segmentType = $style->segmentType;

    $fashion->flawsSaddleBags = $flaws->{'Saddle bags'};

    $fashion->flawsHips = $flaws->Hips;
    $fashion->flawsBreastsTooSmall = $flaws->{'Breasts: too small'};
    $fashion->flawsBreastsTooLarge = $flaws->{'Breasts: too large'};
    $fashion->flawsLowerLegs = $flaws->{'Lower legs'};
    $fashion->flawsOverweight = $flaws->Overweight;
    $fashion->flawsDoubleChin = $flaws->{'Double chin'};
    $fashion->flawsBigButtocks = $flaws->{'Big buttocks'};
    $fashion->flawsStomachLoveHandles = $flaws->{'Stomach/love handles'};
    $fashion->flawsHollowBack = $flaws->{'Hollow back'};
    $fashion->flawsArms = $flaws->{'Arms'};
    $fashion->makeupDroopyEyes = $makeup ->{'Droopy Eyes'};
    $fashion->makeupWideEyes = $makeup ->{'Wide Eyes'};
    $fashion->makeupSmallEyes = $makeup ->{'Small Eyes'};
    $fashion->makeupAccentuatedCheekbones =  $makeup ->{'Accentuated Cheekbones'};
    $fashion->makeupDarkCircles = $makeup ->{'Dark Circles'};
    $fashion->makeupSmallLips = $makeup ->{'Small Lips'};
    $fashion->makeupLargeForehead = $makeup ->{'Large Forehead'};
    $fashion->makeupMoreYouthfullLook = $makeup ->{'More Youthful Look'};
    $fashion->makeupWhenYouWearBlack = $makeup ->{'When you wear black'};
    $fashion->fashionQuizCurrentQuestion = $fashionQuiz-> currentQuestion;
    $fashion->fashionQuizQ1 = $fashionQuiz-> q1;
    $fashion->fashionQuizQ2 = $fashionQuiz-> q2;
    $fashion->fashionQuizQ3 = $fashionQuiz-> q3;
    $fashion->fashionQuizQ4 = $fashionQuiz-> q4;
    $fashion->fashionQuizQ5 = $fashionQuiz-> q5;
    $fashion->fashionQuizQ6 = $fashionQuiz-> q6;
    $fashion->fashionQuizQ7 = $fashionQuiz-> q7;
    $fashion->fashionQuizQ8 = $fashionQuiz-> q8;
    $fashion->fashionQuizQ9 = $fashionQuiz-> q9;
    $fashion->fashionQuizQ10 = $fashionQuiz-> q10;
    $fashion->fashionQuizResults1 = $fashionQuiz-> result1;
    $fashion->fashionQuizResults2 = $fashionQuiz-> result2;
    $fashion->myFaceLength = $myFace-> length;
    $fashion->myFaceSide = $myFace-> side;
    $fashion->myFaceSuggestionType = $myFace-> suggestionType;
    
    return $fashion->updateFashion();
    //return $fashion->testUpdate();
}


function strictEmpty($var) {

    // Delete this line if you want space(s) to count as not empty
    $var = trim($var);
    
    if(isset($var) === true && $var === '') {
    
       return true;
    
    }
    else {
    
        return false;
    
    }

}

 

 
//$jwt = getBearerToken();
 
/** 
 * Get header Authorization
 * */
function getAuthorizationHeader(){
        $headers = null;
        if (isset($_SERVER['Authorization'])) {
            $headers = trim($_SERVER["Authorization"]);
        }
        else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
            $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
        } elseif (function_exists('apache_request_headers')) {
            $requestHeaders = apache_request_headers();
            // Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
            $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
            //print_r($requestHeaders);
            if (isset($requestHeaders['Authorization'])) {
                $headers = trim($requestHeaders['Authorization']);
            }
        }
       // $headers = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLm9yZyIsImF1ZCI6Imh0dHA6XC9cL2V4YW1wbGUuY29tIiwiaWF0IjoxMzU2OTk5NTI0LCJuYmYiOjEzNTcwMDAwMDAsImRhdGEiOnsiaWQiOiIzIiwiZW1haWwiOiJlbWlsZUBpZGVhczRhcHBzLmNvLnphIn19.PsusjAZ10bdOtOuB0CCTv9O3D68-v_YRaCC48oYh_EI";
        return $headers;
    }
/**
 * get access token from header
 * */
function getBearerToken() {
    $headers = getAuthorizationHeader();
    // HEADER: Get the access token from the header
    if (!empty($headers)) {
        if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
            return $matches[1];
        }
    }
    return "";
}
?>