<?php
/**
 * Test Password Sync Queue
 * Access: admin/perfex_saas/test_queue (Admin only)
 */

defined('BASEPATH') or exit('No direct script access allowed');

class Test_queue extends AdminController
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        if (!is_admin()) {
            access_denied('Test Queue');
        }

        echo "<h2>Password Sync Queue Debug</h2>";
        echo "<hr>";

        // 1. Check if table exists
        echo "<h3>1. Checking Table...</h3>";
        $table_name = db_prefix() . 'perfex_saas_password_sync_queue';
        $table_exists = $this->db->table_exists($table_name);
        echo "Table exists: " . ($table_exists ? "✅ YES" : "❌ NO") . "<br>";

        if (!$table_exists) {
            echo "<strong>ERROR: Table doesn't exist! Run module installation again.</strong>";
            exit;
        }

        // 2. Check queue items count
        echo "<h3>2. Queue Items Count:</h3>";
        $total = $this->db->count_all($table_name);
        echo "Total items: <strong>$total</strong><br>";

        $pending = $this->db->where('status', 'pending')->count_all_results($table_name);
        echo "Pending: <strong>$pending</strong><br>";

        $completed = $this->db->where('status', 'completed')->count_all_results($table_name);
        echo "Completed: <strong>$completed</strong><br>";

        $failed = $this->db->where('status', 'failed')->count_all_results($table_name);
        echo "Failed: <strong>$failed</strong><br>";

        // 3. Show latest items
        echo "<h3>3. Latest 10 Queue Items:</h3>";
        $items = $this->db->order_by('id', 'DESC')->limit(10)->get($table_name)->result();
        if (!empty($items)) {
            echo "<table border='1' cellpadding='5' style='border-collapse: collapse;'>";
            echo "<tr><th>ID</th><th>Contact ID</th><th>Email</th><th>Company</th><th>Status</th><th>Attempts</th><th>Created</th><th>Error</th></tr>";
            foreach ($items as $item) {
                echo "<tr>";
                echo "<td>{$item->id}</td>";
                echo "<td>{$item->contact_id}</td>";
                echo "<td>" . ($item->contact_email ?? '<em>null</em>') . "</td>";
                echo "<td>" . ($item->company_slug ?? '<em>null</em>') . "</td>";
                echo "<td><strong>{$item->status}</strong></td>";
                echo "<td>{$item->attempts}</td>";
                echo "<td>{$item->created_at}</td>";
                echo "<td>" . ($item->error_message ? substr($item->error_message, 0, 50) : '-') . "</td>";
                echo "</tr>";
            }
            echo "</table>";
        } else {
            echo "<p><strong>⚠️ No queue items found!</strong></p>";
        }

        // 4. Add test item button
        echo "<h3>4. Add Test Item:</h3>";
        if ($this->input->get('add_test') == '1') {
            // Get first active contact
            $this->db->select('c.id, c.email, c.userid');
            $this->db->from(db_prefix() . 'contacts c');
            $this->db->where('c.active', 1);
            $this->db->limit(1);
            $contact = $this->db->get()->row();

            if ($contact) {
                $test_hash = password_hash('Test123456', PASSWORD_DEFAULT);
                $this->db->insert($table_name, [
                    'contact_id' => $contact->id,
                    'password_hash' => $test_hash,
                    'status' => 'pending',
                    'attempts' => 0,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
                echo "<p style='color: green;'>✅ Test item added! Contact ID: {$contact->id}, Email: {$contact->email}</p>";
                echo "<a href='" . admin_url('perfex_saas/test_queue') . "'>Refresh Page</a>";
            } else {
                echo "<p style='color: red;'>❌ No active contacts found!</p>";
            }
        } else {
            echo "<a href='" . admin_url('perfex_saas/test_queue?add_test=1') . "' class='btn btn-primary'>Add Test Queue Item</a>";
        }

        // 5. Process queue button
        echo "<h3>5. Manual Processing:</h3>";
        if ($this->input->get('process') == '1') {
            echo "<p>Processing queue...</p>";
            $stats = perfex_saas_process_password_sync_queue();
            echo "<pre>";
            print_r($stats);
            echo "</pre>";
            echo "<a href='" . admin_url('perfex_saas/test_queue') . "'>Refresh Page</a>";
        } else {
            echo "<a href='" . admin_url('perfex_saas/test_queue?process=1') . "' class='btn btn-success'>Process Queue Now</a>";
        }

        // 6. Check active companies
        echo "<h3>6. Active Companies Check:</h3>";
        $companies_count = $this->db->where('status', 'active')->count_all_results(db_prefix() . 'perfex_saas_companies');
        echo "Active companies: <strong>$companies_count</strong><br>";

        if ($companies_count > 0) {
            $companies = $this->db->select('*')->where('status', 'active')->limit(5)->get(db_prefix() . 'perfex_saas_companies')->result();
            echo "<table border='1' cellpadding='5' style='border-collapse: collapse; width: 100%;'>";
            echo "<tr><th>ID</th><th>Slug</th><th>Client ID</th><th>DSN (Full)</th><th>Metadata</th><th>Parsed DB</th></tr>";
            foreach ($companies as $comp) {
                // Try multiple ways to get database name
                $parsed_db = '';
                $dsn_display = '<em style="color: red;">ENCRYPTED</em>';
                
                // Try to decrypt DSN
                if (!empty($comp->dsn)) {
                    try {
                        $this->load->library('encryption');
                        $decrypted_dsn = $this->encryption->decrypt($comp->dsn);
                        
                        if ($decrypted_dsn) {
                            $dsn_display = substr(htmlspecialchars($decrypted_dsn), 0, 80) . '...';
                            
                            // Extract database name
                            if (preg_match('/dbname=([^;]+)/', $decrypted_dsn, $matches)) {
                                $parsed_db = $matches[1];
                            }
                        }
                    } catch (Exception $e) {
                        $dsn_display = '<em style="color: orange;">Decryption failed</em>';
                    }
                }
                
                // Method 2: From metadata JSON
                if (empty($parsed_db) && !empty($comp->metadata)) {
                    $metadata = json_decode($comp->metadata, true);
                    if (isset($metadata['db_name'])) {
                        $parsed_db = $metadata['db_name'];
                    }
                }
                
                // Method 3: Fallback to slug (replace dash with underscore)
                if (empty($parsed_db)) {
                    $parsed_db = 'perfex_' . str_replace('-', '_', $comp->slug);
                }
                
                echo "<tr>";
                echo "<td>{$comp->id}</td>";
                echo "<td><strong>{$comp->slug}</strong></td>";
                echo "<td>{$comp->clientid}</td>";
                echo "<td style='font-size: 10px; word-break: break-all;'>" . $dsn_display . "</td>";
                echo "<td style='font-size: 10px;'>" . ($comp->metadata ? substr($comp->metadata, 0, 50) . '...' : '<em>empty</em>') . "</td>";
                echo "<td><strong style='color: " . ($parsed_db ? 'blue' : 'red') . ";'>{$parsed_db}</strong></td>";
                echo "</tr>";
            }
            echo "</table>";
        }

        echo "<hr>";
        
        // 7. Check actual databases
        echo "<h3>7. Actual Databases on Server:</h3>";
        $databases = $this->db->query("SHOW DATABASES LIKE 'perfex_%'")->result_array();
        if (!empty($databases)) {
            echo "<ul>";
            foreach ($databases as $db) {
                $db_name = reset($db);
                echo "<li><strong style='color: green;'>$db_name</strong></li>";
            }
            echo "</ul>";
        } else {
            echo "<p><em>No perfex_* databases found!</em></p>";
        }

        echo "<hr>";
        echo "<p><a href='" . admin_url('perfex_saas/password_sync_queue') . "'>← Back to Password Sync Queue</a></p>";
    }
}
