<?php
/**
 * Certificate Installer Class
 *
 * Handles the creation and updating of certificate-related database tables.
 *
 * @package HVAC_Community_Events
 * @subpackage Certificates
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Certificate Installer class.
 *
 * Creates and updates database tables for certificate functionality.
 *
 * @since 1.0.0
 */
class HVAC_Certificate_Installer {

    /**
     * The single instance of the class.
     *
     * @var HVAC_Certificate_Installer
     */
    protected static $_instance = null;

    /**
     * Main HVAC_Certificate_Installer Instance.
     *
     * Ensures only one instance of HVAC_Certificate_Installer is loaded or can be loaded.
     *
     * @return HVAC_Certificate_Installer - Main instance.
     */
    public static function instance() {
        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * Current database version.
     *
     * @var string
     */
    private $db_version = '1.0.0';

    /**
     * Create the tables needed for certificates.
     *
     * @return void
     */
    public function create_tables() {
        global $wpdb;

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

        $charset_collate = $wpdb->get_charset_collate();
        $table_name = $wpdb->prefix . 'hvac_certificates';

        // Create the certificates table
        $sql = "CREATE TABLE $table_name (
            certificate_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            event_id BIGINT(20) UNSIGNED NOT NULL,
            attendee_id BIGINT(20) UNSIGNED NOT NULL,
            user_id BIGINT(20) UNSIGNED DEFAULT NULL,
            certificate_number VARCHAR(50) NOT NULL,
            file_path VARCHAR(255) NOT NULL,
            png_path VARCHAR(255) DEFAULT NULL,
            date_generated DATETIME NOT NULL,
            generated_by BIGINT(20) UNSIGNED NOT NULL,
            revoked TINYINT(1) NOT NULL DEFAULT 0,
            revoked_date DATETIME DEFAULT NULL,
            revoked_by BIGINT(20) UNSIGNED DEFAULT NULL,
            revoked_reason TEXT DEFAULT NULL,
            email_sent TINYINT(1) NOT NULL DEFAULT 0,
            email_sent_date DATETIME DEFAULT NULL,
            PRIMARY KEY (certificate_id),
            UNIQUE KEY event_attendee (event_id, attendee_id),
            KEY event_id (event_id),
            KEY attendee_id (attendee_id),
            KEY user_id (user_id),
            KEY certificate_number (certificate_number),
            KEY revoked (revoked)
        ) $charset_collate;";

        dbDelta($sql);

        // Set the version option
        update_option('hvac_certificates_db_version', $this->db_version);
        
        // Create certificate options
        if (false === get_option('hvac_certificate_counter')) {
            add_option('hvac_certificate_counter', 0);
        }
        
        if (false === get_option('hvac_certificate_prefix')) {
            add_option('hvac_certificate_prefix', 'HVAC-');
        }
        
        if (false === get_option('hvac_certificate_storage_path')) {
            // Default path is within wp-content/uploads/hvac-certificates
            add_option('hvac_certificate_storage_path', 'hvac-certificates');
        }
        
        // Create the certificate storage directory
        $this->create_certificates_directory();
    }

    /**
     * Create certificates directory if it doesn't exist.
     *
     * @return bool True if directory exists or was created, false otherwise.
     */
    public function create_certificates_directory() {
        $upload_dir = wp_upload_dir();
        $cert_dir = $upload_dir['basedir'] . '/' . get_option('hvac_certificate_storage_path', 'hvac-certificates');
        
        // Create directory if it doesn't exist
        if (!file_exists($cert_dir)) {
            wp_mkdir_p($cert_dir);
        }
        
        // Create .htaccess file to protect directory
        if (file_exists($cert_dir) && !file_exists($cert_dir . '/.htaccess')) {
            $htaccess_content = "# Disable directory browsing
Options -Indexes

# Deny access to php files
<FilesMatch \"\.(php|php5|phtml|php7)$\">
Order Allow,Deny
Deny from all
</FilesMatch>

# Allow PDF downloads only via WordPress
<FilesMatch \"\.(pdf)$\">
Order Allow,Deny
Deny from all
</FilesMatch>

# Restrict direct access
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^" . get_site_url() . " [NC]
RewriteRule \\.(pdf)$ - [NC,F,L]
</IfModule>";
            
            file_put_contents($cert_dir . '/.htaccess', $htaccess_content);
        }
        
        return file_exists($cert_dir);
    }

    /**
     * Check if the certificate tables exist and are up to date.
     *
     * @return bool True if tables are up to date, false otherwise.
     */
    public function check_tables() {
        global $wpdb;
        
        $installed_version = get_option('hvac_certificates_db_version');
        $table_name = $wpdb->prefix . 'hvac_certificates';
        
        // Check if table exists
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
        
        // If table doesn't exist or version is different, create/update tables
        if (!$table_exists || $installed_version !== $this->db_version) {
            $this->create_tables();
            return false;
        }
        
        return true;
    }

    /**
     * Upgrade routine for database tables.
     *
     * @return void
     */
    public function maybe_upgrade() {
        $installed_version = get_option('hvac_certificates_db_version');
        
        // If installed version is different from current version, run upgrade
        if ($installed_version !== $this->db_version) {
            $this->create_tables();
        }
    }
}