<?php
/**
 * FLOWB0T NEXUS - AJAX API Handler
 * Handles all AJAX requests from the UI
 */

require_once NEXUS_ROOT . '/core/Database.php';
require_once NEXUS_ROOT . '/core/Logger.php';
require_once NEXUS_ROOT . '/engine/Processors/ImportProcessor.php';

use Flowb0t\Core\Database;
use Flowb0t\Core\Logger;
use Flowb0t\Engine\Processors\ImportProcessor;

// Get endpoint from request
$endpoint = $_GET['endpoint'] ?? $_POST['endpoint'] ?? '';
$input = json_decode(file_get_contents('php://input'), true) ?? [];

// Initialize response
$response = ['success' => false, 'error' => 'Unknown endpoint'];

try {
    $db = Database::getInstance();
    $pdo = $db->getConnection();

    switch ($endpoint) {

        // ========================================
        // JOB MANAGEMENT
        // ========================================

        case 'create_job':
            $jobUuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
                mt_rand(0, 0xffff), mt_rand(0, 0xffff),
                mt_rand(0, 0xffff),
                mt_rand(0, 0x0fff) | 0x4000,
                mt_rand(0, 0x3fff) | 0x8000,
                mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
            );

            $stmt = $pdo->prepare("
                INSERT INTO nexus_jobs (
                    job_uuid, name, description, job_type,
                    search_terms, target_domains, direct_urls,
                    max_depth, max_pages, max_concurrent, request_timeout, delay_between,
                    search_provider, search_pages, search_types,
                    relevance_threshold, min_content_length, allowed_languages, blocked_domains,
                    auto_import, import_to_pinfeeds, create_users, dedupe_by,
                    status, created_at
                ) VALUES (
                    ?, ?, ?, ?,
                    ?, ?, ?,
                    ?, ?, ?, ?, ?,
                    ?, ?, ?,
                    ?, ?, ?, ?,
                    ?, ?, ?, ?,
                    'pending', NOW()
                )
            ");

            $searchTerms = array_filter(array_map('trim', explode("\n", $input['search_terms'] ?? '')));
            $targetDomains = array_filter(array_map('trim', explode("\n", $input['target_domains'] ?? '')));
            $directUrls = array_filter(array_map('trim', explode("\n", $input['direct_urls'] ?? '')));

            $stmt->execute([
                $jobUuid,
                $input['name'] ?? 'Untitled Job',
                $input['description'] ?? '',
                $input['job_type'] ?? 'search',
                json_encode($searchTerms),
                json_encode($targetDomains),
                json_encode($directUrls),
                $input['max_depth'] ?? 3,
                $input['max_pages'] ?? 10000,
                $input['max_concurrent'] ?? 100,
                $input['request_timeout'] ?? 10,
                $input['delay_between'] ?? 0.5,
                $input['search_provider'] ?? 'bing',
                $input['search_pages'] ?? 10,
                json_encode($input['search_types'] ?? ['web', 'images', 'videos']),
                $input['relevance_threshold'] ?? 2,
                $input['min_content_length'] ?? 100,
                json_encode($input['languages'] ?? ['en', 'pt']),
                $input['blocked_domains'] ?? 'facebook.com,instagram.com,twitter.com',
                isset($input['auto_import']) ? 1 : 0,
                isset($input['import_to_pinfeeds']) ? 1 : 0,
                isset($input['create_users']) ? 1 : 0,
                $input['dedupe_by'] ?? 'url'
            ]);

            $response = ['success' => true, 'job_uuid' => $jobUuid, 'message' => 'Job created successfully'];
            break;

        case 'start_job':
            $jobId = $input['id'] ?? '';
            $stmt = $pdo->prepare("UPDATE nexus_jobs SET status = 'queued' WHERE job_uuid = ? AND status IN ('pending', 'paused')");
            $stmt->execute([$jobId]);
            $response = ['success' => $stmt->rowCount() > 0];
            break;

        case 'pause_job':
            $jobId = $input['id'] ?? '';
            $stmt = $pdo->prepare("UPDATE nexus_jobs SET status = 'paused', paused_at = NOW() WHERE job_uuid = ? AND status = 'running'");
            $stmt->execute([$jobId]);
            $response = ['success' => $stmt->rowCount() > 0];
            break;

        case 'resume_job':
            $jobId = $input['id'] ?? '';
            $stmt = $pdo->prepare("UPDATE nexus_jobs SET status = 'queued' WHERE job_uuid = ? AND status = 'paused'");
            $stmt->execute([$jobId]);
            $response = ['success' => $stmt->rowCount() > 0];
            break;

        case 'cancel_job':
            $jobId = $input['id'] ?? '';
            $stmt = $pdo->prepare("UPDATE nexus_jobs SET status = 'cancelled', completed_at = NOW() WHERE job_uuid = ? AND status IN ('running', 'paused', 'queued')");
            $stmt->execute([$jobId]);
            $response = ['success' => $stmt->rowCount() > 0];
            break;

        case 'restart_job':
            $jobId = $input['id'] ?? '';
            // Get job ID first
            $stmt = $pdo->prepare("SELECT id FROM nexus_jobs WHERE job_uuid = ?");
            $stmt->execute([$jobId]);
            $job = $stmt->fetch();

            if ($job) {
                // Reset job
                $pdo->beginTransaction();
                $pdo->prepare("DELETE FROM nexus_queue WHERE job_id = ?")->execute([$job['id']]);
                $pdo->prepare("DELETE FROM nexus_results WHERE job_id = ?")->execute([$job['id']]);
                $pdo->prepare("
                    UPDATE nexus_jobs SET
                        status = 'queued',
                        progress_percent = 0,
                        current_phase = 0,
                        total_queued = 0,
                        total_processed = 0,
                        total_successful = 0,
                        total_failed = 0,
                        total_skipped = 0,
                        total_imported = 0,
                        total_duplicates = 0,
                        started_at = NULL,
                        paused_at = NULL,
                        completed_at = NULL
                    WHERE job_uuid = ?
                ")->execute([$jobId]);
                $pdo->commit();
                $response = ['success' => true];
            } else {
                $response = ['success' => false, 'error' => 'Job not found'];
            }
            break;

        case 'delete_job':
            $jobId = $input['id'] ?? '';
            $stmt = $pdo->prepare("DELETE FROM nexus_jobs WHERE job_uuid = ? AND status IN ('completed', 'failed', 'cancelled')");
            $stmt->execute([$jobId]);
            $response = ['success' => $stmt->rowCount() > 0];
            break;

        case 'get_job_status':
            $jobId = $input['id'] ?? '';
            $stmt = $pdo->prepare("
                SELECT status, progress_percent, current_phase,
                       total_queued, total_processed, total_imported, total_failed
                FROM nexus_jobs WHERE job_uuid = ?
            ");
            $stmt->execute([$jobId]);
            $job = $stmt->fetch();
            $response = ['success' => true, 'job' => $job];
            break;

        // ========================================
        // EXPORT MANAGEMENT
        // ========================================

        case 'create_export':
        case 'export_job':
        case 'export_results':
            $source = $input['source'] ?? 'pinfeeds';
            $format = $input['format'] ?? 'csv';
            $jobId = $input['id'] ?? $input['job_id'] ?? null;
            $limit = intval($input['limit'] ?? 10000);

            // Create export record
            $stmt = $pdo->prepare("
                INSERT INTO nexus_exports (job_id, export_type, export_scope, status, created_at)
                VALUES (?, ?, ?, 'pending', NOW())
            ");

            $jobDbId = null;
            if ($jobId) {
                $s = $pdo->prepare("SELECT id FROM nexus_jobs WHERE job_uuid = ?");
                $s->execute([$jobId]);
                $jobDbId = $s->fetchColumn();
            }

            $stmt->execute([$jobDbId, $format, $source]);
            $exportId = $pdo->lastInsertId();

            // Start export process (simplified - in production would be async)
            $exportPath = NEXUS_ROOT . '/exports/export_' . $exportId . '.' . $format;

            // Get data based on source
            $data = [];
            switch ($source) {
                case 'pinfeeds':
                    $sql = "SELECT id, title, description, link, author, source_domain, pubDate FROM pinfeeds ORDER BY id DESC";
                    if ($limit > 0) $sql .= " LIMIT " . $limit;
                    $data = $pdo->query($sql)->fetchAll();
                    break;
                case 'users':
                    $sql = "SELECT ID, username, email, first_name, last_name, created_at FROM user_myhashtag ORDER BY ID DESC";
                    if ($limit > 0) $sql .= " LIMIT " . $limit;
                    $data = $pdo->query($sql)->fetchAll();
                    break;
                case 'domains':
                    $sql = "SELECT id, website_base, website_feed, main_category_id FROM feed_data ORDER BY id DESC";
                    if ($limit > 0) $sql .= " LIMIT " . $limit;
                    $data = $pdo->query($sql)->fetchAll();
                    break;
            }

            // Write export file
            if ($format === 'csv') {
                $fp = fopen($exportPath, 'w');
                if (!empty($data)) {
                    fputcsv($fp, array_keys($data[0]));
                    foreach ($data as $row) {
                        fputcsv($fp, $row);
                    }
                }
                fclose($fp);
            } elseif ($format === 'json') {
                file_put_contents($exportPath, json_encode($data, JSON_PRETTY_PRINT));
            } elseif ($format === 'sql') {
                $sql = "";
                foreach ($data as $row) {
                    $values = array_map(function($v) { return "'" . addslashes($v) . "'"; }, $row);
                    $sql .= "INSERT INTO {$source} (" . implode(',', array_keys($row)) . ") VALUES (" . implode(',', $values) . ");\n";
                }
                file_put_contents($exportPath, $sql);
            }

            // Update export record
            $fileSize = file_exists($exportPath) ? filesize($exportPath) : 0;
            $pdo->prepare("
                UPDATE nexus_exports SET
                    status = 'completed',
                    file_path = ?,
                    file_size = ?,
                    total_records = ?,
                    completed_at = NOW()
                WHERE id = ?
            ")->execute(['/exports/export_' . $exportId . '.' . $format, $fileSize, count($data), $exportId]);

            $response = ['success' => true, 'export_id' => $exportId, 'file' => '/exports/export_' . $exportId . '.' . $format];
            break;

        case 'delete_export':
            $exportId = $input['id'] ?? 0;
            $stmt = $pdo->prepare("SELECT file_path FROM nexus_exports WHERE id = ?");
            $stmt->execute([$exportId]);
            $export = $stmt->fetch();

            if ($export && $export['file_path']) {
                $fullPath = NEXUS_ROOT . $export['file_path'];
                if (file_exists($fullPath)) {
                    unlink($fullPath);
                }
            }

            $pdo->prepare("DELETE FROM nexus_exports WHERE id = ?")->execute([$exportId]);
            $response = ['success' => true];
            break;

        case 'clear_old_exports':
            $days = 7;
            $stmt = $pdo->prepare("SELECT file_path FROM nexus_exports WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)");
            $stmt->execute([$days]);
            foreach ($stmt->fetchAll() as $export) {
                if ($export['file_path']) {
                    $fullPath = NEXUS_ROOT . $export['file_path'];
                    if (file_exists($fullPath)) {
                        unlink($fullPath);
                    }
                }
            }
            $pdo->prepare("DELETE FROM nexus_exports WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)")->execute([$days]);
            $response = ['success' => true];
            break;

        // ========================================
        // LOG MANAGEMENT
        // ========================================

        case 'clear_logs':
            $type = $input['type'] ?? 'old';
            if ($type === 'all') {
                $pdo->exec("TRUNCATE TABLE nexus_logs");
            } else {
                $pdo->exec("DELETE FROM nexus_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 14 DAY)");
            }
            $response = ['success' => true];
            break;

        // ========================================
        // SETTINGS
        // ========================================

        case 'save_settings':
            $settings = $input['settings'] ?? [];
            foreach ($settings as $key => $value) {
                $pdo->prepare("
                    INSERT INTO nexus_settings (setting_key, setting_value, updated_at)
                    VALUES (?, ?, NOW())
                    ON DUPLICATE KEY UPDATE setting_value = ?, updated_at = NOW()
                ")->execute([$key, $value, $value]);
            }
            $response = ['success' => true];
            break;

        case 'reset_settings':
            $pdo->exec("DELETE FROM nexus_settings");
            $defaults = [
                'max_concurrent_jobs' => 10,
                'max_concurrent_workers' => 500,
                'default_request_timeout' => 10,
                'default_delay_between' => 0.5,
                'max_queue_size' => 1000000,
                'auto_cleanup_days' => 30,
                'export_retention_days' => 7,
                'log_retention_days' => 14
            ];
            foreach ($defaults as $key => $value) {
                $pdo->prepare("INSERT INTO nexus_settings (setting_key, setting_value) VALUES (?, ?)")->execute([$key, $value]);
            }
            $response = ['success' => true];
            break;

        case 'test_connection':
            $response = ['success' => true, 'message' => 'Connection OK'];
            break;

        case 'clear_cache':
            // Clear any cached data
            $response = ['success' => true];
            break;

        case 'run_cleanup':
            $deleted = 0;
            // Delete old completed jobs
            $stmt = $pdo->query("DELETE FROM nexus_jobs WHERE status IN ('completed', 'cancelled') AND completed_at < DATE_SUB(NOW(), INTERVAL 30 DAY)");
            $deleted += $stmt->rowCount();

            // Delete old logs
            $stmt = $pdo->query("DELETE FROM nexus_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 14 DAY)");
            $deleted += $stmt->rowCount();

            $response = ['success' => true, 'message' => "Deleted {$deleted} records"];
            break;

        case 'optimize_tables':
            $tables = ['nexus_jobs', 'nexus_queue', 'nexus_results', 'nexus_logs', 'pinfeeds', 'feed_data', 'user_myhashtag'];
            foreach ($tables as $table) {
                try {
                    $pdo->exec("OPTIMIZE TABLE {$table}");
                } catch (Exception $e) {}
            }
            $response = ['success' => true];
            break;

        case 'table_stats':
            $stats = [];
            $tables = ['pinfeeds', 'feed_data', 'user_myhashtag', 'nexus_jobs', 'nexus_queue', 'nexus_results', 'nexus_logs'];
            foreach ($tables as $table) {
                try {
                    $count = $pdo->query("SELECT COUNT(*) FROM {$table}")->fetchColumn();
                    $stats[$table] = $count;
                } catch (Exception $e) {
                    $stats[$table] = 'N/A';
                }
            }
            $response = ['success' => true, 'stats' => $stats];
            break;

        // ========================================
        // DASHBOARD REFRESH
        // ========================================

        case 'get_stats':
        case 'get_active-jobs':
            // Return updated HTML for dashboard sections
            ob_start();
            include NEXUS_ROOT . '/ui/pages/dashboard.php';
            $html = ob_get_clean();
            $response = ['success' => true, 'html' => $html];
            break;

        default:
            $response = ['success' => false, 'error' => 'Unknown endpoint: ' . $endpoint];
    }

} catch (Exception $e) {
    $response = ['success' => false, 'error' => $e->getMessage()];
}

// Output response
echo json_encode($response);
