<?php

namespace App\Http\Controllers\Agency;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\Agency\Agency;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function index()
    {

        if (!Auth::check()) {
            return view('customer.welcome');
        }

        $user = auth()->user();
        $agencyId = $user->currentAgencyId();
        
        if (!$agencyId && !$user->isSuperAdmin()) {
            return redirect()->route('agency.login');
        }

        $agency = Agency::find($agencyId);

        // İstatistikler
        $stats = $agency ? $this->getStats($agency) : [];

        // Son rezervasyonlar
        $recentBookings = $agency ? $this->getRecentBookings($agency) : collect();

        // Popüler turlar
        $popularTours = $agency ? $this->getPopularTours($agency) : collect();

        // Aylık gelir grafiği
        $monthlyRevenue = $agency ? $this->getMonthlyRevenue($agency) : ['months' => [], 'revenues' => []];

        // Son aktiviteler
        $recentActivities = $agency ? $this->getRecentActivities($agency) : collect();

        return view('agency.dashboard', compact(
            'stats', 
            'recentBookings', 
            'popularTours', 
            'monthlyRevenue', 
            'recentActivities',
            'agency'
        ));
    }

    private function getStats($agency)
    {
        $currentMonth = Carbon::now()->startOfMonth();
        $lastMonth = Carbon::now()->subMonth()->startOfMonth();

        // Bu ay ve geçen ay istatistikleri
        $thisMonthBookings = $this->getBookingsCount($agency, $currentMonth);
        $lastMonthBookings = $this->getBookingsCount($agency, $lastMonth, $currentMonth);

        $thisMonthRevenue = $this->getRevenue($agency, $currentMonth);
        $lastMonthRevenue = $this->getRevenue($agency, $lastMonth, $currentMonth);

        return [
            'total_tours' => $this->getTotalTours($agency),
            'active_tours' => $this->getActiveTours($agency),
            'total_bookings' => $thisMonthBookings,
            'bookings_change' => $this->calculatePercentageChange($thisMonthBookings, $lastMonthBookings),
            'total_customers' => $this->getTotalCustomers($agency),
            'monthly_revenue' => $thisMonthRevenue,
            'revenue_change' => $this->calculatePercentageChange($thisMonthRevenue, $lastMonthRevenue),
            'pending_bookings' => $this->getPendingBookings($agency),
            'confirmed_bookings' => $this->getConfirmedBookings($agency),
        ];
    }

    private function getBookingsCount($agency, $startDate, $endDate = null)
    {
        $query = DB::table('reservations')
            ->where('agency_id', $agency->id)
            ->where('created_at', '>=', $startDate);

        if ($endDate) {
            $query->where('created_at', '<', $endDate);
        }

        return $query->count();
    }

    private function getRevenue($agency, $startDate, $endDate = null)
    {
        $query = DB::table('reservations')
            ->where('agency_id', $agency->id)
            ->where('status', 'confirmed')
            ->where('created_at', '>=', $startDate);

        if ($endDate) {
            $query->where('created_at', '<', $endDate);
        }

        return $query->sum('total_amount') ?? 0;
    }

    private function getTotalTours($agency)
    {
        return DB::table('products')->where('agency_id', $agency->id)->count();
    }

    private function getActiveTours($agency)
    {
        return DB::table('products')
            ->where('agency_id', $agency->id)
            ->where('is_active', true)
            ->count();
    }

    private function getTotalCustomers($agency)
    {
        return DB::table('reservations')
            ->where('agency_id', $agency->id)
            ->distinct('customer_id')
            ->count();
    }

    private function getPendingBookings($agency)
    {
        return DB::table('reservations')
            ->where('agency_id', $agency->id)
            ->where('status', 'pending')
            ->count();
    }

    private function getConfirmedBookings($agency)
    {
        return DB::table('reservations')
            ->where('agency_id', $agency->id)
            ->where('status', 'confirmed')
            ->count();
    }

    private function getRecentBookings($agency)
    {
        return DB::table('reservations')
            ->leftJoin('products', 'reservations.product_id', '=', 'products.id')
            ->leftJoin('customers', 'reservations.customer_id', '=', 'customers.id')
            ->select(
                'reservations.*',
                'products.name as tour_title',
                'customers.first_name',
                'customers.last_name',
                'customers.phone'
            )
            ->where('reservations.agency_id', $agency->id)
            ->orderBy('reservations.created_at', 'desc')
            ->limit(5)
            ->get();
    }

    private function getPopularTours($agency)
    {
        return DB::table('products')
            ->leftJoin('reservations', 'products.id', '=', 'reservations.product_id')
            ->select(
                'products.id',
                'products.name',
                'products.base_price as price',
                DB::raw('COUNT(reservations.id) as bookings_count'),
                DB::raw('SUM(CASE WHEN reservations.status = "confirmed" THEN reservations.total_amount ELSE 0 END) as total_revenue')
            )
            ->where('products.agency_id', $agency->id)
            ->groupBy('products.id', 'products.name', 'products.base_price')
            ->orderBy('bookings_count', 'desc')
            ->limit(5)
            ->get();
    }

    private function getMonthlyRevenue($agency)
    {
        $months = [];
        $revenues = [];

        // Son 6 ay
        for ($i = 5; $i >= 0; $i--) {
            $date = Carbon::now()->subMonths($i);
            $startOfMonth = $date->copy()->startOfMonth();
            $endOfMonth = $date->copy()->endOfMonth();

            $revenue = DB::table('reservations')
                ->where('agency_id', $agency->id)
                ->where('status', 'confirmed')
                ->whereBetween('created_at', [$startOfMonth, $endOfMonth])
                ->sum('total_amount') ?? 0;

            $months[] = $date->format('M Y');
            $revenues[] = $revenue;
        }

        return [
            'months' => $months,
            'revenues' => $revenues
        ];
    }

    private function getRecentActivities($agency)
    {
        $activities = collect();

        // Son rezervasyonlar
        $recentBookings = DB::table('reservations')
            ->leftJoin('products', 'reservations.product_id', '=', 'products.id')
            ->leftJoin('customers', 'reservations.customer_id', '=', 'customers.id')
            ->select(
                'reservations.created_at',
                'reservations.status',
                'products.name as tour_title',
                'customers.first_name',
                'customers.last_name',
                DB::raw('"booking" as type')
            )
            ->where('reservations.agency_id', $agency->id)
            ->limit(3)
            ->get();

        foreach ($recentBookings as $booking) {
            $activities->push([
                'type' => 'booking',
                'title' => 'Yeni Rezervasyon',
                'description' => "{$booking->first_name} {$booking->last_name} - {$booking->tour_title}",
                'time' => Carbon::parse($booking->created_at)->diffForHumans(),
                'status' => $booking->status,
                'icon' => 'fas fa-calendar-plus',
                'color' => $booking->status === 'confirmed' ? 'success' : 'warning'
            ]);
        }

        // Son tur eklemeleri
        $recentTours = DB::table('products')
            ->select('name as title', 'created_at', 'is_active')
            ->where('agency_id', $agency->id)
            ->orderBy('created_at', 'desc')
            ->limit(2)
            ->get();

        foreach ($recentTours as $tour) {
            $activities->push([
                'type' => 'tour',
                'title' => 'Yeni Tur Eklendi',
                'description' => $tour->title,
                'time' => Carbon::parse($tour->created_at)->diffForHumans(),
                'status' => $tour->is_active ? 'active' : 'inactive',
                'icon' => 'fas fa-map-marked-alt',
                'color' => 'info'
            ]);
        }

        return $activities->sortByDesc('time')->take(5)->values();
    }

    private function calculatePercentageChange($current, $previous)
    {
        if ($previous == 0) {
            return $current > 0 ? 100 : 0;
        }

        return round((($current - $previous) / $previous) * 100, 1);
    }
}
