<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, access-token');

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

require_once __DIR__ . '/plugin_config.php';
require_once __DIR__ . '/../include/config.php';

function wisender_get_header($name) {
    $key = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
    if (isset($_SERVER[$key])) return $_SERVER[$key];

    // Fallback for some servers
    if (function_exists('getallheaders')) {
        $headers = getallheaders();
        foreach ($headers as $k => $v) {
            if (strtolower($k) === strtolower($name)) return $v;
        }
    }
    return null;
}

function wisender_require_access_token() {
    $token = wisender_get_header('access-token');
    if (!$token || $token !== WISENDER_PLUGIN_ACCESS_TOKEN) {
        http_response_code(401);
        echo json_encode([
            "success" => false,
            "message" => "Unauthorized",
            "msg_id"  => "unauthorized"
        ]);
        exit;
    }
}

function wisender_db() {
    global $DBCON;
    $conn = new mysqli($DBCON['host'], $DBCON['user'], $DBCON['pass'], $DBCON['name']);
    if ($conn->connect_error) {
        http_response_code(500);
        echo json_encode([
            "success" => false,
            "message" => "Database connection failed",
            "msg_id"  => "db_connection_error"
        ]);
        exit;
    }
    $conn->set_charset('utf8mb4');
    return $conn;
}

function wisender_json() {
    $raw = file_get_contents("php://input");
    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
}

function wisender_user_status($row) {
    // Extension considers premium only when user_status === "active".
    // Your current panel blocks expired plans at login anyway.
    return "active";
}

function wisender_build_user($row, $token) {
    $name = isset($row['customer_name']) ? $row['customer_name'] : (isset($row['name']) ? $row['name'] : '');
    $whats = isset($row['whatsapp_number']) ? $row['whatsapp_number'] : '';
    $uid = isset($row['user_id']) && $row['user_id'] !== '' ? $row['user_id'] : (string)($row['id'] ?? '');

    return [
        "user_id"             => $uid,
        "name"                => $name,
        "email"               => $row['email'] ?? '',
        "wl_id"               => "",
        "bearer_token"        => $token,
        "access_token_plugin" => $token,

        // Optional fields used around the extension UI:
        "user_premium"        => 1,
        "dataCadastro"        => $row['created_at'] ?? date('Y-m-d'),
        "whatsapp_registro"   => $whats,
        "whatsapp_plugin"     => $whats,
        "path"                => "",
        "afiliado"            => "",
        "campanhaID"          => "",
        "cookies"             => [
            "_fbc" => "",
            "_fbp" => "",
            "_ga" => "",
            "_ttclid" => "",
            "_ttp" => ""
        ]
    ];
}

function wisender_plan_is_valid($row) {
    $today = date('Y-m-d');
    $expiry = $row['plan_expiry_date'] ?? '';
    if ($expiry === '') return false;
    return $expiry >= $today;
}

function wisender_is_enabled($row) {
    // Adjust if you use other columns to disable users.
    // In your schema: status enum('true','false'), archive enum('true','false'), deleted_key yes/no.
    if (isset($row['status']) && $row['status'] === 'false') return false;
    if (isset($row['archive']) && $row['archive'] === 'true') return false;
    if (isset($row['deleted_key']) && $row['deleted_key'] === 'yes') return false;
    return true;
}
?>
