<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'db/config.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

if (empty($_POST['email']) || empty($_POST['firstname']) || empty($_POST['lastname'])  || empty($_POST['password'])) {
    $output = ['status' => false, 'success' => "Some Missing Information"];
    echo json_encode($output);
    exit();
}

function check_input($par) {
    return htmlspecialchars(stripslashes(trim($par)));
}


if (
    empty($_POST['email']) ||
    empty($_POST['firstname']) ||
    empty($_POST['lastname']) ||
    empty($_POST['password']) ||
    empty($_POST['dob'])
) {
    $output = ['status' => false, 'success' => "Some Missing Information"];
    echo json_encode($output);
    exit();
}

$firstname = mysqli_escape_string($con, check_input($_POST['firstname']));
$lastname = mysqli_escape_string($con, check_input($_POST['lastname']));
$email = mysqli_escape_string($con, check_input($_POST['email']));
$phone = mysqli_escape_string($con, check_input($_POST['phone']));
$password = mysqli_escape_string($con, check_input($_POST['password']));
$dob = mysqli_escape_string($con, check_input($_POST['dob']));


$birthDate = new DateTime($dob);
$today = new DateTime();
$age = $today->diff($birthDate)->y;

if ($age < 18) {
    echo json_encode([
        'status' => false,
        'success' => "You must be 18 and above"
    ]);
    exit();
}


$pass2 = sha1($password);

// Check if email or phone already exists
$sql2 = "SELECT * FROM users WHERE email = '$email'";
$result2 = $con->query($sql2);
if ($result2->num_rows >= 1) {
    echo json_encode(['status' => false, 'success' => "Account Already Exists"]);
    exit();
}

// Generate Unique User ID
function check_number($con) {
    $unique_number = rand(100000000, 999999999);
    $sql = $con->query("SELECT * FROM users WHERE user_id = '$unique_number'");
    return ($sql->num_rows > 0) ? check_number($con) : $unique_number;
}

$user_id = check_number($con);

// Generate Verification Code
function gen_code() {
    return rand(100000, 999999);

}

$ver_code = gen_code();

date_default_timezone_set("Africa/Lagos");
$date_t = date("d-M-Y h:i:s a");
$code_exp = strtotime("+10 minutes");
$auth = sha1(rand(1000000000, 9999999999));


$sqlx = $con->query("INSERT INTO users 
(user_id, auth, firstname, lastname, email, phone, password, package, status, ver_code, code_expiry, date_reg, dob) 
VALUES 
('$user_id', '$auth', '$firstname', '$lastname', '$email', '$phone', '$pass2', 'Free', 'Pending', '$ver_code', '$code_exp', '$date_t', '$dob')");



if ($sqlx) {
    // Send Email
    $subject = "Your Verification Code!";
    $message = '<!DOCTYPE HTML>
    <html>
    <body>
    <p>Dear ' . $firstname . ',</p>
    <p>You just created an account on MVASA.</p>
    <p>Your verification code is <strong>' . $ver_code . '</strong></p>
    </body>
    </html>';

    $mail = new PHPMailer();
    require 'mail_head.php';
    $mail->setFrom('tech@diimtech.com', 'MVASA');
    $mail->addAddress($email);
    $mail->addBcc("diimtech@gmail.com");
    $mail->Subject = $subject;
    $mail->msgHTML($message);
    $mail->Send();

    // Send SMS via Termii API
    $p_len = strlen($phone);
    $send = ($p_len == 11) ? "234" . substr($phone, -10) : (($p_len == 10) ? "234" . $phone : null);

    if ($send) {
       /* $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => 'https://api.ng.termii.com/api/sms/send',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => [
                'api_key' => 'TLoKQsvIlcSxHmM3AyxOCQgRgWEZSBgKmTSnDf2ozdeqLxo56anMUUCb84mzAg',
                'to' => $send,
                'from' => 'N-Alert',
                'sms' => "Your FindWhoSabi confirmation code is $ver_code. Valid for 10 minutes, one-time use only.",
                'type' => 'plain',
                'channel' => 'dnd'
            ]
        ]);
        curl_exec($curl);
        curl_close($curl); */
    }

    $output = ['status' => true, 'success' => "Successful", 'user_id' => $user_id, 'email' => $email, 'auth' => $auth];
} else {
    $output = ['status' => false, 'success' => "Database Insertion Failed"];
}

$con->close();
echo json_encode($output);
?>
