<?php

declare(strict_types=1);

namespace App\Modules\Operation;

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

/**
 * CrewHomeController — Coordinates Crew workspace selector hub and switching (RC-016).
 */
class CrewHomeController extends BaseController
{
    protected string $layout = 'crew';

    /**
     * Redirect to Crew Dashboard.
     */
    public function index(Request $request): void
    {
        $this->redirect('/app/crew/dashboard');
    }

    /**
     * Show Crew Portal Welcome Dashboard.
     */
    public function dashboard(Request $request): void
    {
        $userId = (int) Session::get('auth_user_id', 0);
        $db = Database::getConnection();

        // 1. Clear active workspace context when in portal level
        Session::set('active_workspace_id', null);
        Session::set('active_workspace_name', null);
        Session::set('workspace_id', null);
        Session::set('super_admin_workspace_mode', null);

        // Fetch user metadata for display
        $stmtUser = $db->prepare('SELECT display_name, username FROM users WHERE id = ?');
        $stmtUser->execute([$userId]);
        $userRow = $stmtUser->fetch(\PDO::FETCH_ASSOC);
        $crewName = $userRow ? ($userRow['display_name'] ?: $userRow['username']) : 'Crew Member';

        // 2. Count total assigned workspaces
        $stmtCount = $db->prepare('
            SELECT COUNT(DISTINCT w.id)
            FROM workspaces w
            JOIN crew_accounts ca ON ca.workspace_id = w.id
            WHERE ca.user_id = :user_id AND ca.is_active = 1 AND w.workspace_status != \'purged\' AND w.workspace_status != \'archived\'
        ');
        $stmtCount->execute(['user_id' => $userId]);
        $totalAssigned = (int) $stmtCount->fetchColumn();

        // 3. Get incoming weddings (occurring in next 30 days)
        $today = date('Y-m-d');
        $thirtyDaysLater = date('Y-m-d', strtotime('+30 days'));

        $stmtIncoming = $db->prepare('
            SELECT w.id, w.groom_name, w.bride_name, w.wedding_date, w.workspace_status,
                   (SELECT venue_name FROM wedding_events WHERE workspace_id = w.id AND is_primary = 1 AND is_deleted = 0 LIMIT 1) AS venue_name
            FROM workspaces w
            JOIN crew_accounts ca ON ca.workspace_id = w.id
            WHERE ca.user_id = :user_id 
              AND ca.is_active = 1 
              AND w.workspace_status != \'purged\'
              AND w.workspace_status != \'archived\'
              AND w.wedding_date >= :today
              AND w.wedding_date <= :thirty_days_later
            ORDER BY w.wedding_date ASC
        ');
        $stmtIncoming->execute([
            'user_id' => $userId,
            'today' => $today,
            'thirty_days_later' => $thirtyDaysLater
        ]);
        $incomingWeddings = $stmtIncoming->fetchAll(\PDO::FETCH_ASSOC);

        $this->render('operation/dashboard', [
            'title' => 'Crew Dashboard',
            'crewName' => $crewName,
            'totalAssigned' => $totalAssigned,
            'incomingWeddings' => $incomingWeddings
        ]);
    }

    /**
     * Show Assigned Weddings List with Search & Pagination.
     */
    public function weddingsList(Request $request): void
    {
        $userId = (int) Session::get('auth_user_id', 0);
        $db = Database::getConnection();

        // 1. Clear active workspace context when in portal level
        Session::set('active_workspace_id', null);
        Session::set('active_workspace_name', null);
        Session::set('workspace_id', null);
        Session::set('super_admin_workspace_mode', null);

        // 2. Search & Pagination parameters
        $search = $request->get('search', '');
        $searchQuery = '%' . $search . '%';

        $page = max(1, (int) $request->get('page', 1));
        $limit = 10;
        $offset = ($page - 1) * $limit;

        // 3. Fetch count of workspaces
        $stmtTotal = $db->prepare('
            SELECT COUNT(DISTINCT w.id)
            FROM workspaces w
            JOIN crew_accounts ca ON ca.workspace_id = w.id
            WHERE ca.user_id = :user_id 
              AND ca.is_active = 1 
              AND w.workspace_status != \'purged\'
              AND w.workspace_status != \'archived\'
              AND (w.groom_name LIKE :search1 OR w.bride_name LIKE :search2)
        ');
        $stmtTotal->execute([
            'user_id' => $userId,
            'search1' => $searchQuery,
            'search2' => $searchQuery
        ]);
        $totalItems = (int) $stmtTotal->fetchColumn();
        $totalPages = (int) ceil($totalItems / $limit);

        // 4. Fetch page items
        $stmt = $db->prepare('
            SELECT w.id, w.groom_name, w.bride_name, w.wedding_date, w.workspace_status, w.slug,
                   (SELECT venue_name FROM wedding_events WHERE workspace_id = w.id AND is_primary = 1 AND is_deleted = 0 LIMIT 1) AS venue_name
            FROM workspaces w
            JOIN crew_accounts ca ON ca.workspace_id = w.id
            WHERE ca.user_id = :user_id 
              AND ca.is_active = 1 
              AND w.workspace_status != \'purged\'
              AND w.workspace_status != \'archived\'
              AND (w.groom_name LIKE :search1 OR w.bride_name LIKE :search2)
            ORDER BY w.wedding_date ASC
            LIMIT :limit OFFSET :offset
        ');
        $stmt->bindValue(':user_id', $userId, \PDO::PARAM_INT);
        $stmt->bindValue(':search1', $searchQuery, \PDO::PARAM_STR);
        $stmt->bindValue(':search2', $searchQuery, \PDO::PARAM_STR);
        $stmt->bindValue(':limit', $limit, \PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, \PDO::PARAM_INT);
        $stmt->execute();
        $workspaces = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $this->render('operation/weddings_list', [
            'title' => 'Assigned Weddings',
            'workspaces' => $workspaces,
            'search' => $search,
            'page' => $page,
            'totalPages' => $totalPages,
            'totalItems' => $totalItems
        ]);
    }

    /**
     * Process workspace selection.
     */
    public function selectWorkspace(Request $request): void
    {
        $userId = (int) Session::get('auth_user_id', 0);
        $workspaceId = (int) $request->post('workspace_id');

        $db = Database::getConnection();
        
        // Secure check: verify crew user is indeed assigned to target workspace
        $stmt = $db->prepare('
            SELECT w.id, w.groom_name, w.bride_name 
            FROM workspaces w
            JOIN crew_accounts ca ON ca.workspace_id = w.id
            WHERE ca.user_id = :user_id AND ca.workspace_id = :workspace_id AND ca.is_active = 1
            LIMIT 1
        ');
        $stmt->execute([
            'user_id' => $userId,
            'workspace_id' => $workspaceId
        ]);
        $ws = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$ws) {
            Session::set('flash_danger', 'Unauthorized workspace selection.');
            $this->redirect('/app/crew/dashboard');
            return;
        }

        $workspaceName = "{$ws['groom_name']} & {$ws['bride_name']}";
        
        Session::set('active_workspace_id', $workspaceId);
        Session::set('active_workspace_name', $workspaceName);
        Session::set('workspace_id', $workspaceId);

        // Save last selected workspace in persistent cookie for 1 year (RC001-S01)
        $cookieName = 'last_selected_workspace_id_' . $userId;
        $isSecure = function_exists('env') ? (env('APP_ENV') === 'production') : false;
        setcookie($cookieName, (string) $workspaceId, [
            'expires'  => time() + (365 * 24 * 60 * 60),
            'path'     => '/',
            'secure'   => $isSecure,
            'httponly' => true,
            'samesite' => 'Strict',
        ]);

        $this->redirect('/app/crew/operation/scanner');
    }
}
