<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class ComprehensiveVisitsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * Generates comprehensive test data covering:
     * - All visit statuses (Pending Visitor, Pending Approve, Pending Host, Approved, Rejected, Completed, Canceled, Expired)
     * - All meeting types (single, multiple)
     * - Date scenarios (today, yesterday, tomorrow, past week, next week, date ranges)
     * - All locations
     * - All user roles
     */
    public function run(): void
    {
        echo "🌱 Starting Comprehensive Visits Seeder...\n\n";

        // Get locations and users
        $locations = DB::table('locations')->pluck('id')->toArray();
        $users = DB::table('user_roles')->get();

        if (empty($locations)) {
            echo "❌ No locations found. Please run LocationsSeeder first.\n";
            return;
        }

        if ($users->isEmpty()) {
            echo "❌ No users found. Please run TestUserSeeder first.\n";
            return;
        }

        $admin = $users->where('email', 'admin@beyti.test')->first();
        $securityAdmin = $users->where('email', 'security.admin@beyti.test')->first();
        $securityMember = $users->where('email', 'security@beyti.test')->first();
        $host = $users->where('email', 'host@beyti.test')->first();

        $visitId = 1;
        $requestIdCounter = 1;

        // ============================================
        // TODAY'S VISITS - Various Statuses
        // ============================================
        echo "📅 Creating TODAY'S visits...\n";

        // 1. Approved - Single Day - Today
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $admin,
            'location_id' => $locations[0],
            'meeting_type' => 'single',
            'date' => today(),
            'start_time' => '09:00:00',
            'end_time' => '17:00:00',
            'status' => 'Approved',
            'visitor_email' => 'john.doe@techcorp.com',
            'visitor_name' => 'John Doe',
            'visitor_phone' => '0101234567',
            'visitor_company' => 'Tech Corp',
            'visit_reason' => 'Business meeting to discuss Q1 2026 partnership opportunities and contract renewal',
            'reviewed_by' => $securityAdmin->email,
        ]);

        // 2. Approved - Multiple Days - Spanning Today
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $host,
            'location_id' => $locations[0],
            'meeting_type' => 'multiple',
            'date_from' => today()->subDays(1),
            'date_to' => today()->addDays(2),
            'start_time' => '08:00:00',
            'end_time' => '18:00:00',
            'status' => 'Approved',
            'visitor_email' => 'sarah.wilson@consulting.com',
            'visitor_name' => 'Sarah Wilson',
            'visitor_phone' => '0109876543',
            'visitor_company' => 'Wilson Consulting',
            'visit_reason' => 'Multi-day workshop for training staff on new enterprise resource planning system',
            'reviewed_by' => $securityMember->email,
        ]);

        // 3. Pending Visitor - Single Day - Today
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $admin,
            'location_id' => $locations[1] ?? $locations[0],
            'meeting_type' => 'single',
            'date' => today(),
            'start_time' => '10:00:00',
            'end_time' => '12:00:00',
            'status' => 'Pending Visitor',
            'visitor_email' => 'mike.brown@example.com',
            'visitor_name' => null,
            'visitor_phone' => null,
            'visitor_company' => null,
            'visit_reason' => 'Technical consultation meeting for new infrastructure project proposal review',
            'token_expires_at' => now()->addDays(3),
            'has_visitors' => false,
        ]);

        // 4. Completed - Single Day - Today (early morning meeting)
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $securityAdmin,
            'location_id' => $locations[0],
            'meeting_type' => 'single',
            'date' => today(),
            'start_time' => '08:00:00',
            'end_time' => '09:30:00',
            'status' => 'Completed',
            'visitor_email' => 'emma.davis@suppliers.com',
            'visitor_name' => 'Emma Davis',
            'visitor_phone' => '0105551234',
            'visitor_company' => 'Suppliers Inc',
            'visit_reason' => 'Quarterly supplier review meeting and contract negotiations for upcoming fiscal year',
            'reviewed_by' => $securityMember->email,
        ]);

        // ============================================
        // YESTERDAY'S VISITS
        // ============================================
        echo "📅 Creating YESTERDAY'S visits...\n";

        // 5. Completed - Single Day - Yesterday
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $host,
            'location_id' => $locations[0],
            'meeting_type' => 'single',
            'date' => today()->subDay(),
            'start_time' => '14:00:00',
            'end_time' => '16:00:00',
            'status' => 'Completed',
            'visitor_email' => 'alex.johnson@partners.com',
            'visitor_name' => 'Alex Johnson',
            'visitor_phone' => '0107778888',
            'visitor_company' => 'Partners LLC',
            'visit_reason' => 'Strategic planning session for joint venture collaboration and market expansion',
            'reviewed_by' => $securityAdmin->email,
        ]);

        // 6. Rejected - Single Day - Yesterday
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $admin,
            'location_id' => $locations[0],
            'meeting_type' => 'single',
            'date' => today()->subDay(),
            'start_time' => '10:00:00',
            'end_time' => '11:00:00',
            'status' => 'Rejected',
            'visitor_email' => 'suspicious@unknown.com',
            'visitor_name' => null,
            'visitor_phone' => null,
            'visitor_company' => null,
            'visit_reason' => 'General business inquiry without specific details or company information',
            'reviewed_by' => $securityAdmin->email,
            'rejection_reason' => 'Insufficient company information and unclear business purpose. Security concerns due to lack of verifiable credentials.',
        ]);

        // ============================================
        // TOMORROW'S VISITS
        // ============================================
        echo "📅 Creating TOMORROW'S visits...\n";

        // 7. Approved - Single Day - Tomorrow
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $host,
            'location_id' => $locations[1] ?? $locations[0],
            'meeting_type' => 'single',
            'date' => today()->addDay(),
            'start_time' => '11:00:00',
            'end_time' => '13:00:00',
            'status' => 'Approved',
            'visitor_email' => 'lisa.anderson@marketing.com',
            'visitor_name' => 'Lisa Anderson',
            'visitor_phone' => '0103334444',
            'visitor_company' => 'Marketing Solutions',
            'visit_reason' => 'Marketing campaign presentation and brand strategy discussion for new product launch',
            'reviewed_by' => $securityMember->email,
        ]);

        // 8. Pending Approve - Single Day - Tomorrow
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $admin,
            'location_id' => $locations[0],
            'meeting_type' => 'single',
            'date' => today()->addDay(),
            'start_time' => '09:00:00',
            'end_time' => '10:00:00',
            'status' => 'Pending Approve',
            'visitor_email' => 'robert.taylor@legal.com',
            'visitor_name' => 'Robert Taylor',
            'visitor_phone' => '0106667777',
            'visitor_company' => 'Taylor Legal Associates',
            'visit_reason' => 'Legal consultation regarding contract compliance and regulatory requirements review',
        ]);

        // ============================================
        // LAST 7 DAYS - Various Dates
        // ============================================
        echo "📅 Creating visits from LAST 7 DAYS...\n";

        // 9. Completed - 3 days ago
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $securityAdmin,
            'location_id' => $locations[0],
            'meeting_type' => 'single',
            'date' => today()->subDays(3),
            'start_time' => '13:00:00',
            'end_time' => '15:00:00',
            'status' => 'Completed',
            'visitor_email' => 'david.lee@finance.com',
            'visitor_name' => 'David Lee',
            'visitor_phone' => '0102223333',
            'visitor_company' => 'Finance Group',
            'visit_reason' => 'Financial audit meeting and quarterly performance review with detailed analysis',
            'reviewed_by' => $securityAdmin->email,
        ]);

        // 10. Completed - 5 days ago
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $host,
            'location_id' => $locations[0],
            'meeting_type' => 'single',
            'date' => today()->subDays(5),
            'start_time' => '10:00:00',
            'end_time' => '12:00:00',
            'status' => 'Completed',
            'visitor_email' => 'maria.garcia@hr.com',
            'visitor_name' => 'Maria Garcia',
            'visitor_phone' => '0108889999',
            'visitor_company' => 'HR Solutions',
            'visit_reason' => 'Human resources policy review and employee benefit program consultation session',
            'reviewed_by' => $securityMember->email,
        ]);

        // 11. Expired - 6 days ago (token expired)
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $admin,
            'location_id' => $locations[0],
            'meeting_type' => 'single',
            'date' => today()->subDays(6),
            'start_time' => '14:00:00',
            'end_time' => '16:00:00',
            'status' => 'Expired',
            'visitor_email' => 'expired.visitor@example.com',
            'visitor_name' => null,
            'visitor_phone' => null,
            'visitor_company' => null,
            'visit_reason' => 'IT infrastructure assessment meeting that was not completed in time',
            'token_expires_at' => now()->subDays(3),
            'has_visitors' => false,
        ]);

        // ============================================
        // LAST 30 DAYS - More Historical Data
        // ============================================
        echo "📅 Creating visits from LAST 30 DAYS...\n";

        // 12. Completed - 10 days ago
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $host,
            'location_id' => $locations[1] ?? $locations[0],
            'meeting_type' => 'single',
            'date' => today()->subDays(10),
            'start_time' => '09:00:00',
            'end_time' => '11:00:00',
            'status' => 'Completed',
            'visitor_email' => 'james.white@construction.com',
            'visitor_name' => 'James White',
            'visitor_phone' => '0104445555',
            'visitor_company' => 'White Construction',
            'visit_reason' => 'Construction project planning and site assessment for new facility expansion',
            'reviewed_by' => $securityAdmin->email,
        ]);

        // 13. Completed - Multiple Days - 15-12 days ago
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $admin,
            'location_id' => $locations[0],
            'meeting_type' => 'multiple',
            'date_from' => today()->subDays(15),
            'date_to' => today()->subDays(12),
            'start_time' => '08:00:00',
            'end_time' => '17:00:00',
            'status' => 'Completed',
            'visitor_email' => 'patricia.miller@training.com',
            'visitor_name' => 'Patricia Miller',
            'visitor_phone' => '0107776666',
            'visitor_company' => 'Miller Training Institute',
            'visit_reason' => 'Comprehensive employee training workshop covering leadership and management skills',
            'reviewed_by' => $securityMember->email,
        ]);

        // 14. Canceled - 20 days ago
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $securityAdmin,
            'location_id' => $locations[0],
            'meeting_type' => 'single',
            'date' => today()->subDays(20),
            'start_time' => '15:00:00',
            'end_time' => '17:00:00',
            'status' => 'Canceled',
            'visitor_email' => 'canceled@visitor.com',
            'visitor_name' => null,
            'visitor_phone' => null,
            'visitor_company' => null,
            'visit_reason' => 'Product demonstration meeting that was canceled due to scheduling conflicts',
        ]);

        // 15. Rejected - 25 days ago
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $host,
            'location_id' => $locations[0],
            'meeting_type' => 'single',
            'date' => today()->subDays(25),
            'start_time' => '11:00:00',
            'end_time' => '12:00:00',
            'status' => 'Rejected',
            'visitor_email' => 'rejected.user@spam.com',
            'visitor_name' => null,
            'visitor_phone' => null,
            'visitor_company' => null,
            'visit_reason' => 'Unsolicited sales pitch without prior appointment or company verification',
            'reviewed_by' => $securityAdmin->email,
            'rejection_reason' => 'Unsolicited visit request without proper business credentials or prior relationship with the organization.',
        ]);

        // ============================================
        // FUTURE VISITS - Next Week
        // ============================================
        echo "📅 Creating FUTURE visits (next week)...\n";

        // 16. Approved - 3 days from now
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $admin,
            'location_id' => $locations[0],
            'meeting_type' => 'single',
            'date' => today()->addDays(3),
            'start_time' => '10:00:00',
            'end_time' => '12:00:00',
            'status' => 'Approved',
            'visitor_email' => 'future.visitor@tech.com',
            'visitor_name' => 'Kevin Park',
            'visitor_phone' => '0109998888',
            'visitor_company' => 'Tech Innovations',
            'visit_reason' => 'Innovation workshop and technology roadmap planning session for digital transformation',
            'reviewed_by' => $securityMember->email,
        ]);

        // 17. Pending Visitor - 5 days from now
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $host,
            'location_id' => $locations[1] ?? $locations[0],
            'meeting_type' => 'single',
            'date' => today()->addDays(5),
            'start_time' => '14:00:00',
            'end_time' => '16:00:00',
            'status' => 'Pending Visitor',
            'visitor_email' => 'pending.future@example.com',
            'visitor_name' => null,
            'visitor_phone' => null,
            'visitor_company' => null,
            'visit_reason' => 'Business development meeting for exploring potential partnership opportunities',
            'token_expires_at' => now()->addDays(7),
            'has_visitors' => false,
        ]);

        // 18. Approved - Multiple Days - Next Week (7-10 days from now)
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $securityAdmin,
            'location_id' => $locations[0],
            'meeting_type' => 'multiple',
            'date_from' => today()->addDays(7),
            'date_to' => today()->addDays(10),
            'start_time' => '09:00:00',
            'end_time' => '18:00:00',
            'status' => 'Approved',
            'visitor_email' => 'long.term@consulting.com',
            'visitor_name' => 'Michelle Chen',
            'visitor_phone' => '0105556666',
            'visitor_company' => 'Chen Consulting Group',
            'visit_reason' => 'Extended business process optimization consultation and systems integration planning',
            'reviewed_by' => $securityAdmin->email,
        ]);

        // 19. Pending Approve - 7 days from now
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $admin,
            'location_id' => $locations[0],
            'meeting_type' => 'single',
            'date' => today()->addDays(7),
            'start_time' => '13:00:00',
            'end_time' => '15:00:00',
            'status' => 'Pending Approve',
            'visitor_email' => 'awaiting.approval@company.com',
            'visitor_name' => 'Thomas Anderson',
            'visitor_phone' => '0103332222',
            'visitor_company' => 'Anderson Analytics',
            'visit_reason' => 'Data analytics presentation and business intelligence solution demonstration meeting',
        ]);

        // 20. Pending Host - 4 days from now (Returned by security)
        $this->createVisit([
            'id' => $visitId++,
            'request_id' => $this->generateRequestId($requestIdCounter++),
            'host' => $host,
            'location_id' => $locations[0],
            'meeting_type' => 'single',
            'date' => today()->addDays(4),
            'start_time' => '11:00:00',
            'end_time' => '13:00:00',
            'status' => 'Pending Host',
            'visitor_email' => 'needs.clarification@example.com',
            'visitor_name' => 'Rachel Green',
            'visitor_phone' => '0107778899',
            'visitor_company' => 'Green Enterprises',
            'visit_reason' => 'Initial vendor proposal meeting requiring additional documentation',
            'reviewed_by' => $securityMember->email,
            'rejection_reason' => 'Please provide additional documentation: company registration certificate and recent tax clearance. Visit purpose needs more detailed description.',
        ]);

        echo "\n✅ Comprehensive Visits Seeder completed successfully!\n";
        echo "📊 Total visits created: " . ($visitId - 1) . "\n\n";

        echo "Summary by Status:\n";
        $this->printStatusSummary();

        echo "\nSummary by Date Range:\n";
        $this->printDateRangeSummary();
    }

    /**
     * Create a visit with visitors
     */
    private function createVisit(array $data): void
    {
        // Get host name and phone based on email
        $hostData = $this->getHostData($data['host']->email);

        $visitData = [
            'id' => $data['id'],
            'request_id' => $data['request_id'],
            'host_email' => $data['host']->email,
            'host_name' => $hostData['name'],
            'host_phone' => $hostData['phone'],
            'location_id' => $data['location_id'],
            'visit_reason' => $data['visit_reason'],
            'meeting_type' => $data['meeting_type'],
            'status' => $data['status'],
            'registration_token' => Str::random(64),
            'number_of_visitors' => 1,
            'created_at' => now(),
            'updated_at' => now(),
        ];

        // Add date fields based on meeting type
        if ($data['meeting_type'] === 'single') {
            $visitData['date'] = $data['date'];
            $visitData['start_time'] = $data['start_time'];
            $visitData['end_time'] = $data['end_time'];
        } else {
            $visitData['date_from'] = $data['date_from'];
            $visitData['date_to'] = $data['date_to'];
            $visitData['start_time'] = $data['start_time'];
            $visitData['end_time'] = $data['end_time'];
        }

        // Add main visitor email
        $visitData['main_visitor_email'] = $data['visitor_email'];

        // Add status-specific fields
        if (in_array($data['status'], ['Approved', 'Completed', 'Rejected', 'Pending Host'])) {
            $visitData['reviewed_by_email'] = $data['reviewed_by'] ?? null;
            $visitData['reviewed_at'] = now();
        }

        if ($data['status'] === 'Rejected' || $data['status'] === 'Pending Host') {
            $visitData['rejection_reason'] = $data['rejection_reason'] ?? null;
        }

        if (isset($data['token_expires_at'])) {
            $visitData['token_expires_at'] = $data['token_expires_at'];
        } else if ($data['status'] === 'Pending Visitor') {
            $visitData['token_expires_at'] = now()->addDays(7);
        }

        if (in_array($data['status'], ['Approved', 'Completed'])) {
            $visitData['visitor_registered_at'] = now();
        }

        DB::table('visits')->insert($visitData);

        // Create visitor record if visitor has registered
        if (($data['has_visitors'] ?? true) && $data['visitor_name']) {
            DB::table('visitors')->insert([
                'visit_id' => $data['id'],
                'name' => $data['visitor_name'],
                'email' => $data['visitor_email'],
                'phone' => $data['visitor_phone'],
                'company_name' => $data['visitor_company'],
                'is_main_visitor' => true,
                'id_front_image' => 'storage/ids/sample_front_' . $data['id'] . '.jpg',
                'id_back_image' => 'storage/ids/sample_back_' . $data['id'] . '.jpg',
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            // Add some visits with multiple visitors
            if (in_array($data['id'], [1, 2, 7, 13, 18]) && in_array($data['status'], ['Approved', 'Completed'])) {
                DB::table('visitors')->insert([
                    'visit_id' => $data['id'],
                    'name' => 'Additional Visitor ' . $data['id'],
                    'email' => 'additional' . $data['id'] . '@example.com',
                    'phone' => '010555' . str_pad($data['id'], 4, '0', STR_PAD_LEFT),
                    'company_name' => $data['visitor_company'],
                    'is_main_visitor' => false,
                    'id_front_image' => 'storage/ids/additional_front_' . $data['id'] . '.jpg',
                    'id_back_image' => 'storage/ids/additional_back_' . $data['id'] . '.jpg',
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);

                DB::table('visits')->where('id', $data['id'])->update(['number_of_visitors' => 2]);
            }
        }

        // Create status history
        $this->createStatusHistory($data['id'], $data['status'], $data['reviewed_by'] ?? null);

        echo "  ✓ Created {$data['status']} visit: {$data['request_id']} - {$data['visitor_email']}\n";
    }

    /**
     * Create status history for a visit
     */
    private function createStatusHistory(int $visitId, string $status, ?string $reviewedBy): void
    {
        $statusFlow = [
            'Pending Visitor' => ['Pending Visitor'],
            'Pending Approve' => ['Pending Visitor', 'Pending Approve'],
            'Pending Host' => ['Pending Visitor', 'Pending Approve', 'Pending Host'],
            'Approved' => ['Pending Visitor', 'Pending Approve', 'Approved'],
            'Rejected' => ['Pending Visitor', 'Pending Approve', 'Rejected'],
            'Completed' => ['Pending Visitor', 'Pending Approve', 'Approved', 'Completed'],
            'Canceled' => ['Pending Visitor', 'Canceled'],
            'Expired' => ['Pending Visitor', 'Expired'],
        ];

        $statuses = $statusFlow[$status] ?? ['Pending Visitor'];
        $hostData = $reviewedBy ? $this->getHostData($reviewedBy) : null;

        foreach ($statuses as $index => $historyStatus) {
            $fromStatus = $index > 0 ? $statuses[$index - 1] : null;

            DB::table('visit_status_history')->insert([
                'visit_id' => $visitId,
                'from_status' => $fromStatus,
                'to_status' => $historyStatus,
                'changed_by_email' => $reviewedBy,
                'changed_by_name' => $hostData ? $hostData['name'] : null,
                'reason' => $this->getStatusNote($historyStatus),
                'created_at' => now()->subMinutes(count($statuses) - $index),
            ]);
        }
    }

    /**
     * Get status change note
     */
    private function getStatusNote(string $status): string
    {
        return match($status) {
            'Pending Visitor' => 'Visit request created and invitation sent to visitor',
            'Pending Approve' => 'Visitor completed registration, awaiting security approval',
            'Pending Host' => 'Returned to host for additional information',
            'Approved' => 'Visit approved by security team',
            'Rejected' => 'Visit rejected by security team',
            'Completed' => 'Visit completed successfully',
            'Canceled' => 'Visit canceled',
            'Expired' => 'Registration token expired',
            default => 'Status updated',
        };
    }

    /**
     * Get host data (name and phone) based on email
     */
    private function getHostData(string $email): array
    {
        return match($email) {
            'admin@beyti.test' => [
                'name' => 'Ahmed Mohamed',
                'phone' => '01021002800'
            ],
            'security.admin@beyti.test' => [
                'name' => 'Khaled Hassan',
                'phone' => '01012345678'
            ],
            'security@beyti.test' => [
                'name' => 'Fatima Ali',
                'phone' => '01098765432'
            ],
            'host@beyti.test' => [
                'name' => 'Omar Mahmoud',
                'phone' => '01055556666'
            ],
            default => [
                'name' => 'Unknown Host',
                'phone' => '01000000000'
            ],
        };
    }

    /**
     * Generate request ID
     */
    private function generateRequestId(int $counter): string
    {
        return 'VIS-' . today()->format('Ymd') . '-' . str_pad($counter, 4, '0', STR_PAD_LEFT);
    }

    /**
     * Print status summary
     */
    private function printStatusSummary(): void
    {
        $statuses = DB::table('visits')
            ->select('status', DB::raw('count(*) as count'))
            ->groupBy('status')
            ->get();

        foreach ($statuses as $status) {
            echo "  • {$status->status}: {$status->count}\n";
        }
    }

    /**
     * Print date range summary
     */
    private function printDateRangeSummary(): void
    {
        // Today
        $todayCount = DB::table('visits')
            ->where(function($q) {
                $q->where(function($sq) {
                    $sq->where('meeting_type', 'single')
                       ->whereDate('date', today());
                })->orWhere(function($sq) {
                    $sq->where('meeting_type', 'multiple')
                       ->whereDate('date_from', '<=', today())
                       ->whereDate('date_to', '>=', today());
                });
            })->count();

        // Yesterday
        $yesterday = today()->subDay();
        $yesterdayCount = DB::table('visits')
            ->where(function($q) use ($yesterday) {
                $q->where(function($sq) use ($yesterday) {
                    $sq->where('meeting_type', 'single')
                       ->whereDate('date', $yesterday);
                })->orWhere(function($sq) use ($yesterday) {
                    $sq->where('meeting_type', 'multiple')
                       ->whereDate('date_from', '<=', $yesterday)
                       ->whereDate('date_to', '>=', $yesterday);
                });
            })->count();

        // Last 7 days
        $last7Count = DB::table('visits')
            ->where(function($q) {
                $startDate = today()->subDays(6);
                $endDate = today();
                $q->where(function($sq) use ($startDate, $endDate) {
                    $sq->where('meeting_type', 'single')
                       ->whereBetween('date', [$startDate, $endDate]);
                })->orWhere(function($sq) use ($startDate, $endDate) {
                    $sq->where('meeting_type', 'multiple')
                       ->where(function($subQ) use ($startDate, $endDate) {
                           $subQ->whereBetween('date_from', [$startDate, $endDate])
                                ->orWhereBetween('date_to', [$startDate, $endDate])
                                ->orWhere(function($dateQ) use ($startDate, $endDate) {
                                    $dateQ->where('date_from', '<=', $startDate)
                                          ->where('date_to', '>=', $endDate);
                                });
                       });
                });
            })->count();

        // Last 30 days
        $last30Count = DB::table('visits')->count();

        echo "  • Today: {$todayCount}\n";
        echo "  • Yesterday: {$yesterdayCount}\n";
        echo "  • Last 7 days: {$last7Count}\n";
        echo "  • Last 30 days: {$last30Count}\n";
    }
}
