<?php
if (!defined('ABSPATH')) exit;
add_action('rest_api_init', function () {
    register_rest_route('dripbox/v1', '/verify-license', [
        'methods'  => 'POST',
        'callback' => 'dripbox_verify_license',
        'permission_callback' => '__return_true'
    ]);
});

function dripbox_verify_license(WP_REST_Request $req) {
    global $wpdb;

    $email   = sanitize_email($req->get_param('email'));
    $key     = sanitize_text_field($req->get_param('license'));
    $domain  = sanitize_text_field($req->get_param('domain'));

    $table = $wpdb->prefix . 'dripbox_licenses';

    $row = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$table} WHERE license_key = %s",
        $key
    ));

    if (!$row) {
        return ['valid' => false, 'reason' => 'not_found'];
    }

    if ($row->email !== $email) {
        return ['valid' => false, 'reason' => 'email_mismatch'];
    }

    if ($row->status !== 'active') {
        return ['valid' => false, 'reason' => 'inactive'];
    }

    if ($row->expires_at && strtotime($row->expires_at) < time()) {
        return ['valid' => false, 'reason' => 'expired'];
    }

    // Primeira ativação: associa domínio
    if (!$row->domain) {
        $wpdb->update($table, ['domain' => $domain], ['id' => $row->id]);
        return ['valid' => true];
    }

    // Segunda ativação em domínio diferente: bloqueia
    if ($row->domain !== $domain) {
        return ['valid' => false, 'reason' => 'domain_mismatch'];
    }

    return ['valid' => true];
}
