<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\FinancingApplication;
use App\Models\ContactMessage;
use App\Models\ServiceBooking;
use App\Models\NewsletterSubscriber;
use App\Models\AdminUser;
use App\Models\Setting;
use App\Models\Page;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Blog;
use App\Models\Service;
use App\Models\Car;

class DashboardController extends Controller
{
    public function index()
    {
        try {
            $stats = [
                'total_applications' => FinancingApplication::count(),
                'pending_applications' => FinancingApplication::where('status', 'pending')->count(),
                'approved_applications' => FinancingApplication::where('status', 'approved')->count(),
                'total_messages' => ContactMessage::count(),
                'unread_messages' => ContactMessage::where('status', 'unread')->count(),
                'total_bookings' => ServiceBooking::count(),
                'pending_bookings' => ServiceBooking::where('status', 'pending')->count(),
                'newsletter_subscribers' => NewsletterSubscriber::where('is_active', true)->count(),
                'total_blogs' => Blog::count(),
                'total_services' => Service::count(),
                'optimized_count' => Car::whereNotNull('meta_title')->where('meta_title', '!=', '')->count() + 
                                     Service::whereNotNull('meta_title')->where('meta_title', '!=', '')->count(),
            ];

            // Monthly applications for chart (last 6 months)
            $sixMonthsAgo = now()->subMonths(6);
            $monthlyApplications = FinancingApplication::select(
                DB::raw('MONTH(created_at) as month'),
                DB::raw('YEAR(created_at) as year'),
                DB::raw('COUNT(*) as count')
            )
            ->where('created_at', '>=', $sixMonthsAgo)
            ->groupBy('year', 'month')
            ->orderBy('year')
            ->orderBy('month')
            ->get();

            // Application status breakdown
            $statusBreakdown = FinancingApplication::select('status', DB::raw('COUNT(*) as count'))
                ->groupBy('status')
                ->get();

            // Recent activity
            $recentApplications = FinancingApplication::latest()->limit(5)->get();
            $recentMessages = ContactMessage::latest()->limit(5)->get();
            $recentBookings = ServiceBooking::latest()->limit(5)->get();

            return view('admin.dashboard', compact(
                'stats', 'monthlyApplications', 'statusBreakdown',
                'recentApplications', 'recentMessages', 'recentBookings'
            ));
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Dashboard Error: ' . $e->getMessage(), [
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            return response()->json(['error' => $e->getMessage(), 'file' => $e->getFile()], 500);
        }
    }

    public function seoSettings()
    {
        try {
            $settings = \App\Models\Setting::pluck('value', 'key')->toArray();
            $pages = \App\Models\Page::all();
            $blogs = \App\Models\Blog::all();
            $services = \App\Models\Service::all();
            $cars = \App\Models\Car::all();
            
            return view('admin.settings.seo', compact('settings', 'pages', 'blogs', 'services', 'cars'));
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('SEO Settings Error: ' . $e->getMessage());
            return back()->with('error', 'SEO Error: ' . $e->getMessage());
        }
    }

    public function updateSeoSettings(Request $request)
    {
        foreach ($request->except('_token') as $key => $value) {
            \App\Models\Setting::updateOrCreate(
                ['key' => $key],
                ['value' => $value]
            );
        }
        return redirect()->back()->with('success', 'SEO settings updated successfully.');
    }
}
