<?php
require_once 'config/db.php';

function addColumnIfNotExists($conn, $table, $column, $definition) {
    $check = $conn->query("SHOW COLUMNS FROM $table LIKE '$column'");
    if ($check->num_rows == 0) {
        $sql = "ALTER TABLE $table ADD COLUMN $column $definition";
        if ($conn->query($sql)) {
            echo "<p>Added column <strong>$column</strong> to <strong>$table</strong>.</p>";
        } else {
            echo "<p style='color:red'>Error adding $column to $table: " . $conn->error . "</p>";
        }
    } else {
        echo "<p>Column <strong>$column</strong> already exists in <strong>$table</strong>.</p>";
    }
}

function dropColumnIfExists($conn, $table, $column) {
    $check = $conn->query("SHOW COLUMNS FROM $table LIKE '$column'");
    if ($check->num_rows > 0) {
        $conn->query("ALTER TABLE $table DROP COLUMN $column");
        echo "<p>Dropped column <strong>$column</strong> from <strong>$table</strong>.</p>";
    }
}

echo "<h2>Database Schema Update</h2>";

// 1. user_templates
addColumnIfNotExists($conn, 'user_templates', 'greeting_text', 'TEXT');

// 2. user_apis
dropColumnIfExists($conn, 'user_apis', 'wa_instance_id');
dropColumnIfExists($conn, 'user_apis', 'wa_token');

addColumnIfNotExists($conn, 'user_apis', 'wa_apikey', 'VARCHAR(255) AFTER wa_url');
addColumnIfNotExists($conn, 'user_apis', 'sms_user', 'VARCHAR(100)');
addColumnIfNotExists($conn, 'user_apis', 'sms_password', 'VARCHAR(100)');
addColumnIfNotExists($conn, 'user_apis', 'sms_sender_id', 'VARCHAR(20)');

echo "<h3>Done. Try adding user again.</h3>";
echo '<a href="index.php?page=admin&action=add_user">Back to Add User</a>';
?>
