<?php
header('Access-Control-Allow-Origin: *');
header("Content-type: application/json; charset=utf-8");

//die();

if (isset($_SERVER['HTTP_ORIGIN'])) {
    // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
    // you want to allow, and if so:
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 1000');
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
        // may also be using PUT, PATCH, HEAD etc
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
    }

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
        header("Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization");
    }
    exit(0);
}

// error_reporting(0);

include '../../../utils/database.php';
include '../../../utils/helper.php';

$response1['success'] = 'false';
$response1['message'] = '500';


$price = 725;


$conn = new mysqli($servername, $username, $password, $dbname_process);
// Check connection
mysqli_set_charset($conn, "utf8");
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error); 
}

// Get the raw POST data
$rawData = file_get_contents('php://input');

// Decode the JSON into a PHP array
$data = json_decode($rawData, true);

// Now you can access the users array
$users = $data['users'] ?? [];

$currentTime = time();

$data = array();

$addedRecord = 0;
$allRecord = sizeof($users);
for ($i=0; $i<sizeof($users); $i++){
    $phone = $users[$i]["phone"];
    $persona = $users[$i]["persona"];
    $firstName = $users[$i]["firstName"];
    $type = $users[$i]["type"];
    $type = strtoupper($type);
    
    $tamdidToken = getUniqueToken();
    $token = md5(uniqid(rand(), true)) . md5(uniqid(rand(), true)) . md5(uniqid(rand(), true));
    
    $disPrice = getPriceFromType($type);
    $discountPercent = getDiscountFromType($type);
    
    $conn->query("UPDATE tamdid SET `active`=0 WHERE `phone`='$phone'");
    if ($conn->query("INSERT IGNORE INTO tamdid(`phone` , `persona` , `tamdidToken` , `discountPercent` , `price` , `disPrice` , `token` , `createdAt` , `type` , `firstName`)
        VALUES ('$phone' , '$persona' , '$tamdidToken' , '$discountPercent' , '$price' , '$disPrice' , '$token' , '$currentTime' , '$type' , '$firstName')")) {
        $addedRecord++;
        
        $res["phone"] = $phone;
        $res["token"] = "tmd".$tamdidToken;
        
        array_push($data , $res);
    }
}

$response1['success'] = 'true';
$response1['message'] = $addedRecord . " / " . $allRecord . " records added!";
$response1['result'] = $data;
$json_response = json_encode($response1);
echo $json_response;
die();

function getDiscountFromType($type){
    switch ("$type"){
        case "R1":
            return 25;
        case "R2":
            return 25; 
        case "R3":
            return 25;
        case "R4":
            return 25;
        case "R5":
            return 30; 
        case "R6":
            return 20;
        case "R7":
            return 30;
        case "R8":
            return 30; 
        case "R9":
            return 30; 
        case "R10":
            return 30;  
        case "R11":
            return 25;    
        case "R12":
            return 25; 
    }
}
function getPriceFromType($type){
    switch ("$type"){
        case "R1":
            return 543;
        case "R2":
            return 543; 
        case "R3":
            return 543;
        case "R4":
            return 543;
        case "R5":
            return 499; 
        case "R6":
            return 579;
        case "R7":
            return 499;
        case "R8":
            return 499; 
        case "R9":
            return 499; 
        case "R10":
            return 499;    
        case "R11":
            return 543;    
        case "R12":
            return 543;    
    }
}


function getUniqueToken($tokenLength = 8){
    $token = "";
    //Combination of character, number and special character...
    $combinationString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for($i=0;$i<$tokenLength;$i++){
        $token .= $combinationString[uniqueSecureHelper(0,strlen($combinationString))];
    }
    return $token;
}

/*
    This helper function will return unique and secure string...
*/
function uniqueSecureHelper($minVal, $maxVal) {
        $range = $maxVal - $minVal;
        if ($range < 0) return $minVal; // not so random...

        $log = log($range, 2);
        $bytes = (int) ($log / 8) + 1; // length in bytes
        $bits = (int) $log + 1; // length in bits
        $filter = (int) (1 << $bits) - 1; // set all lower bits to 1

        do {
            $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
            $rnd = $rnd & $filter; // discard irrelevant bits
        } while ($rnd >= $range);
        return $minVal + $rnd;
}