<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

final class AdminEmailQueueController extends Controller
{
    private function ensureTable($db): void
    {
        $st = $db->query("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='email_queue'");
        if ((int)$st->fetchColumn() <= 0) {
            throw new \RuntimeException("email_queue table missing");
        }
    }

    public function index(): void
    {
        require_admin_area();
        $db = Database::getInstance();
        $this->ensureTable($db);

        $status = trim((string)($_GET['status'] ?? ''));
        $q = trim((string)($_GET['q'] ?? ''));

        $where = [];
        $params = [];

        if ($status !== '') {
            $where[] = "status = :st";
            $params[':st'] = $status;
        }
        if ($q !== '') {
            $where[] = "(to_email LIKE :q OR subject_line LIKE :q OR template_key LIKE :q)";
            $params[':q'] = '%'.$q.'%';
        }

        $sql = "SELECT * FROM email_queue";
        if ($where) $sql .= " WHERE " . implode(" AND ", $where);
        $sql .= " ORDER BY id DESC LIMIT 300";

        $st = $db->prepare($sql);
        $st->execute($params);
        $rows = $st->fetchAll() ?: [];

        // KPI counts
        $counts = [
            'queued' => 0, 'sent' => 0, 'failed' => 0, 'all' => 0
        ];
        try {
            $counts['all'] = (int)$db->query("SELECT COUNT(*) FROM email_queue")->fetchColumn();
            foreach (['queued','sent','failed'] as $s) {
                $c = $db->prepare("SELECT COUNT(*) FROM email_queue WHERE status=:s");
                $c->execute([':s'=>$s]);
                $counts[$s] = (int)$c->fetchColumn();
            }
        } catch (\Throwable $e) {}

        $this->view('admin/email_queue/index', compact('rows','status','q','counts'));
    }

    public function retry(): void
    {
        require_admin_area();
        $db = Database::getInstance();
        $this->ensureTable($db);

        $id = (int)($_GET['id'] ?? 0);
        if ($id > 0) {
            $db->prepare("UPDATE email_queue SET status='queued', error_message=NULL, sent_at=NULL WHERE id=:id")
               ->execute([':id'=>$id]);
            if (function_exists('flash_set')) flash_set('success', 'Email moved back to queue');
        } else {
            if (function_exists('flash_set')) flash_set('danger', 'Missing id');
        }

        header('Location: ' . base_path('admin/email-queue'));
        exit;
    }

    public function retryAllFailed(): void
    {
        require_admin_area();
        $db = Database::getInstance();
        $this->ensureTable($db);

        $db->exec("UPDATE email_queue SET status='queued', error_message=NULL, sent_at=NULL WHERE status='failed'");
        if (function_exists('flash_set')) flash_set('success', 'All failed emails re-queued');

        header('Location: ' . base_path('admin/email-queue?status=failed'));
        exit;
    }

    public function delete(): void
    {
        require_admin_area();
        $db = Database::getInstance();
        $this->ensureTable($db);

        $id = (int)($_GET['id'] ?? 0);
        if ($id > 0) {
            $db->prepare("DELETE FROM email_queue WHERE id=:id")->execute([':id'=>$id]);
            if (function_exists('flash_set')) flash_set('success', 'Deleted');
        } else {
            if (function_exists('flash_set')) flash_set('danger', 'Missing id');
        }

        header('Location: ' . base_path('admin/email-queue'));
        exit;
    }

    public function runWorker(): void
    {
        require_admin_area();

        // Run worker script (best-effort). Adjust path if your worker differs.
        $cli = BASE_PATH . '/admin/cli/run_jobs.php';
        $ok = false;
        $out = '';

        if (is_file($cli)) {
            $cmd = 'php ' . escapeshellarg($cli) . ' 2>&1';
            $out = (string)shell_exec($cmd);
            $ok = true;
        } else {
            // fallback: if you have a dedicated email worker
            $alt = BASE_PATH . '/admin/cli/send_queued_emails.php';
            if (is_file($alt)) {
                $cmd = 'php ' . escapeshellarg($alt) . ' 2>&1';
                $out = (string)shell_exec($cmd);
                $ok = true;
            }
        }

        if (function_exists('flash_set')) {
            if ($ok) flash_set('success', 'Worker executed');
            else flash_set('danger', 'Worker script not found in admin/cli');
        }

        // store last output (short) for quick display
        if ($out !== '') {
            if (session_status() !== PHP_SESSION_ACTIVE) session_start();
            $_SESSION['_worker_last_output'] = mb_substr($out, 0, 2000);
        }

        header('Location: ' . base_path('admin/email-queue'));
        exit;
    }

    public function workerOutput(): void
    {
        require_admin_area();
        if (session_status() !== PHP_SESSION_ACTIVE) session_start();
        header('Content-Type: text/plain; charset=utf-8');
        echo (string)($_SESSION['_worker_last_output'] ?? '');
    }
}
