<?php

if (isset($_POST['login'])) {
    include 'dbconnect.php';
    $phone = $_POST['phone'];
    $password = sha1($_POST['password']);
    $token= $_POST['token'];
    tryLoginUser($db, $phone, $password,$token);
}

function tryLoginUser($db, $phone, $password,$token)
{
    $stmt = pg_prepare($db, "login_user", 'SELECT * FROM users WHERE phone = $1 and password = $2');
    $result = pg_execute($db, "login_user", array($phone, $password));

    if (pg_num_rows($result) == 1) {
        $row = pg_fetch_assoc($result);
        $email = $row["email"];
        $verify = strval(emailVerification($email));
        $response = array(
            "success" => true,
            "response" => "Proceed to two-step verification",
            "email" => $row["email"],
            "username" => $row["username"],
            "userid" => $row["id"],
            "description" => $row["description"],
            "profession" => $row["profession"],
            "profile" =>$row["profile"],
            "code" => $verify
        );
$stmt = pg_prepare($db, "update_contact", 'UPDATE reg_contacts SET token = $1 WHERE phone = $2');
$result = pg_execute($db, "update_contact", array($token, $phone));
$affectedRows = pg_affected_rows($result);

        echo json_encode($response);
    } else {
        $response = array(
            "success" => false,
            "response" => "Incorrect user details"
        );
        echo json_encode($response);
    }
}

function emailVerification($email)
{
    $code = mt_rand(10000, 99999);
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://emailapi.netcorecloud.net/v5/mail/send",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "{\"from\":{\"email\":\"info@fixafrica.co.ke\",\"name\":\"BRIDGE VERIFICATION.\"},\"subject\":\"Email Verification Code: \",\"content\":[{\"type\":\"html\",\"value\":\"VERIFICATION CODE IS:<p> $code </p> <br>Valid for the next 10 minutes.<br>\"}],\"personalizations\":[{\"to\":[{\"email\":\"$email\",\"name\":\"$email\"}]}]}",
        CURLOPT_HTTPHEADER => array(
            "api_key: f5928e237eb4142dbb609aa44feeb713",
            "content-type: application/json"
        ),
    ));
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        //  echo $response;
    }
    return strval($code);
}

?>
