<?php
require_once __DIR__ . "/settings.php";
require_once __DIR__ . "/database.php";

session_start();
$plan = $_POST['plan'];
if (!isset(PLANS[$plan])) {
    header("Location: /#pricing");
    die("Invalid plan chosen.");
}
if (!isset($_SESSION['username']) || !isset($_SESSION['password']) || !isset($_SESSION['renewing'])) {
    header("Location: /");
    die();
}

\Stripe\Stripe::setApiKey(STRIPE_SK);

$token = $_POST['stripeToken'];
$email = $_POST['email'];

try {
    // Free plan
    if (PLANS[$plan]["monthly"] == 0) {
        $free = TRUE;
    }

    if (!$free && $email !== $_POST['stripeEmail']) {
        throw new Exception("You need to use the same email for payment and for your account.");
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new Exception("The email you supplied is not valid.  You need a valid email address to use the service.");
    }

    if (!$free) {
        $customer = \Stripe\Customer::create(array(
                    'email' => $database->select('accounts', 'email', ['accountid' => $_SESSION['accountid']])[0],
                    'source' => $token
        ));

        $charge = \Stripe\Charge::create(array(
                    'customer' => $customer->id,
                    'amount' => PLANS[$plan]["monthly"] * 100,
                    'currency' => 'usd'
        ));

        if (!$charge['paid']) {
            throw new Exception("The charge did not complete successfully.  Reason: " . $charge["failure_message"]);
        }
    }

    $error = false;
    $message = ($free ? "Your account is now active!" : "Your purchase was successful!");

    // Setup cURL
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_USERPWD, NEXTCLOUD_USER . ":" . NEXTCLOUD_PASS);
    curl_setopt($curl, CURLOPT_HTTPHEADER, ['OCS-APIRequest: true', "Content-Type: application/x-www-form-urlencoded"]);

    if ($_SESSION['renewing'] == TRUE) {
        // Enable account
        curl_setopt($curl, CURLOPT_URL, "https://dontsell.me/ocs/v1.php/cloud/users/" . urlencode($_SESSION['username']) . "/enable");
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
        $out = curl_exec($curl);
        if (strpos($out, "<status>ok</status>") === FALSE) {
            preg_match('/\<message\>(.*?)\<\/message\>/', $out, $match);
            throw new Exception("Your payment was successful, but we could not setup your account.  <a href=\"https://support.netsyms.com\">Click here to contact support.</a>  Reason: " . $match[1]);
        }
        // Set quota
        curl_setopt($curl, CURLOPT_URL, "https://dontsell.me/ocs/v1.php/cloud/users/" . urlencode($_SESSION['username']));
        curl_setopt($curl, CURLOPT_POSTFIELDS, "key=quota&value=" . PLANS[$plan]["mb"] . "MB");
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
        $out = curl_exec($curl);
        if (strpos($out, "<status>ok</status>") === FALSE) {
            preg_match('/\<message\>(.*?)\<\/message\>/', $out, $match);
            throw new Exception("Your payment was successful, but we could not setup your account.  <a href=\"https://support.netsyms.com\">Click here to contact support.</a>  Reason: " . $match[1]);
        }

        // Check if account is active on the same plan
        if ($database->has("billing", ["uid" => $_SESSION['username'], "validuntil[>=]" => date("Y-m-d"), "quota" => PLANS[$plan]["mb"]])) {
            $rows = $database->select("billing", "validuntil", ["uid" => $_SESSION['username'], "validuntil[>=]" => date("Y-m-d"), "quota" => PLANS[$plan]["mb"]]);
            $latest = time();
            foreach ($rows as $r) {
                if (strtotime($r) > $latest) {
                    $latest = strtotime($r);
                }
            }
            // Add billing data
            $database->insert("billing", [
                "uid" => $_SESSION['username'],
                "validfrom" => date("Y-m-d"),
                "validuntil" => date("Y-m-d", strtotime("+30 days", $latest)),
                "quota" => PLANS[$plan]["mb"]]
            );
        } else {
            // Add billing data
            $database->insert("billing", [
                "uid" => $_SESSION['username'],
                "validfrom" => date("Y-m-d"),
                "validuntil" => date("Y-m-d", strtotime("+30 days")),
                "quota" => PLANS[$plan]["mb"]]
            );
        }
    } else {
        // Add user
        curl_setopt($curl, CURLOPT_URL, "https://dontsell.me/ocs/v1.php/cloud/users");
        $postfields = "userid=" . urlencode($_SESSION['username']) . "&password=" . urlencode($_SESSION['password']) . "";
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        $out = curl_exec($curl);
        if (strpos($out, "<status>ok</status>") === FALSE) {
            preg_match('/\<message\>(.*?)\<\/message\>/', $out, $match);
            throw new Exception("Your payment was successful, but we could not setup your account.  <a href=\"https://support.netsyms.com\">Click here to contact support.</a>  Reason: " . $match[1]);
        }

        // Set quota
        curl_setopt($curl, CURLOPT_URL, "https://dontsell.me/ocs/v1.php/cloud/users/" . urlencode($_SESSION['username']));
        curl_setopt($curl, CURLOPT_POSTFIELDS, "key=quota&value=" . PLANS[$plan]["mb"] . "MB");
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
        $out = curl_exec($curl);
        if (strpos($out, "<status>ok</status>") === FALSE) {
            preg_match('/\<message\>(.*?)\<\/message\>/', $out, $match);
            throw new Exception("Your payment was successful, but we could not setup your account.  <a href=\"https://support.netsyms.com\">Click here to contact support.</a>  Reason: " . $match[1]);
        }
        // Set email
        curl_setopt($curl, CURLOPT_URL, "https://dontsell.me/ocs/v1.php/cloud/users/" . urlencode($_SESSION['username']));
        curl_setopt($curl, CURLOPT_POSTFIELDS, "key=email&value=$email");
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
        $out = curl_exec($curl);
        if (strpos($out, "<status>ok</status>") === FALSE) {
            preg_match('/\<message\>(.*?)\<\/message\>/', $out, $match);
            throw new Exception("Your payment was successful, but we could not setup your account.  <a href=\"https://support.netsyms.com\">Click here to contact support.</a>  Reason: " . $match[1]);
        }
        
        // Add billing data
        $database->insert("billing", [
            "uid" => $_SESSION['username'],
            "validfrom" => date("Y-m-d"),
            "validuntil" => date("Y-m-d", strtotime("+30 days")),
            "quota" => PLANS[$plan]["mb"]]
        );
    }
} catch (Exception $e) {
    $error = true;
    $message = "Something went wrong.  Details:<br />" . $e->getMessage();
    file_put_contents("../../billingerrors.log", "[" . date("Y-m-d H:i:s") . "]\t" . $_SESSION['username'] . "\t" . $e->getMessage() . "\n", FILE_APPEND);
}
unset($_SESSION['username']);
unset($_SESSION['password']);
unset($_SESSION['renewing']);
?>
<!DOCTYPE HTML>
<title><?php echo SITE_TITLE; ?></title>
<?php
include __DIR__ . '/inc/meta.php';
include __DIR__ . '/inc/piwik.php';
?>
<!-- Wrapper -->
<div id="wrapper">

    <?php include __DIR__ . "/inc/header.php"; ?>

    <!-- Section -->
    <section id="one" class="main alt">
        <header class="accent1">
            <?php
            if ($error === TRUE) {
                echo "<h1>Oops...</h1>";
            } else {
                echo "<h1>Thanks!</h1>";
            }
            ?>
        </header>
        <div class="inner alt">
            <div class="content">
                <?php
                if ($error !== TRUE) {
                    ?>
                    <div style="text-align: center;">
                        <img src="assets/large-checkmark.svg" style="max-width: 50%; max-height: 200px;"/><br />
                        <?php
                        echo $message;
                        ?>
                    </div>
                    <?php
                } else {
                    echo $message;
                }
                ?>
                <p>
            </div>
        </div>
    </section>

    <?php include __DIR__ . "/inc/footer.php"; ?>

</div>

<?php include __DIR__ . "/inc/scripts.php"; ?>