<?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 {

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

    // ✅ Read JSON input
    $input = json_decode(file_get_contents("php://input"), true);
    $email = trim($input['email'] ?? '');

    if (empty($email)) {
        sendResponse(400, "Email is required");
        exit;
    }

    // ✅ Firebase user check
    try {
        $user = $auth->getUserByEmail($email);
    } catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) {
        sendResponse(404, "User not found in Firebase");
        exit;
    }

    // ❌ Email not verified
    if (!$user->emailVerified) {
        sendResponse(200, "Email not verified", [
            "emailVerified" => false
        ]);
        exit;
    }

    // ✅ Check DB
    $check = $conn->prepare("SELECT id FROM users WHERE email = ?");
    $check->execute([$email]);

    if ($check->rowCount() === 0) {

        session_start();

        // ✅ Insert sub-admin
        $stmt = $conn->prepare(
            "INSERT INTO users (name, email, role, firebase_uid) VALUES (?, ?, ?, ?)"
        );

        $stmt->execute([
            $user->displayName ?? '',
            $email,
            'subadmin',
            $user->uid
        ]);

        $userId = $conn->lastInsertId();
        $_SESSION['user_id'] = $userId;

        // ✅ Fetch admins
        $stmt = $conn->prepare(
            "SELECT email, name FROM users 
             WHERE role = 'admin' 
             AND deleted_at IS NULL 
             AND email IS NOT NULL"
        );
        $stmt->execute();
        $admins = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // ✅ Email data
        $subAdminName  = $user->displayName ?? '';
        $subAdminEmail = $email;

        foreach ($admins as $admin) {

            $senderMail = $admin['email'];

            $subject = "New Sub-Admin Account Created – Action Required";

            $body = "
                <p>Hello Admin,</p>

                <p>A new <strong>Sub-Admin account</strong> has been created on 
                <strong>Carrier Jobs</strong>.</p>

                <p><strong>Sub-Admin Details:</strong></p>
                <ul>
                    <li><strong>Name:</strong> {$subAdminName}</li>
                    <li><strong>Email:</strong> {$subAdminEmail}</li>
                </ul>

                <p>Please review this request and take the necessary action:</p>
                <ul>
                    <li>Accept or Reject the Sub-Admin request</li>
                    <li>Assign appropriate permissions</li>
                </ul>

                <p>You can manage this request from the admin panel.</p>

                <br>

                <p>Regards,<br>
                <strong>Carrier Jobs System</strong></p>
            ";

            include dirname(__DIR__) . "/email_send/send_email.php";
        }

    } else {
        // Existing user
        $existingUser = $check->fetch(PDO::FETCH_ASSOC);
        session_start();
        $_SESSION['user_id'] = $existingUser['id'];
    }

    // ✅ Final response
    sendResponse(200, "Email verified successfully", [
        "emailVerified" => true
    ]);

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