<?php
/**
 * Simple database check
 */

// Include WordPress
require_once dirname(__FILE__) . '/../../../../wp-load.php';

echo '<h1>Database Check</h1>';

global $wpdb;
$table_name = $wpdb->prefix . 'pc_hfap_snippets';

echo '<p>Table name: ' . $table_name . '</p>';

// Check if table exists
$table_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table_name));

if ($table_name === $table_exists) {
    echo '<p style="color: green;">✓ Table exists!</p>';
    
    // Count snippets
    $count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
    echo '<p>Total snippets: ' . $count . '</p>';
    
    // Try to insert a test snippet
    $result = $wpdb->insert(
        $table_name,
        array(
            'title' => 'Database Test ' . date('Y-m-d H:i:s'),
            'location' => 'header',
            'code' => '<!-- Test -->'
        ),
        array('%s', '%s', '%s')
    );
    
    if ($result) {
        echo '<p style="color: green;">✓ Insert successful! ID: ' . $wpdb->insert_id . '</p>';
        
        // Delete the test
        $wpdb->query("DELETE FROM $table_name WHERE title LIKE 'Database Test%'");
        echo '<p style="color: green;">✓ Test snippet deleted</p>';
    } else {
        echo '<p style="color: red;">✗ Insert failed!</p>';
        echo '<p>Error: ' . $wpdb->last_error . '</p>';
    }
} else {
    echo '<p style="color: red;">✗ Table does not exist!</p>';
    echo '<p>Attempting to create table...</p>';
    
    // Create table
    $charset_collate = $wpdb->get_charset_collate();
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        title varchar(255) NOT NULL,
        location enum('header','footer','body') NOT NULL DEFAULT 'header',
        code longtext NOT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    ) $charset_collate;";
    
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta($sql);
    
    // Check again
    $table_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table_name));
    
    if ($table_name === $table_exists) {
        echo '<p style="color: green;">✓ Table created successfully!</p>';
    } else {
        echo '<p style="color: red;">✗ Failed to create table!</p>';
        echo '<p>Error: ' . $wpdb->last_error . '</p>';
    }
}

echo '<h2>Database Variables</h2>';
echo '<p>DB Host: ' . DB_HOST . '</p>';
echo '<p>DB Name: ' . DB_NAME . '</p>';
echo '<p>Table Prefix: ' . $wpdb->prefix . '</p>';
