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

    $input = json_decode(file_get_contents("php://input"), true);
    $userId = $_POST['id'] ?? null;

    if (!$userId) {
        sendResponse(400, "User id is required");
    }

    // 🔹 Fetch firebase UID
    $stmt = $conn->prepare(
        "SELECT firebase_uid FROM users 
         WHERE id = ? AND deleted_at IS NULL"
    );
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        sendResponse(404, "User not found");
    }

    $firebaseUid = $user['firebase_uid'];

    // 🔥 Delete Firebase user
    $auth->deleteUser($firebaseUid);

    // 🔹 Soft delete in DB
    $stmt = $conn->prepare(
        "UPDATE users 
         SET deleted_at = NOW()
         WHERE id = ?"
    );
    $stmt->execute([$userId]);

    sendResponse(200, "User deleted successfully");

} catch (Exception $e) {
    sendResponse(500, $e->getMessage());
}
