<?php

namespace Formatrica\Setup;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use wpdb;

final class Activator
{
    public function activate(): void
    {
        $this->maybe_create_tables();
        $this->secure_uploads_dir();

        // Initialize or update database schema version
        $schema_manager = new Schema_Manager();
        $schema_manager->run_migrations();

        // Note: We no longer need to flush rewrite rules since we're not using Custom Post Types
    }

    private function maybe_create_tables(): void
    {
        global $wpdb;
        $charset = $wpdb->get_charset_collate();

        // Forms table
        $forms_table = $wpdb->prefix . 'formatrica_forms';
        $sql_forms = "CREATE TABLE IF NOT EXISTS {$forms_table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            title varchar(255) NOT NULL DEFAULT '',
            fields longtext NOT NULL,
            settings longtext NOT NULL,
            active tinyint(1) NOT NULL DEFAULT 1,
            created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY active (active),
            KEY created_at (created_at)
        ) {$charset};";

        // Submissions table
        $submissions_table = $wpdb->prefix . 'formatrica_submissions';
        $sql_submissions = "CREATE TABLE IF NOT EXISTS {$submissions_table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            form_id bigint(20) unsigned NOT NULL,
            submission_uuid varchar(36) NOT NULL,
            data longtext NOT NULL,
            status varchar(20) NOT NULL DEFAULT 'new',
            ip_address varchar(45) DEFAULT NULL,
            user_agent text DEFAULT NULL,
            created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY form_id (form_id),
            KEY submission_uuid (submission_uuid)
        ) {$charset};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql_forms);
        dbDelta($sql_submissions);

        // Pro tables (drafts, rate buckets, payments) are owned by the Pro
        // package and created by Pro\Setup\Pro_Activator when Pro boots. A Free
        // activation must never create them (docs/wporg-free-runtime-separation.md).
    }

    private function secure_uploads_dir(): void
    {
        $uploads = wp_upload_dir();
        if (!empty($uploads['error'])) {
            return;
        }

        $dir = trailingslashit($uploads['basedir']) . 'formatrica';
        wp_mkdir_p($dir);

        $htaccess = "Options -Indexes\n<FilesMatch \"\\.(php|phtml|phar|php\\d?)$\">\n    Require all denied\n</FilesMatch>\n";

        $htaccess_file = trailingslashit($dir) . '.htaccess';
        $index_file = trailingslashit($dir) . 'index.html';

        if (false === file_put_contents($htaccess_file, $htaccess)) {
            do_action('formatrica_debug_log', 'Failed to create .htaccess protection file at ' . $htaccess_file);
        }

        if (false === file_put_contents($index_file, '')) {
            do_action('formatrica_debug_log', 'Failed to create index.html protection file at ' . $index_file);
        }
    }
}
