<?php
// Set content type to application/json
header('Content-Type: application/json');

// Allow cross-origin requests - adjust in production if needed
// For development, '*' is often fine. For production, you might want to restrict this
// to specific domains or your widget serving domain if it's different.
header('Access-Control-Allow-Origin: *'); // In production, replace * with your specific domain
header('Access-Control-Allow-Methods: GET, OPTIONS'); // Allow GET and OPTIONS (for preflight)
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight OPTIONS request (for CORS)
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

require_once __DIR__ . '/../../config/db_connect.php'; // Database connection

$response = ['status' => 'inactive', 'message' => 'Widget not authorized: Unknown reason.'];

// Input retrieval
$widget_id_from_request = trim($_GET['widget_id'] ?? '');
$domain_from_request = trim($_GET['domain'] ?? '');

// Input validation
if (empty($widget_id_from_request)) {
    $response['message'] = 'Widget not authorized: Missing widget ID.';
    echo json_encode($response);
    exit();
}
if (empty($domain_from_request)) {
    $response['message'] = 'Widget not authorized: Missing domain information.';
    echo json_encode($response);
    exit();
}

// Basic format validation (can be enhanced)
if (strlen($widget_id_from_request) !== 32 || !ctype_xdigit($widget_id_from_request)) { // Assuming 32-char hex
    $response['message'] = 'Widget not authorized: Invalid widget ID format.';
    echo json_encode($response);
    exit();
}
// A simple check for domain - can be more robust
if (strlen($domain_from_request) > 255 || !preg_match('/^[a-z0-9.-]+$/i', str_replace('www.', '', $domain_from_request))) {
    $response['message'] = 'Widget not authorized: Invalid domain format.';
    echo json_encode($response);
    exit();
}

// Enhanced query to check expiry in real-time
$stmt = $mysqli->prepare("
    SELECT domain_name, subscription_status, plan_type, subscription_end_date 
    FROM websites 
    WHERE widget_id = ?
");

if (!$stmt) {
    error_log("Validate_widget: DB prepare error: " . $mysqli->error);
    $response['message'] = 'Widget not authorized: Server error (DBP).';
    echo json_encode($response);
    exit();
}

$stmt->bind_param("s", $widget_id_from_request);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
    $website_data = $result->fetch_assoc();
    $db_domain_name = $website_data['domain_name'];
    $db_subscription_status = $website_data['subscription_status'];
    $plan_type = $website_data['plan_type'];
    $subscription_end_date = $website_data['subscription_end_date'];

    // Domain comparison
    $normalized_request_domain = strtolower(preg_replace('/^www\./i', '', $domain_from_request));
    $normalized_db_domain = strtolower(preg_replace('/^www\./i', '', $db_domain_name));

    if ($normalized_request_domain === $normalized_db_domain) {
        // Check if subscription is active
        if ($db_subscription_status === 'active') {
            // Additional check for expiry (in case cron job hasn't run yet)
            if ($plan_type === 'lifetime' || $subscription_end_date === null) {
                // Lifetime or no expiry
                $response['status'] = 'active';
                $response['message'] = 'Widget is authorized.';
            } elseif ($subscription_end_date && strtotime($subscription_end_date) > time()) {
                // Not expired yet
                $response['status'] = 'active';
                $response['message'] = 'Widget is authorized.';
            } else {
                // Expired - should be caught by cron job, but handle gracefully
                $response['message'] = 'Widget not authorized: Subscription expired.';
                
                // Optionally auto-deactivate here (though cron job should handle this)
                $update_stmt = $mysqli->prepare("UPDATE websites SET subscription_status = 'inactive' WHERE widget_id = ?");
                if ($update_stmt) {
                    $update_stmt->bind_param("s", $widget_id_from_request);
                    $update_stmt->execute();
                    $update_stmt->close();
                }
            }
        } else {
            $response['message'] = 'Widget not authorized: Subscription inactive (' . $db_subscription_status . ').';
        }
    } else {
        $response['message'] = 'Widget not authorized: Domain mismatch.';
    }
} else {
    $response['message'] = 'Widget not authorized: Widget ID not found.';
}

$stmt->close();
$mysqli->close();

echo json_encode($response);
exit();
?>
