<?php
// require_once('../../vendor/autoload.php');
require_once('../init.php');

function error_res($status, $response_code, $message)
{
    $response = new stdClass;
    $response->status = $status;
    $response->response_code = $response_code;
    $response->message = $message;
    return json_encode($response);
}

foreach ($_POST as $key => $value) {
    $_POST[$key] = htmlspecialchars(trim($value), ENT_QUOTES, 'UTF-8');
}
extract($_POST);
// print_r($_POST);

if (isset($phone, $password, $address, $first_name, $last_name, $business_name, $email) && !empty($phone) && !empty($password) && !empty($address) && !empty($email)) {

    $userr = User::find_by_query("SELECT * FROM user WHERE email='$email'");
    if ($userr) {
        echo error_res(false, "03", "Email Address Already Existed!");
        exit;
    }
    $userrr = User::find_by_query("SELECT * FROM user WHERE business_name='$business_name'");
    if ($userrr) {
        echo error_res(false, "03", "Business Name Already Taken!");
        exit;
    }
    $userrrr = User::find_by_query("SELECT * FROM user WHERE phone='$phone'");
    if ($userrrr) {
        echo error_res(false, "03", "Phone Number Already Registered!");
        exit;
    }

    $user = new User;

    $user->first_name = trim($first_name);
    $user->last_name = trim($last_name);
    $user->business_name = trim($business_name);
    $user->phone = $phone;
    $user->email = $email;
    $user->password = trim($password);
    $user->address = trim($address);
    $user->status = 1;

    // $id = base64_decode($referrer);
    // if (is_int($id)) {
    //     $referrer_user = User::find_by_id($id);
    //     if ($referrer_user) {
    //         $user->referrer = $referrer_user->id;
    //     }
    // }

    if ($user->save()) {

        // include ENVIRONMENT == 'prod' ? '../../email/qservers_mail_attachment_create.php' : '../../email/mail_verify_dev.php';
        // include ENVIRONMENT == 'prod' ? '../../email/mail_verify_prod.php' : '../../email/mail_verify_dev.php';

        $wallet = new Wallet;
        $wallet->user_id = $user->id;
        $wallet->balance = 0;
        if ($wallet->save()) {
            // $_SESSION['user_id'] = $user->id;
            echo error_res(true, "00", "Profile Created Successful");
            exit;
        } else {
            echo error_res(false, "03", "Profile Creation Failed!");
            exit;
        }
    } else {

        echo error_res(false, "03", "Registration Error Contact Administrator!");
        exit;
    }
} else {

    echo error_res(false, "03", "Registration Error Contact Administratorrrr!");
    exit;
}
