<?php
// OneLauncher - api.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, X-Requested-With');

// Responde preflight CORS imediatamente
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once 'db.php';

$action = $_GET['action'] ?? '';


if ($action == 'get_launcher_config') {
    $device_id = $_GET['device_id'] ?? '';
    $theme_id = 1;
    $message_title = '';
    $message_body = '';

    $autoplay_package = '';

    if (!empty($device_id)) {
        $stmt_dev = $conn->prepare("SELECT theme_id, message_title, message_body, autoplay_package FROM devices WHERE device_id = ?");
        $stmt_dev->bind_param("s", $device_id);
        $stmt_dev->execute();
        $res_dev = $stmt_dev->get_result();
        if ($dev = $res_dev->fetch_assoc()) {
            if ((int)$dev['theme_id'] > 0) {
                $theme_id = (int)$dev['theme_id'];
            }
            $message_title = $dev['message_title'] ?? '';
            $message_body = $dev['message_body'] ?? '';
            $autoplay_package = $dev['autoplay_package'] ?? '';
        }
    }

    // 1. Configurações Globais
    $resConfig = $conn->query("SELECT * FROM config WHERE theme_id = $theme_id LIMIT 1");
    $config = $resConfig->fetch_assoc();
    if (!$config) {
        $resConfig = $conn->query("SELECT * FROM config WHERE theme_id = 1 LIMIT 1");
        $config = $resConfig->fetch_assoc();
    }

    // Obter suporte padrão caso esteja vazio
    if (empty($config['support_whatsapp'])) {
        $resDefSup = $conn->query("SELECT support_whatsapp FROM config WHERE theme_id = 1 LIMIT 1");
        if ($resDefSup && $rowDefSup = $resDefSup->fetch_assoc()) {
            $config['support_whatsapp'] = $rowDefSup['support_whatsapp'] ?? '';
        }
    }

    // 2. Imagens de Propaganda
    $resPropaganda = $conn->query("SELECT image_url FROM propaganda WHERE (active IS NULL OR active = 1) AND (theme_id = $theme_id OR theme_id = 1) ORDER BY item_order ASC");
    $propaganda = [];
    if ($resPropaganda && is_object($resPropaganda)) {
        while ($row = $resPropaganda->fetch_assoc()) {
            $propaganda[] = $row['image_url'];
        }
    }

    // Botões Verticais (Garantir 3) com APK URL se for direct_install
    $sqlBtn = "SELECT b.*, s.apk_url as direct_apk_url, s.name as direct_app_name 
               FROM vertical_buttons b 
               LEFT JOIN app_store s ON b.package_name = s.package_name AND s.theme_id = b.theme_id 
               WHERE b.theme_id = $theme_id
               ORDER BY b.button_index ASC LIMIT 3";
    $res = $conn->query($sqlBtn);
    $buttons = [];
    while ($row = $res->fetch_assoc()) {
        $buttons[] = [
            "index" => (int)$row['button_index'],
            "label" => $row['label'],
            "icon" => $row['icon_url'],
            "package_name" => $row['package_name'],
            "action_type" => $row['action_type'],
            "apk_url" => $row['direct_apk_url'] ?? '',
            "app_name" => $row['direct_app_name'] ?? ''
        ];
    }

    // App Store
    $res = $conn->query("SELECT * FROM app_store WHERE theme_id = $theme_id ORDER BY item_order ASC");
    $app_store = [];
    while ($row = $res->fetch_assoc()) {
        $app_store[] = [
            "id" => (int)$row['id'],
            "name" => $row['name'],
            "package_name" => $row['package_name'],
            "icon" => $row['icon_url'],
            "apk_url" => $row['apk_url'],
            "version" => $row['version']
        ];
    }

    // 4. Grade de Apps (Bottom)
    $resApps = $conn->query("SELECT * FROM launcher_apps WHERE theme_id = $theme_id ORDER BY item_order ASC");
    $apps = [];
    while ($row = $resApps->fetch_assoc()) {
        $apps[] = [
            "name" => $row['app_name'],
            "package" => $row['package_name'],
            "icon" => $row['icon_url'],
            "apk_url" => $row['apk_url'] ?? ''
        ];
    }

    // 5. Configurações de Layout
    $resLayout = $conn->query("SELECT component_name, margin_top, margin_left, margin_right, margin_bottom, width_weight, height_weight, item_width, item_height, corner_radius, spacing, x, y, width, height, visible FROM layout_settings WHERE theme_id = $theme_id");
    $layout = [];
    while ($row = $resLayout->fetch_assoc()) {
        $layout[$row['component_name']] = [
            "margin_top" => (int)$row['margin_top'],
            "margin_left" => (int)$row['margin_left'],
            "margin_right" => (int)$row['margin_right'],
            "margin_bottom" => (int)$row['margin_bottom'],
            "width_weight" => (float)$row['width_weight'],
            "height_weight" => (float)$row['height_weight'],
            "item_width" => (int)$row['item_width'],
            "item_height" => (int)$row['item_height'],
            "corner_radius" => (int)$row['corner_radius'],
            "spacing" => (int)$row['spacing'],
            "x" => isset($row['x']) ? (float)$row['x'] : 0.0,
            "y" => isset($row['y']) ? (float)$row['y'] : 0.0,
            "width" => isset($row['width']) ? (float)$row['width'] : 0.0,
            "height" => isset($row['height']) ? (float)$row['height'] : 0.0,
            "visible" => isset($row['visible']) ? (bool)(int)$row['visible'] : true
        ];
    }

    $response = [
        "status" => "success",
        "config" => [
            "app_name" => $config['app_name'],
            "logo" => $config['app_logo'],
            "background" => $config['app_background'],
            "primary_color" => $config['primary_color'],
            "version_code" => (int)$config['update_version_code'],
            "version_name" => $config['update_version_name'] ?? '1.0.0',
            "apk_url" => $config['update_apk_url'],
            "custom_layout_enabled" => (bool)$config['custom_layout_enabled'],
            "tech_password" => $config['tech_password'] ?? '',
            "logo_size" => (int)($config['logo_size'] ?? 95),
            "app_icon_full" => (bool)($config['app_icon_full'] ?? 0),
            "support_whatsapp" => $config['support_whatsapp'] ?? '',
            "autoplay_package" => $autoplay_package,
            "show_banner" => (bool)($config['show_banner'] ?? 1)
        ],
        "propaganda" => $propaganda,
        "vertical_buttons" => $buttons,
        "app_grid" => $apps,
        "app_store" => $app_store,
        "layout" => $layout,
        "message" => [
            "title" => $message_title,
            "body" => $message_body
        ]
    ];
    
    echo json_encode($response);
    exit;
}

if ($action == 'check_device') {
    $device_id = $_GET['device_id'] ?? '';
    if (empty($device_id)) {
        echo json_encode(["status" => "error", "message" => "Device ID ausente"]);
        exit;
    }

    $stmt = $conn->prepare("SELECT * FROM devices WHERE device_id = ? LIMIT 1");
    $stmt->bind_param("s", $device_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $device = $res->fetch_assoc();

    if (!$device) {
        // Auto-registro como inativo por padrão
        $stmt_ins = $conn->prepare("INSERT INTO devices (device_id, active, note) VALUES (?, 0, 'Auto-registrado')");
        $stmt_ins->bind_param("s", $device_id);
        $stmt_ins->execute();
        echo json_encode([
            "status" => "blocked",
            "message" => "Dispositivo não autorizado. Entre em contato com o suporte.",
            "device_id" => $device_id
        ]);
        exit;
    }

    // Verificar se está ativo e se não expirou
    $is_active = (int)$device['active'];
    $expiration = $device['expiration_date'];
    $now = date('Y-m-d H:i:s');

    $blocked = false;
    $msg = "";

    if (!$is_active) {
        $blocked = true;
        $msg = "Acesso desativado pelo administrador.";
    } elseif ($expiration && $expiration < $now) {
        $blocked = true;
        $msg = "Seu acesso expirou em " . date('d/m/Y', strtotime($expiration)) . ".";
    }

    // - Atualiza o último check
    $stmt_upd = $conn->prepare("UPDATE devices SET last_check = ? WHERE device_id = ?");
    $stmt_upd->bind_param("ss", $now, $device_id);
    $stmt_upd->execute();

    $response = [
        "status" => $blocked ? "blocked" : "authorized",
        "message" => $msg,
        "expiration" => $expiration ? date('d/m/Y', strtotime($expiration)) : "Vitalício",
        "device_id" => $device_id
    ];

    // Se estiver bloqueado, envia a lista de planos para o usuário escolher
    if ($blocked) {
        $resPlans = $conn->query("SELECT * FROM plans WHERE active = 1 ORDER BY price ASC");
        $plans = [];
        while ($p = $resPlans->fetch_assoc()) {
            $plans[] = [
                "id" => (int)$p['id'],
                "name" => $p['name'],
                "days" => (int)$p['duration_days'],
                "price" => (float)$p['price']
            ];
        }
        $response['plans'] = $plans;
    }

    echo json_encode($response);
    exit;
}

if ($action == 'get_plans') {
    $res = $conn->query("SELECT * FROM plans WHERE active = 1 ORDER BY price ASC");
    $plans = [];
    while ($row = $res->fetch_assoc()) {
        $plans[] = [
            "id" => (int)$row['id'],
            "name" => $row['name'],
            "days" => (int)$row['duration_days'],
            "price" => (float)$row['price']
        ];
    }
    echo json_encode(["status" => "success", "plans" => $plans]);
    exit;
}

if ($action == 'generate_pix') {
    $device_id = $_GET['device_id'] ?? '';
    $plan_id = (int)($_GET['plan_id'] ?? 0);

    if (empty($device_id) || $plan_id <= 0) {
        echo json_encode(["status" => "error", "message" => "Dados inválidos"]);
        exit;
    }

    // 1. Obter Token do MP e dados do plano
    $resConfig = $conn->query("SELECT mercado_pago_token FROM config WHERE theme_id = 1 LIMIT 1");
    $config = $resConfig->fetch_assoc();
    $mp_token = $config['mercado_pago_token'] ?? '';

    if (empty($mp_token)) {
        echo json_encode(["status" => "error", "message" => "Pagamento automático não configurado pelo administrador."]);
        exit;
    }

    $stmtPlan = $conn->prepare("SELECT * FROM plans WHERE id = ? LIMIT 1");
    $stmtPlan->bind_param("i", $plan_id);
    $stmtPlan->execute();
    $resPlan = $stmtPlan->get_result();
    $plan = $resPlan->fetch_assoc();
    if (!$plan) {
        echo json_encode(["status" => "error", "message" => "Plano inválido"]);
        exit;
    }

    $external_ref = "pix_" . $device_id . "_" . $plan_id . "_" . time();
    $amount = (float)$plan['price'];
    $description = "Assinatura " . $plan['name'] . " - OneLauncher";

    // 2. Chamar API Pix do Mercado Pago via cURL
    $url = "https://api.mercadopago.com/v1/payments";
    $headers = [
        "Authorization: Bearer $mp_token",
        "X-Idempotency-Key: $external_ref",
        "Content-Type: application/json"
    ];

    $payload = [
        "transaction_amount" => $amount,
        "description" => $description,
        "payment_method_id" => "pix",
        "external_reference" => $external_ref,
        "payer" => [
            "email" => "cliente_pay@onelauncher.top",
            "first_name" => "Cliente",
            "last_name" => "OneLauncher",
            "identification" => [
                "type" => "CPF",
                "number" => "12345678909"
            ]
        ]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    $response_mp = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $json_mp = json_decode($response_mp, true);

    if ($http_code >= 200 && $http_code < 300 && isset($json_mp['id'])) {
        $payment_id = $json_mp['id'];
        $qr_code = $json_mp['point_of_interaction']['transaction_data']['qr_code'] ?? '';
        $qr_code_base64 = $json_mp['point_of_interaction']['transaction_data']['qr_code_base64'] ?? '';

        // Salvar no banco
        $stmtPay = $conn->prepare("INSERT INTO payments (device_id, plan_id, external_reference, payment_id, status, qr_code, qr_code_base64, amount) VALUES (?, ?, ?, ?, 'pending', ?, ?, ?)");
        $stmtPay->bind_param("sissssd", $device_id, $plan_id, $external_ref, $payment_id, $qr_code, $qr_code_base64, $amount);
        $stmtPay->execute();

        echo json_encode([
            "status" => "success",
            "payment_id" => $payment_id,
            "qr_code" => $qr_code,
            "qr_code_base64" => $qr_code_base64,
            "amount" => $amount
        ]);
    } else {
        echo json_encode(["status" => "error", "message" => "Erro MP: " . ($json_mp['message'] ?? 'Erro desconhecido'), "debug_code" => $http_code]);
    }
    exit;
}

if ($action == 'check_payment') {
    $payment_id = $_GET['payment_id'] ?? '';
    if (empty($payment_id)) {
        echo json_encode(["status" => "error", "message" => "Payment ID ausente"]);
        exit;
    }

    $stmtPay = $conn->prepare("SELECT * FROM payments WHERE payment_id = ? LIMIT 1");
    $stmtPay->bind_param("s", $payment_id);
    $stmtPay->execute();
    $res = $stmtPay->get_result();
    $pay = $res->fetch_assoc();

    if (!$pay) {
        echo json_encode(["status" => "error", "message" => "Pagamento não encontrado"]);
        exit;
    }

    if ($pay['status'] == 'approved') {
        echo json_encode(["status" => "approved", "message" => "Pagamento confirmado!"]);
        exit;
    }

    // Opcional: Consultar API do MP para atualizar status se ainda estiver pendente (polling robusto)
    $resConfig = $conn->query("SELECT mercado_pago_token FROM config WHERE theme_id = 1 LIMIT 1");
    $config = $resConfig->fetch_assoc();
    $mp_token = $config['mercado_pago_token'] ?? '';

    $url = "https://api.mercadopago.com/v1/payments/$payment_id";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $mp_token"]);
    $response_mp = curl_exec($ch);
    curl_close($ch);

    $json_mp = json_decode($response_mp, true);
    $new_status = $json_mp['status'] ?? 'pending';

    if ($new_status != $pay['status']) {
        $stmtUpdPay = $conn->prepare("UPDATE payments SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE payment_id = ?");
        $stmtUpdPay->bind_param("ss", $new_status, $payment_id);
        $stmtUpdPay->execute();
        
        if ($new_status == 'approved') {
            // Liberar dispositivo
            $device_id = $pay['device_id'];
            $plan_id = $pay['plan_id'];
            
            $stmtPlan = $conn->prepare("SELECT duration_days FROM plans WHERE id = ? LIMIT 1");
            $stmtPlan->bind_param("i", $plan_id);
            $stmtPlan->execute();
            $resPlan = $stmtPlan->get_result();
            $plan = $resPlan->fetch_assoc();
            $days = $plan['duration_days'];
            
            // Calcular nova data de vencimento
            $stmtDev = $conn->prepare("SELECT expiration_date FROM devices WHERE device_id = ? LIMIT 1");
            $stmtDev->bind_param("s", $device_id);
            $stmtDev->execute();
            $resDev = $stmtDev->get_result();
            $dev = $resDev->fetch_assoc();
            
            $current_exp = $dev['expiration_date'];
            $start_date = ($current_exp && $current_exp > date('Y-m-d H:i:s')) ? $current_exp : date('Y-m-d H:i:s');
            
            $new_exp = date('Y-m-d H:i:s', strtotime("+$days days", strtotime($start_date)));
            
            $stmtUpdDev = $conn->prepare("UPDATE devices SET expiration_date = ?, active = 1 WHERE device_id = ?");
            $stmtUpdDev->bind_param("ss", $new_exp, $device_id);
            $stmtUpdDev->execute();
            
            echo json_encode(["status" => "approved", "message" => "Pagamento confirmado e acesso liberado até $new_exp!"]);
            exit;
        }
    }

    echo json_encode(["status" => $new_status, "message" => "Aguardando pagamento..."]);
    exit;
}

if ($action == 'import_layout') {
    $jsonInput = file_get_contents('php://input');
    $data = json_decode($jsonInput, true);
    
    if (!$data) {
        echo json_encode(["status" => "error", "message" => "JSON inválido"]);
        exit;
    }
    
    $theme_id = (int)($data['theme_id'] ?? 1);
    
    // Autenticação pela senha técnica cadastrada
    $resConfig = $conn->query("SELECT tech_password FROM config WHERE theme_id = 1 LIMIT 1");
    $config = $resConfig->fetch_assoc();
    $current_pass = $config['tech_password'] ?? '8899';
    
    $received_pass = $data['tech_password'] ?? '';
    if ($received_pass !== $current_pass) {
        echo json_encode(["status" => "error", "message" => "Senha técnica inválida ou não autorizada"]);
        exit;
    }
    
    // Atualiza as configurações globais de branding
    $app_name = $data['app_name'] ?? 'OneLauncher';
    $primary_color = $data['theme']['primary_color'] ?? '#00008B';
    $app_logo = $data['theme']['logo_url'] ?? '';
    $app_background = $data['theme']['background_url'] ?? '';
    
    $app_name_esc = str_replace("'", "''", $app_name);
    $primary_color_esc = str_replace("'", "''", $primary_color);
    $app_logo_esc = str_replace("'", "''", $app_logo);
    $app_background_esc = str_replace("'", "''", $app_background);
    
    $conn->query("UPDATE config SET
        app_name = '$app_name_esc',
        primary_color = '$primary_color_esc',
        app_logo = '$app_logo_esc',
        app_background = '$app_background_esc'
        WHERE theme_id = $theme_id");
        
    // Atualiza as dimensões absolutas de cada componente na tabela layout_settings
    if (isset($data['layout']) && is_array($data['layout'])) {
        foreach ($data['layout'] as $component => $bounds) {
            $x = (float)($bounds['x'] ?? 0.0);
            $y = (float)($bounds['y'] ?? 0.0);
            $w = (float)($bounds['width'] ?? 0.0);
            $h = (float)($bounds['height'] ?? 0.0);
            $visible = ($bounds['visible'] ?? true) ? 1 : 0;
            
            $component_esc = str_replace("'", "''", $component);
            
            $conn->query("UPDATE layout_settings SET 
                x = $x, y = $y, width = $w, height = $h, visible = $visible 
                WHERE component_name = '$component_esc' AND theme_id = $theme_id");
        }
    }
    
    echo json_encode(["status" => "success", "message" => "Layout e configurações importados com sucesso!"]);
    exit;
}

echo json_encode(["status" => "error", "message" => "Ação inválida"]);
?>
