<?php
header("Access-Control-Allow-Origin: *");
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");
//import config file for database access
require_once('../../config.php');

require_once('./validatekey.php');

$response = [];

//code for testing
// $username = '940082756';
// $key = 'abcdefghijk';

$data = json_decode(file_get_contents('php://input'), true);

//handling the data posted through url
if (isset($data['username']) && isset($data['key'])) {
    $username = $data['username'];
    $key = $data['key'];

    $objvalidate = new validatekey($CFG->dbhost, $CFG->dbname, $CFG->dbuser, $CFG->dbpass);

    //check user and fetching key

    $userdetails = $objvalidate->validateuser($username);


    if (!empty($userdetails)) {
        foreach ($userdetails as $user) {
            if ($user->installstatus != "Installed") {
                if ($key == $user->serialkey) {
                    $objvalidate->updateinstallationstatus($user->id);
                    http_response_code(200);
                    $response['status'] = 'success';
                    $response['message'] = 'Key installed successfully';
                } else {
                    http_response_code(200);
                    $response['status'] = 'failed';
                    $response['message'] = 'Invalid key';
                }
            } else {
                http_response_code(200);
                $response['status'] = 'failed';
                $response['message'] = 'Key alredy installed';
            }
        }
    } else {
        http_response_code(200);
        $response['status'] = 'failed';
        $response['message'] = 'Invalid user';
    }
} else {
    http_response_code(400);
    $response['status'] = 'failed';
    $response['message'] = 'Invalid Params';
}
echo json_encode($response);
