<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Visit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    /**
     * Get dashboard statistics
     */
    public function stats(Request $request)
    {
        $todayVisits = Visit::where(function($query) {
            $query->where(function($q) {
                // Single meetings: date equals today
                $q->where('meeting_type', 'single')
                  ->whereDate('date', today());
            })->orWhere(function($q) {
                // Multiple meetings: today is between date_from and date_to
                $q->where('meeting_type', 'multiple')
                  ->whereDate('date_from', '<=', today())
                  ->whereDate('date_to', '>=', today());
            });
        })->count();
        $completedVisits = Visit::where('status', 'Completed')->count();
        $totalVisits = Visit::count();
        $pendingVisits = Visit::whereIn('status', ['Pending Visitor', 'Pending Approve', 'Pending Host'])->count();

        // Status breakdown
        $statusBreakdown = Visit::select('status', DB::raw('count(*) as count'))
            ->groupBy('status')
            ->pluck('count', 'status')
            ->toArray();

        // Monthly trend (last 6 months)
        $monthlyTrend = Visit::select(
                DB::raw('DATE_FORMAT(created_at, "%Y-%m") as month'),
                DB::raw('count(*) as count')
            )
            ->where('created_at', '>=', now()->subMonths(6))
            ->groupBy('month')
            ->orderBy('month')
            ->get();

        return response()->json([
            'todayVisits' => $todayVisits,
            'completedVisits' => $completedVisits,
            'totalVisits' => $totalVisits,
            'pendingVisits' => $pendingVisits,
            'statusBreakdown' => $statusBreakdown,
            'monthlyTrend' => $monthlyTrend,
        ]);
    }

    /**
     * Get recent visits
     */
    public function recentVisits(Request $request)
    {
        $limit = $request->get('limit', 5);

        $visits = Visit::with(['mainVisitor'])
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get()
            ->map(function ($visit) {
                // Determine online/offline status based on visit date matching today
                $status = 'offline';

                if ($visit->meeting_type === 'single' && $visit->date) {
                    // Single meetings: check if date equals today
                    if ($visit->date->isSameDay(today())) {
                        $status = 'online';
                    }
                } elseif ($visit->meeting_type === 'multiple' && $visit->date_from && $visit->date_to) {
                    // Multiple meetings: check if today is between date_from and date_to
                    if (today()->between($visit->date_from, $visit->date_to)) {
                        $status = 'online';
                    }
                }

                return [
                    'id' => $visit->id,
                    'name' => ($visit->mainVisitor ? $visit->mainVisitor->name : $visit->main_visitor_email),
                    'requestNo' => $visit->request_id,
                    'status' => $status,
                    'avatar' => null, // Optional field - can be added later when visitor images are implemented
                ];
            });

        return response()->json($visits);
    }

    /**
     * Get today's scheduled visits
     */
    public function todayVisits()
    {
        $visits = Visit::with(['location', 'mainVisitor'])
            ->where(function($query) {
                $query->where(function($q) {
                    // Single meetings: date equals today
                    $q->where('meeting_type', 'single')
                      ->whereDate('date', today());
                })->orWhere(function($q) {
                    // Multiple meetings: today is between date_from and date_to
                    $q->where('meeting_type', 'multiple')
                      ->whereDate('date_from', '<=', today())
                      ->whereDate('date_to', '>=', today());
                });
            })
            // ->where('status', 'Approved')
            ->orderBy('start_time')
            ->get()
            ->map(function ($visit) {
                // Format dates based on meeting type
                if ($visit->meeting_type === 'single') {
                    $startDate = $visit->date->format('d-m-Y') . ' ' .
                                 \Carbon\Carbon::parse($visit->start_time)->format('H:i');
                    $endDate = $visit->date->format('d-m-Y') . ' ' .
                               \Carbon\Carbon::parse($visit->end_time)->format('H:i');
                } else {
                    $startDate = $visit->date_from->format('d-m-Y') . ' ' .
                                 \Carbon\Carbon::parse($visit->start_time)->format('H:i');
                    $endDate = $visit->date_to->format('d-m-Y') . ' ' .
                               \Carbon\Carbon::parse($visit->end_time)->format('H:i');
                }

                return [
                    'id' => (string)$visit->id,
                    'requestId' => $visit->request_id,
                    'hostName' => $visit->host_name,
                    'location' => isset($visit->location) ? $visit->location->name : '',
                    'mainVisitor' => isset($visit->mainVisitor) ? $visit->mainVisitor->name : $visit->main_visitor_email,
                    'numberOfVisitors' => $visit->number_of_visitors,
                    'status' => $visit->status,
                    'startDate' => $startDate,
                    'endDate' => $endDate,
                ];
            });

        return response()->json($visits);
    }

    /**
     * Get visit counts grouped by status with date range filter
     */
    public function visitStatus(Request $request)
    {
        $request->validate([
            'range' => 'required|in:today,yesterday,last_7_days,last_30_days',
        ]);

        $range = $request->get('range');

        // Build the base query with date filtering
        $query = Visit::query();

        switch ($range) {
            case 'today':
                $query->where(function($q) {
                    $q->where(function($sq) {
                        // Single meetings: date equals today
                        $sq->where('meeting_type', 'single')
                           ->whereDate('date', today());
                    })->orWhere(function($sq) {
                        // Multiple meetings: today is between date_from and date_to
                        $sq->where('meeting_type', 'multiple')
                           ->whereDate('date_from', '<=', today())
                           ->whereDate('date_to', '>=', today());
                    });
                });
                break;

            case 'yesterday':
                $yesterday = today()->subDay();
                $query->where(function($q) use ($yesterday) {
                    $q->where(function($sq) use ($yesterday) {
                        // Single meetings: date equals yesterday
                        $sq->where('meeting_type', 'single')
                           ->whereDate('date', $yesterday);
                    })->orWhere(function($sq) use ($yesterday) {
                        // Multiple meetings: yesterday is between date_from and date_to
                        $sq->where('meeting_type', 'multiple')
                           ->whereDate('date_from', '<=', $yesterday)
                           ->whereDate('date_to', '>=', $yesterday);
                    });
                });
                break;

            case 'last_7_days':
                $startDate = today()->subDays(6); // Last 7 days including today
                $endDate = today();
                $query->where(function($q) use ($startDate, $endDate) {
                    $q->where(function($sq) use ($startDate, $endDate) {
                        // Single meetings: date is within last 7 days
                        $sq->where('meeting_type', 'single')
                           ->whereBetween('date', [$startDate, $endDate]);
                    })->orWhere(function($sq) use ($startDate, $endDate) {
                        // Multiple meetings: date range overlaps with last 7 days
                        $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);
                                    });
                           });
                    });
                });
                break;

            case 'last_30_days':
                $startDate = today()->subDays(29); // Last 30 days including today
                $endDate = today();
                $query->where(function($q) use ($startDate, $endDate) {
                    $q->where(function($sq) use ($startDate, $endDate) {
                        // Single meetings: date is within last 30 days
                        $sq->where('meeting_type', 'single')
                           ->whereBetween('date', [$startDate, $endDate]);
                    })->orWhere(function($sq) use ($startDate, $endDate) {
                        // Multiple meetings: date range overlaps with last 30 days
                        $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);
                                    });
                           });
                    });
                });
                break;
        }

        // Get counts for each status
        $statusCounts = $query->select('status', DB::raw('count(*) as count'))
            ->groupBy('status')
            ->pluck('count', 'status')
            ->toArray();

        // Return all statuses with 0 for missing ones
        return response()->json([
            'completed' => $statusCounts['Completed'] ?? 0,
            'approved' => $statusCounts['Approved'] ?? 0,
            'pending_approve' => $statusCounts['Pending Approve'] ?? 0,
            'pending_visitor' => $statusCounts['Pending Visitor'] ?? 0,
            'pending_host' => $statusCounts['Pending Host'] ?? 0,
            'expired' => $statusCounts['Expired'] ?? 0,
            'rejected' => $statusCounts['Rejected'] ?? 0,
            'canceled' => $statusCounts['Canceled'] ?? 0,
        ]);
    }
}
