<?php
/**
 * shipping/debug.php
 * Script de diagnóstico — BORRAR después de resolver el problema
 * Acceder via: https://api.sistemarrb.com/shipping/debug.php
 */

header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

$results = [];

// ── 1. Verificar extensiones PHP ──────────────────────────────────────────────
$results['php_version']    = PHP_VERSION;
$results['curl_available'] = function_exists('curl_init') ? 'SI' : 'NO';
$results['json_available'] = function_exists('json_encode') ? 'SI' : 'NO';
$results['mysqli_available'] = class_exists('mysqli') ? 'SI' : 'NO';

// ── 2. Verificar config.php ───────────────────────────────────────────────────
$configPath = __DIR__ . '/../config.php';
$results['config_exists'] = file_exists($configPath) ? 'SI' : 'NO';

if (file_exists($configPath)) {
    require_once $configPath;
    $results['DB_HOST_defined'] = defined('DB_HOST') ? 'SI (' . DB_HOST . ')' : 'NO';
    $results['DB_NAME_defined'] = defined('DB_NAME') ? 'SI (' . DB_NAME . ')' : 'NO';

    // ── 3. Conectar a BD ──────────────────────────────────────────────────────
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        $results['db_connect'] = 'ERROR: ' . $conn->connect_error;
    } else {
        $results['db_connect'] = 'OK';
        $conn->set_charset('utf8');

        // ── 4. Verificar tabla configuracion ─────────────────────────────────
        $r = $conn->query("SHOW TABLES LIKE 'configuracion'");
        $results['tabla_configuracion'] = ($r && $r->num_rows > 0) ? 'EXISTE' : 'NO EXISTE';

        if ($r && $r->num_rows > 0) {
            // Verificar columnas
            $cols = $conn->query("DESCRIBE configuracion");
            $colNames = [];
            while ($row = $cols->fetch_assoc()) {
                $colNames[] = $row['Field'] . ' (' . $row['Type'] . ')';
            }
            $results['columnas_configuracion'] = implode(', ', $colNames);

            // Intentar INSERT de prueba
            $testVal = json_encode(['test' => true, 'ts' => time()]);
            $testVal = $conn->real_escape_string($testVal);
            $conn->query("INSERT INTO configuracion (clave, valor, actualizado)
                          VALUES ('debug_test', '$testVal', NOW())
                          ON DUPLICATE KEY UPDATE valor = '$testVal', actualizado = NOW()");
            if ($conn->error) {
                $results['insert_test'] = 'ERROR: ' . $conn->error;
            } else {
                $results['insert_test'] = 'OK (affected: ' . $conn->affected_rows . ')';
            }

            // Leer lo que se insertó
            $r2 = $conn->query("SELECT * FROM configuracion WHERE clave = 'debug_test' LIMIT 1");
            if ($r2 && $r2->num_rows > 0) {
                $results['select_test'] = 'OK: ' . json_encode($r2->fetch_assoc());
            } else {
                $results['select_test'] = 'NO SE ENCONTRÓ EL REGISTRO';
            }
        }

        // ── 5. Verificar tabla inversionista ─────────────────────────────────
        $r3 = $conn->query("SHOW TABLES LIKE 'inversionista'");
        $results['tabla_inversionista'] = ($r3 && $r3->num_rows > 0) ? 'EXISTE' : 'NO EXISTE';
        if ($r3 && $r3->num_rows > 0) {
            $cols2 = $conn->query("DESCRIBE inversionista");
            $colNames2 = [];
            while ($row2 = $cols2->fetch_assoc()) {
                $colNames2[] = $row2['Field'] . ' (' . $row2['Type'] . ')';
            }
            $results['columnas_inversionista'] = implode(', ', $colNames2);
        }

        $conn->close();
    }
}

// ── 6. Probar cURL a Skydropx ─────────────────────────────────────────────────
if (function_exists('curl_init')) {
    $ch = curl_init('https://pro.skydropx.com/api/v1/oauth/token');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode([
            'client_id'     => 'QsgcphLaKKrD3G-qKyMLvIG7EJD1mcJBL5J0o_jX_Cs',
            'client_secret' => 'DpY8SEx925sqxt78DCIqrYpwhBtiqBDRdk0bNSKRD1M',
            'grant_type'    => 'client_credentials',
            'redirect_uri'  => 'urn:ietf:wg:oauth:2.0:oob',
            'scope'         => 'default orders.create',
        ]),
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $resp     = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr  = curl_error($ch);
    curl_close($ch);

    if ($curlErr) {
        $results['skydropx_oauth'] = 'cURL ERROR: ' . $curlErr;
    } elseif ($httpCode === 200) {
        $tokenData = json_decode($resp, true);
        $results['skydropx_oauth'] = 'OK HTTP 200 — token: ' . substr($tokenData['access_token'] ?? '', 0, 20) . '...';
    } else {
        $results['skydropx_oauth'] = "HTTP $httpCode: $resp";
    }
} else {
    $results['skydropx_oauth'] = 'cURL no disponible';
}

// ── 7. Verificar permisos de escritura en carpeta shipping/ ──────────────────
$results['shipping_writable'] = is_writable(__DIR__) ? 'SI' : 'NO';
$results['log_file_writable']  = is_writable(__DIR__ . '/create_log.txt') ? 'SI' : 'NO (o no existe)';

echo json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
