<?php
/**
 * One-time migration script for XtraLogTools integration.
 * Visit this page once as admin, then delete it.
 */
if (session_status() === PHP_SESSION_NONE) session_start();
require_once dirname(__DIR__) . '/include/config.php';

// Basic admin check
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    die('Not logged in.');
}
$adm = $pdo->query("SELECT is_admin FROM users WHERE id=" . (int)$_SESSION['user_id'])->fetch();
if (!$adm || !$adm['is_admin']) die('Not admin.');

$results = [];

// 1. Add settings columns
try {
    $pdo->exec("ALTER TABLE settings
        ADD COLUMN IF NOT EXISTS xtralogtools_api_key  VARCHAR(255) NOT NULL DEFAULT '',
        ADD COLUMN IF NOT EXISTS xtralogtools_api_url  VARCHAR(255) NOT NULL DEFAULT 'https://xtralogtools.com/api/v1/logs.php',
        ADD COLUMN IF NOT EXISTS xtralogtools_enabled  TINYINT(1)   NOT NULL DEFAULT 0,
        ADD COLUMN IF NOT EXISTS xtralogtools_markup   DECIMAL(6,2) NOT NULL DEFAULT 10.00");
    $results[] = ['ok', 'Settings columns added (or already exist).'];
} catch (PDOException $e) {
    $results[] = ['err', 'Settings columns: ' . $e->getMessage()];
}

// 2. Create xtralog_products
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS xtralog_products (
        id           INT AUTO_INCREMENT PRIMARY KEY,
        product_id   VARCHAR(100) NOT NULL UNIQUE,
        product_name VARCHAR(255) NOT NULL,
        description  TEXT,
        server       TINYINT(1)   NOT NULL DEFAULT 1,
        api_price    DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        our_price    DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        category     VARCHAR(100) NOT NULL DEFAULT '',
        status       TINYINT(1)   NOT NULL DEFAULT 1,
        synced_at    TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        KEY idx_status   (status),
        KEY idx_category (category)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    $results[] = ['ok', 'xtralog_products table created (or already exists).'];
} catch (PDOException $e) {
    $results[] = ['err', 'xtralog_products: ' . $e->getMessage()];
}

// 3. Create xtralog_orders
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS xtralog_orders (
        id           INT AUTO_INCREMENT PRIMARY KEY,
        user_id      INT           NOT NULL,
        product_id   VARCHAR(100)  NOT NULL,
        product_name VARCHAR(255)  NOT NULL,
        server       TINYINT(1)    NOT NULL DEFAULT 1,
        quantity     INT           NOT NULL DEFAULT 1,
        unit_price   DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        total_charge DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        order_ref    VARCHAR(100)  NOT NULL UNIQUE,
        api_response TEXT,
        logs_data    LONGTEXT,
        status       ENUM('pending','completed','failed') NOT NULL DEFAULT 'pending',
        created_at   TIMESTAMP     NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at   TIMESTAMP     NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        KEY idx_user_id  (user_id),
        KEY idx_status   (status),
        KEY idx_product  (product_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    $results[] = ['ok', 'xtralog_orders table created (or already exists).'];
} catch (PDOException $e) {
    $results[] = ['err', 'xtralog_orders: ' . $e->getMessage()];
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>XtraLogTools Migration</title>
  <style>
    body { font-family: monospace; padding: 30px; background: #f8f9fa; }
    .ok  { color: #198754; }
    .err { color: #dc3545; }
    li   { margin: 6px 0; font-size: 14px; }
    h2   { color: #4D148C; }
    .done { background: #d1e7dd; border: 1px solid #a3cfbb; border-radius: 8px; padding: 14px 18px; margin-top: 20px; }
  </style>
</head>
<body>
  <h2>XtraLogTools Migration</h2>
  <ul>
    <?php foreach ($results as [$type, $msg]): ?>
    <li class="<?php echo $type; ?>">
      <?php echo $type === 'ok' ? '✅' : '❌'; ?> <?php echo htmlspecialchars($msg); ?>
    </li>
    <?php endforeach; ?>
  </ul>
  <div class="done">
    <strong>Migration complete.</strong><br>
    You can now <a href="logs-api-settings.php">go to Logs API Settings</a> to configure your XtraLogTools API key.<br><br>
    <strong style="color:#dc3545;">⚠️ Delete this file after running it:</strong>
    <code>admin/run-xtralogtools-migration.php</code>
  </div>
</body>
</html>
