<?php

include_once dirname(__DIR__, 2) . "/config/dbcon.php";
include_once dirname(__DIR__, 2) . "/helpers/api_helper.php";

include_once dirname(__DIR__, 2) . "/firebase/firebase_init.php";

try {

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(405, "Method Not Allowed");
    }

    $input = json_decode(file_get_contents("php://input"), true);

    $name = $input['name'] ?? null;
    $email = $input['email'] ?? null;
    $password = $input['password'] ?? null;

    if (empty($name) && empty($email) && empty($password)) {
        sendResponse(400, "Name, Email and Password are required");
    }

    if (empty($name)) {
        sendResponse(400, "Field 'name' is required");
    }

    if (empty($email)) {
        sendResponse(400, "Field 'email' is required");
    }

    if (empty($password)) {
        sendResponse(400, "Field 'password' is required");
    }

    $userProperties = [
        'email' => $email,
        'password' => $password,
        'displayName' => $name,
        'emailVerified' => false,
    ];

    $createdUser = $auth->createUser($userProperties);
    $uid = $createdUser->uid;


    $auth->sendEmailVerificationLink($email);

    sendResponse(201, "Registration Successful. Verification email sent!", [
        'uid' => $uid,
        'name' => $name,
        'email' => $email,
        'emailVerification' => "sent"
    ]);

} catch (\Kreait\Firebase\Exception\Auth\EmailExists $e) {

    sendResponse(409, "Email already registered");

} catch (Exception $e) {

    sendResponse(500, $e->getMessage());

}
