<?php
/**
 * Team Member Registration via Invitation Link Token
 * Location: public_html/team_register.php
 */

require_once __DIR__ . '/connections/connect.php';
require_once __DIR__ . '/includes/functions.php';

$token = $_GET['token'] ?? '';
$error = '';
$success = false;
$invitation = null;
$company_name = '';

if (empty($token)) {
    $error = "Missing team invitation token.";
} else {
    // Validate Token
    $stmt = $pdo->prepare("SELECT ti.*, a.company_name FROM team_invitations ti JOIN accounts a ON ti.account_id = a.id WHERE ti.invite_token = ? AND ti.status = 'PENDING' AND ti.expires_at > NOW()");
    $stmt->execute([$token]);
    $invitation = $stmt->fetch();

    if (!$invitation) {
        $error = "This team invitation link is invalid or has expired.";
    } else {
        $company_name = $invitation['company_name'];
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $invitation) {
    $full_name = sanitize_input($_POST['full_name'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if (empty($full_name)) {
        $error = "Please enter your Full Name.";
    } elseif (strlen($password) < 6) {
        $error = "Password must be at least 6 characters.";
    } elseif ($password !== $confirm_password) {
        $error = "Passwords do not match.";
    } else {
        try {
            $pdo->beginTransaction();

            $user_id = 'usr_' . bin2hex(random_bytes(6));
            $name_parts = explode(' ', $full_name, 2);
            $first_name = $name_parts[0];
            $last_name = $name_parts[1] ?? '';
            $password_hash = password_hash($password, PASSWORD_DEFAULT);

            // Insert User linked to existing Account
            $stmt_usr = $pdo->prepare("INSERT INTO users (id, account_id, email, password_hash, first_name, last_name, role, is_verified) VALUES (?, ?, ?, ?, ?, ?, ?, 1)");
            $stmt_usr->execute([$user_id, $invitation['account_id'], $invitation['email'], $password_hash, $first_name, $last_name, $invitation['role']]);

            // Mark invitation accepted
            $stmt_inv = $pdo->prepare("UPDATE team_invitations SET status = 'ACCEPTED' WHERE id = ?");
            $stmt_inv->execute([$invitation['id']]);

            $pdo->commit();

            $success = true;
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Error creating team account: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Accept Team Invitation - MiBuildqc</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 min-h-screen flex items-center justify-center p-4">

    <div class="bg-white rounded-[24px] max-w-[420px] w-full p-8 shadow-xl border border-slate-100 space-y-6">
        <div class="bg-[#E8E5FF] rounded-xl py-3 px-6 text-center">
            <span class="text-3xl font-extrabold text-slate-900">MiBuild<span class="text-[#635BFF]">qc</span></span>
        </div>

        <h1 class="text-xl font-bold text-center text-slate-800">
            Join <?php echo htmlspecialchars($company_name); ?> Team
        </h1>

        <?php if ($success): ?>
            <div class="p-4 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-800 text-xs text-center space-y-3">
                <p>Welcome to the team! Your account has been created and verified.</p>
                <a href="login.php" class="inline-block px-5 py-2.5 bg-indigo-600 text-white font-bold rounded-xl">Go to Login</a>
            </div>
        <?php elseif ($error && !$invitation): ?>
            <div class="p-4 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-xs text-center">
                <?php echo $error; ?>
            </div>
        <?php else: ?>

            <?php if ($error): ?>
                <div class="p-3 rounded-xl bg-rose-50 text-rose-800 text-xs"><?php echo $error; ?></div>
            <?php endif; ?>

            <form action="team_register.php?token=<?php echo htmlspecialchars($token); ?>" method="POST" class="space-y-4">
                <div>
                    <label class="block text-xs font-semibold text-slate-500 mb-1">Email (Invited)</label>
                    <input type="text" disabled value="<?php echo htmlspecialchars($invitation['email']); ?>" class="w-full px-3.5 py-2.5 rounded-xl border bg-slate-100 text-sm font-mono text-slate-600">
                </div>

                <div>
                    <label class="block text-xs font-semibold text-slate-500 mb-1">Your Full Name</label>
                    <input type="text" name="full_name" required placeholder="Jane Smith" class="w-full px-3.5 py-2.5 rounded-xl border text-sm">
                </div>

                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-xs font-semibold text-slate-500 mb-1">Password</label>
                        <input type="password" name="password" required class="w-full px-3.5 py-2.5 rounded-xl border text-sm">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-500 mb-1">Confirm Password</label>
                        <input type="password" name="confirm_password" required class="w-full px-3.5 py-2.5 rounded-xl border text-sm">
                    </div>
                </div>

                <button type="submit" class="w-full py-3 px-4 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold uppercase tracking-wider">
                    Complete Team Registration
                </button>
            </form>

        <?php endif; ?>
    </div>

</body>
</html>