<?php

require __DIR__ . "/required.php";


try {
    $client = new GuzzleHttp\Client();
    $response = $client
            ->request('POST', CLOUD_URL, [
        'form_params' => [
        	'id' => CLOUD_ID,
            'key' => CLOUD_KEY,
            'action' => "getaccounts"
        ]
    ]);
    if ($response->getStatusCode() != 200) {
    	if ($VARS['web'] == "1") {
			header("Location: ./index.php?page=home&err=remotefail");
		}
		echo "Error: Remote server error.  Try again later.";
		die();
    }
    $resp = json_decode($response->getBody(), TRUE);
    $database->delete('accounts', []);
    foreach ($resp as $p) {
    	$database->insert('accounts', ["uid" => $p['uid'], "username" => $p['username'], "password" => $p['password'], "authsecret" => $p['authsecret']]);
    }
    if ($database->has('config', ['key' => 'lastsync'])) {
    	$database->update('config', ['value' => time()], ['key' => 'lastsync']);
    } else {
       	$database->insert('config', ['key' => 'lastsync', 'value' => time()]);
    }
    if ($VARS['web'] == "1") {
	    header("Location: ./index.php?page=home&msg=syncok");
    }
    echo "Sync complete.";
    die();
} catch (Exception $e) {
    if ($VARS['web'] == "1") {
		header("Location: ./index.php?page=home&err=fail");
	}
	echo "Error: " . $e->getMessage();
	die();
}
