<?php
// verify_email_api.php
// API endpoint for admin panel to verify email by providing email in request body (JSON)
// - Expects POST request with JSON: { "email": "user@example.com" }
// - Returns JSON responses for success/error
// - Assumes authentication is handled elsewhere (e.g., via API keys, sessions in admin panel)
// - For security, implement auth checks before using this in production

// ====== CORS HEADERS ======
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}
// ===========================

// Safe logging (no error display)
ini_set('display_errors', '0');
ini_set('log_errors', '1');
if (!ini_get('error_log')) {
    ini_set('error_log', __DIR__ . '/php-error.log');
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Function to send JSON response and exit
function send_json_response($status, $message, $data = null) {
    header('Content-Type: application/json; charset=UTF-8');
    $response = [
        'status' => $status,
        'message' => $message
    ];
    if ($data !== null) {
        $response['data'] = $data;
    }
    echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}

try {
    require_once __DIR__ . '/../unified_config.php';

    // Connect (db() function or $conn provided)
    if (function_exists('db')) {
        $conn = db();
    } elseif (isset($conn) && $conn instanceof mysqli) {
        // ok
    } else {
        throw new Exception("Database connection not provided. Ensure unified_config.php defines db() or \$conn.");
    }

    // Only allow POST requests
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        send_json_response('error', 'Invalid request method. Only POST is allowed.', null);
    }

    // Read JSON input from body
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    if (json_last_error() !== JSON_ERROR_NONE || !isset($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        send_json_response('error', 'Invalid or missing email in request body. Provide valid JSON: { "email": "user@example.com" }', null);
    }

    $email = trim($data['email']);

    // Find user by email
    $stmt = $conn->prepare("
        SELECT id, email_confirmed
        FROM loginusers
        WHERE email = ?
        LIMIT 1
    ");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $res = $stmt->get_result();
    $user = $res->fetch_assoc();

    if (!$user) {
        send_json_response('error', 'No user found with this email.', null);
    }

    // Already verified
    if ((int)$user['email_confirmed'] === 1) {
        send_json_response('success', 'Email is already verified.', ['user_id' => $user['id']]);
    }

    // Verify now and clear token
    $uid = (int)$user['id'];
    $upd = $conn->prepare("
        UPDATE loginusers
        SET email_confirmed = 1, emailToken = NULL
        WHERE id = ?
        LIMIT 1
    ");
    $upd->bind_param("i", $uid);
    $upd->execute();

    send_json_response('success', 'Email verified successfully.', ['user_id' => $user['id']]);

} catch (Throwable $e) {
    error_log("VERIFY_API_FATAL: " . $e->getMessage());
    send_json_response('error', 'Server error occurred. Please try again later or contact support.', null);
}
