<?php
header("Content-Type: application/json");
require_once __DIR__ . "/../auth/require-auth.php";
require_once __DIR__ . "/../services/db.php";

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

$projectId = isset($data['project_id']) ? (int)$data['project_id'] : null;
$email = strtolower(trim($data['email'] ?? ''));
$invitedBy = $_SESSION['user']['id'] ?? 1;

if (!$projectId || !$email) {
    http_response_code(400);
    echo json_encode(["error" => "project_id and email are required"]);
    exit;
}

// 1. Generate unique token
$token = bin2hex(random_bytes(16));

$sql = "INSERT INTO invitations (project_id, email, token, invited_by, created_at) VALUES (?, ?, ?, ?, GETDATE())";
$stmt = sqlsrv_query($conn, $sql, [$projectId, $email, $token, $invitedBy]);

if ($stmt === false) {
    http_response_code(500);
    echo json_encode(["error" => "Failed to generate invite", "details" => sqlsrv_errors()]);
    exit;
}

// 2. Dynamically determine protocol and host
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST'] ?? '51.79.53.46:8080'; // Fallback server IP if HTTP_HOST isn't present

// 🔑 Clean HashRouter URL formatting:
if (strpos($host, 'localhost:5173') !== false) {
    $inviteUrl = "{$protocol}{$host}/#/register?token=" . $token;
} else {
    // Production / Server path
    $inviteUrl = "{$protocol}{$host}/HZ-ProjectHub-v2/frontend/dist/#/register?token=" . $token;
}

echo json_encode([
    "success" => true,
    "message" => "Invitation created successfully",
    "invite_url" => $inviteUrl,
    "token" => $token
]);