<?php
session_start();
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");
    }

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

    $email = $input['email'] ?? null;
    $password = $input['password'] ?? null;
    $rememberMe = $input['rememberMe'] ?? false;

    if ($rememberMe) {
        $_SESSION['remember_email'] = $email;
    } else {
        unset($_SESSION['remember_email']);
    }

    // Validation: Both Missing
    if (empty($email) && empty($password)) {
        sendResponse(400, "Email and Password are required");
    }

    // Validation: Email Missing
    if (empty($email)) {
        sendResponse(400, "Field 'email' is required");
    }

    // Validation: Password Missing
    if (empty($password)) {
        sendResponse(400, "Field 'password' is required");
    }

    // Firebase Login
    $signInResult = $auth->signInWithEmailAndPassword($email, $password);
    $uid = $signInResult->firebaseUserId();

    $_SESSION['user_uid'] = $uid;

    sendResponse(200, "Login Successful", [
        "uid" => $uid
    ]);

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

    sendResponse(401, "Invalid password");

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

    sendResponse(404, "User not found");

} catch (Exception $e) {

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

}
