<?php

declare(strict_types=1);

namespace App\Modules\Workspace;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Session;
use App\Core\Database;
use App\Core\Logger;

/**
 * AdminDashboardController — Coordinates the Platform Administration Business Dashboard (RC-016 & RC-016B).
 */
class AdminDashboardController extends BaseController
{
    protected string $layout = 'admin';

    /**
     * Show Super Admin Dashboard with metrics and workspace search.
     */
    public function index(Request $request): void
    {
        // Clear active workspace viewing mode when return to dashboard
        Session::set('super_admin_workspace_mode', null);
        Session::set('active_workspace_id', null);
        Session::set('active_workspace_name', null);

        $db = Database::getConnection();
        $today = date('Y-m-d');
        $endOfWeek = date('Y-m-d', strtotime('+7 days'));

        // 1. Summary Cards
        $totalWorkspaces = (int) $db->query('SELECT COUNT(*) FROM workspaces')->fetchColumn();
        $activeWorkspaces = (int) $db->query("SELECT COUNT(*) FROM workspaces WHERE workspace_status = 'running'")->fetchColumn();
        
        $statuses = ['draft', 'preparing', 'published', 'running', 'completed', 'archived', 'suspended'];
        $statusCounts = [];
        foreach ($statuses as $status) {
            $stmt = $db->prepare('SELECT COUNT(*) FROM workspaces WHERE workspace_status = ?');
            $stmt->execute([$status]);
            $statusCounts[$status] = (int) $stmt->fetchColumn();
        }

        // 2. Commercial Summary
        $starterPlans = (int) $db->query('SELECT COUNT(*) FROM workspaces WHERE commercial_plan_id = 1')->fetchColumn();
        $proPlans = (int) $db->query('SELECT COUNT(*) FROM workspaces WHERE commercial_plan_id = 2')->fetchColumn();
        $customPlans = (int) $db->query('SELECT COUNT(*) FROM workspaces WHERE commercial_plan_id = 3')->fetchColumn();

        // 3. Event Summary
        $weddingEvents = (int) $db->query('SELECT COUNT(*) FROM workspaces WHERE event_type_id = 1')->fetchColumn();
        $engagementEvents = (int) $db->query('SELECT COUNT(*) FROM workspaces WHERE event_type_id = 2')->fetchColumn();
        $customEvents = (int) $db->query('SELECT COUNT(*) FROM workspaces WHERE event_type_id NOT IN (1, 2)')->fetchColumn();

        // 4. Upcoming Events counts
        $stmtToday = $db->prepare('SELECT COUNT(*) FROM workspaces WHERE wedding_date = ?');
        $stmtToday->execute([$today]);
        $upcomingToday = (int) $stmtToday->fetchColumn();

        $stmtWeek = $db->prepare('SELECT COUNT(*) FROM workspaces WHERE wedding_date >= ? AND wedding_date <= ?');
        $stmtWeek->execute([$today, $endOfWeek]);
        $upcomingWeek = (int) $stmtWeek->fetchColumn();

        // 5. Closest Upcoming Event
        $stmtClosest = $db->query('
            SELECT w.id, w.groom_name, w.bride_name, w.wedding_date, w.workspace_status, w.slug, et.name AS event_type
            FROM workspaces w
            JOIN event_types et ON et.id = w.event_type_id
            WHERE w.wedding_date >= CURRENT_DATE
            ORDER BY w.wedding_date ASC
            LIMIT 1
        ');
        $closestEvent = $stmtClosest->fetch(\PDO::FETCH_ASSOC) ?: null;

        // 6. Recent Workspaces
        $stmtRecent = $db->query('
            SELECT w.id, w.groom_name, w.bride_name, w.wedding_date, w.workspace_status, w.slug, w.created_at, cp.name AS plan_name
            FROM workspaces w
            JOIN commercial_plans cp ON cp.id = w.commercial_plan_id
            ORDER BY w.created_at DESC
            LIMIT 5
        ');
        $recentWorkspaces = $stmtRecent->fetchAll(\PDO::FETCH_ASSOC);

        // 7. Workspace Search Results
        $search = trim((string) ($request->get('search') ?? ''));
        $searchResults = [];
        if ($search !== '') {
            $stmtSearch = $db->prepare('
                SELECT DISTINCT w.id, w.groom_name, w.bride_name, w.slug, w.wedding_date, w.workspace_status, cp.name AS plan_name, cp.id AS plan_id, w.custom_guest_limit
                FROM workspaces w
                JOIN commercial_plans cp ON cp.id = w.commercial_plan_id
                LEFT JOIN users u ON u.workspace_id = w.id
                LEFT JOIN crew_accounts ca ON ca.workspace_id = w.id
                LEFT JOIN guests g ON g.workspace_id = w.id
                WHERE w.groom_name LIKE ?
                   OR w.bride_name LIKE ?
                   OR w.slug LIKE ?
                   OR w.workspace_status LIKE ?
                   OR cp.name LIKE ?
                   OR u.email LIKE ?
                   OR u.username LIKE ?
                   OR u.display_name LIKE ?
                   OR ca.display_name LIKE ?
                   OR w.wedding_date LIKE ?
                   OR g.phone_number LIKE ?
                ORDER BY w.wedding_date ASC
            ');
            $searchQuery = "%{$search}%";
            $stmtSearch->execute([
                $searchQuery,
                $searchQuery,
                $searchQuery,
                $searchQuery,
                $searchQuery,
                $searchQuery,
                $searchQuery,
                $searchQuery,
                $searchQuery,
                $searchQuery,
                $searchQuery
            ]);
            $searchResults = $stmtSearch->fetchAll(\PDO::FETCH_ASSOC);
        }

        $this->render('admin/dashboard', [
            'title' => 'Admin Dashboard',
            'search' => $search,
            'searchResults' => $searchResults,
            'totalWorkspaces' => $totalWorkspaces,
            'activeWorkspaces' => $activeWorkspaces,
            'statusCounts' => $statusCounts,
            'starterPlans' => $starterPlans,
            'proPlans' => $proPlans,
            'customPlans' => $customPlans,
            'weddingEvents' => $weddingEvents,
            'engagementEvents' => $engagementEvents,
            'customEvents' => $customEvents,
            'upcomingToday' => $upcomingToday,
            'upcomingWeek' => $upcomingWeek,
            'closestEvent' => $closestEvent,
            'recentWorkspaces' => $recentWorkspaces,
            'success' => Session::get('flash_success') ?? null,
            'info' => Session::get('flash_info') ?? null,
        ]);

        Session::set('flash_success', null);
        Session::set('flash_info', null);
    }

    /**
     * Adopts workspace context and redirects to Couple dashboard in Viewing Mode (Part I).
     */
    public function openWorkspace(Request $request): void
    {
        $workspaceId = (int) $request->param('id');
        
        $db = Database::getConnection();
        $stmt = $db->prepare('SELECT id, groom_name, bride_name FROM workspaces WHERE id = ?');
        $stmt->execute([$workspaceId]);
        $workspace = $stmt->fetch();

        if (!$workspace) {
            $this->flash('error', 'Workspace not found.');
            $this->redirect('/app/admin/dashboard');
            return;
        }

        $workspaceName = "{$workspace['groom_name']} & {$workspace['bride_name']}";

        // Audit Log: Record Super Admin workspace adoption action (RC001-O01)
        $adminId = (int) Session::get('auth_user_id', 0);
        Logger::info('Super Admin adopted workspace context (Viewing Mode)', [
            'action'         => 'open_workspace',
            'admin_id'       => $adminId,
            'workspace_id'   => $workspaceId,
            'workspace_name' => $workspaceName,
            'ip'             => $request->getIp(),
            'timestamp'      => date('Y-m-d H:i:s'),
        ]);

        // Store Super Admin viewing context
        Session::set('active_workspace_id', $workspaceId);
        Session::set('active_workspace_name', $workspaceName);
        Session::set('super_admin_workspace_mode', true);

        $this->redirect('/app/couple/dashboard');
    }

    /**
     * Commercial Plans Management placeholder.
     */
    public function plansPlaceholder(Request $request): void
    {
        $this->render('admin/plans_placeholder', [
            'title' => 'Commercial Plans Management'
        ]);
    }

    /**
     * Theme Management placeholder.
     */
    public function themesPlaceholder(Request $request): void
    {
        $this->render('admin/themes_placeholder', [
            'title' => 'Theme Management'
        ]);
    }
}
