<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Permission;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SuperAdminController extends Controller
{
    /**
     * Show super admin dashboard
     */
    public function dashboard()
    {
        $totalAdmins = User::where('role', 'admin')->count();
        $totalUsers = User::where('role', 'user')->count();
        $totalPermissions = Permission::count();
        $totalTransactions = Transaction::count();
        $totalRevenue = Transaction::where('type', 'income')->sum('amount');
        $totalExpenses = Transaction::where('type', 'expense')->sum('amount');

        $admins = User::where('role', 'admin')
            ->withCount('permissions')
            ->latest()
            ->paginate(15);

        // Get recent users (last 5 created users with role 'user')
        $recentUsers = User::where('role', 'user')
            ->latest()
            ->take(5)
            ->get();

        // Get top users by income (users with highest total income from transactions)
        $topUsers = User::where('role', 'user')
            ->withSum(['transactions' => function ($query) {
                $query->where('type', 'income');
            }], 'amount')
            ->orderByDesc('transactions_sum_amount')
            ->take(5)
            ->get();

        return view('super-admin.dashboard', compact(
            'totalAdmins',
            'totalUsers',
            'totalPermissions',
            'totalTransactions',
            'totalRevenue',
            'totalExpenses',
            'admins',
            'recentUsers',
            'topUsers'
        ));
    }

    /**
     * Show all admins with their permissions
     */
    public function manageAdmins()
    {
        $admins = User::where('role', 'admin')
            ->with('permissions')
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return view('super-admin.manage-admins', compact('admins'));
    }

    /**
     * Show edit form for admin permissions
     */
    public function editAdminPermissions(User $user)
    {
        if (!$user->isAdmin()) {
            return redirect()->route('super-admin.admins')->with('error', 'User is not an admin.');
        }

        $permissions = Permission::all()->groupBy('category');
        $adminPermissionIds = $user->permissions()->pluck('permissions.id')->toArray();

        return view('super-admin.edit-permissions', compact(
            'user',
            'permissions',
            'adminPermissionIds'
        ));
    }

    /**
     * Update admin permissions
     */
    public function updateAdminPermissions(Request $request, User $user)
    {
        if (!$user->isAdmin()) {
            return redirect()->route('super-admin.admins')->with('error', 'User is not an admin.');
        }

        $validated = $request->validate([
            'permissions' => 'array',
            'permissions.*' => 'exists:permissions,id',
        ]);

        $permissionIds = $validated['permissions'] ?? [];

        // Sync permissions
        $user->permissions()->sync($permissionIds);

        return redirect()->route('super-admin.admins')
            ->with('success', 'Admin permissions updated successfully.');
    }

    /**
     * Create a new admin
     */
    public function createAdmin()
    {
        return view('super-admin.create-admin');
    }

    /**
     * Store new admin
     */
    public function storeAdmin(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:8|confirmed',
        ]);

        $admin = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => bcrypt($validated['password']),
            'role' => 'admin',
            'total_balance' => 0,
        ]);

        return redirect()->route('super-admin.edit-permissions', $admin->id)
            ->with('success', 'Admin created successfully. Now assign permissions.');
    }

    /**
     * Delete an admin
     */
    public function deleteAdmin(User $user)
    {
        if (!$user->isAdmin()) {
            return redirect()->route('super-admin.admins')->with('error', 'User is not an admin.');
        }

        $user->permissions()->detach();
        $user->delete();

        return redirect()->route('super-admin.admins')
            ->with('success', 'Admin deleted successfully.');
    }

    /**
     * View all permissions
     */
    public function permissions()
    {
        $permissions = Permission::all()->groupBy('category');
        $admins = User::where('role', 'admin')->select('id', 'name')->get();

        return view('super-admin.permissions', compact('permissions', 'admins'));
    }

    /**
     * Show statistics dashboard
     */
    public function statistics(Request $request)
    {
        // Get filter month (default: current month, format: YYYY-MM)
        $filterMonth = $request->input('month', now()->format('Y-m'));

        // Get start and end dates for the filter month
        $startDate = \Carbon\Carbon::createFromFormat('Y-m', $filterMonth)->startOfMonth();
        $endDate = \Carbon\Carbon::createFromFormat('Y-m', $filterMonth)->endOfMonth();

        // Get admin statistics
        $adminStats = User::where('role', 'admin')
            ->select('id', 'name', 'email', 'created_at')
            ->withCount('permissions')
            ->withCount('transactions')
            ->get();

        // Get permission statistics
        $permissionStats = Permission::select('id', 'name', 'category', 'created_at')
            ->withCount('admins')
            ->orderBy('category')
            ->get()
            ->groupBy('category');

        // ========================================
        // Financial Statistics
        // ========================================

        // Overall totals (all time)
        $overallStats = [
            'totalSales' => \App\Models\SalesDashboard::sum('sales'),
            'totalRevenue' => \App\Models\SalesDashboard::sum('revenue'),
            'totalExpenses' => \App\Models\Transaction::where('type', 'expense')->sum('amount'),
            'totalProfit' => \App\Models\SalesDashboard::sum('gross_profit'),
            'totalPayments' => \App\Models\SalesDashboard::sum('payment'),
            'totalDue' => \App\Models\SalesDashboard::sum('due'),
        ];

        // Calculate Net Profit/Loss
        $overallStats['netProfit'] = $overallStats['totalRevenue'] - $overallStats['totalExpenses'];

        // Monthly filtered stats
        $monthlyStats = [
            'sales' => \App\Models\SalesDashboard::whereBetween('date', [$startDate, $endDate])->sum('sales'),
            'revenue' => \App\Models\SalesDashboard::whereBetween('date', [$startDate, $endDate])->sum('revenue'),
            'expenses' => \App\Models\Transaction::where('type', 'expense')->whereBetween('date', [$startDate, $endDate])->sum('amount'),
            'profit' => \App\Models\SalesDashboard::whereBetween('date', [$startDate, $endDate])->sum('gross_profit'),
            'payments' => \App\Models\SalesDashboard::whereBetween('date', [$startDate, $endDate])->sum('payment'),
            'due' => \App\Models\SalesDashboard::whereBetween('date', [$startDate, $endDate])->sum('due'),
        ];

        // Calculate Net Profit for filtered month
        $monthlyStats['netProfit'] = $monthlyStats['revenue'] - $monthlyStats['expenses'];

        // Get monthly data for the last 12 months (for chart)
        $monthlyChartData = [];
        for ($i = 11; $i >= 0; $i--) {
            $month = \Carbon\Carbon::now()->subMonths($i);
            $monthStart = $month->startOfMonth();
            $monthEnd = $month->endOfMonth();

            $monthlyChartData[] = [
                'month' => $month->format('M Y'),
                'sales' => \App\Models\SalesDashboard::whereBetween('date', [$monthStart, $monthEnd])->sum('sales'),
                'revenue' => \App\Models\SalesDashboard::whereBetween('date', [$monthStart, $monthEnd])->sum('revenue'),
                'expenses' => \App\Models\Transaction::where('type', 'expense')->whereBetween('date', [$monthStart, $monthEnd])->sum('amount'),
                'profit' => \App\Models\SalesDashboard::whereBetween('date', [$monthStart, $monthEnd])->sum('gross_profit'),
            ];
        }

        // Get available months for filter (last 12 months)
        $availableMonths = [];
        for ($i = 0; $i < 12; $i++) {
            $month = \Carbon\Carbon::now()->subMonths($i);
            $availableMonths[] = [
                'value' => $month->format('Y-m'),
                'label' => $month->format('F Y'),
            ];
        }

        return view('super-admin.statistics', compact(
            'adminStats',
            'permissionStats',
            'overallStats',
            'monthlyStats',
            'monthlyChartData',
            'availableMonths',
            'filterMonth'
        ));
    }

    /**
     * Print statistics report
     */
    public function statisticsPrint(Request $request)
    {
        // Get filter month (default: current month, format: YYYY-MM)
        $filterMonth = $request->input('month', now()->format('Y-m'));

        // Get start and end dates for the filter month
        $startDate = \Carbon\Carbon::createFromFormat('Y-m', $filterMonth)->startOfMonth();
        $endDate = \Carbon\Carbon::createFromFormat('Y-m', $filterMonth)->endOfMonth();

        // Overall totals (all time)
        $overallStats = [
            'totalSales' => \App\Models\SalesDashboard::sum('sales'),
            'totalRevenue' => \App\Models\SalesDashboard::sum('revenue'),
            'totalExpenses' => \App\Models\Transaction::where('type', 'expense')->sum('amount'),
            'totalProfit' => \App\Models\SalesDashboard::sum('gross_profit'),
            'totalPayments' => \App\Models\SalesDashboard::sum('payment'),
            'totalDue' => \App\Models\SalesDashboard::sum('due'),
        ];

        // Calculate Net Profit/Loss
        $overallStats['netProfit'] = $overallStats['totalRevenue'] - $overallStats['totalExpenses'];

        // Monthly filtered stats
        $monthlyStats = [
            'sales' => \App\Models\SalesDashboard::whereBetween('date', [$startDate, $endDate])->sum('sales'),
            'revenue' => \App\Models\SalesDashboard::whereBetween('date', [$startDate, $endDate])->sum('revenue'),
            'expenses' => \App\Models\Transaction::where('type', 'expense')->whereBetween('date', [$startDate, $endDate])->sum('amount'),
            'profit' => \App\Models\SalesDashboard::whereBetween('date', [$startDate, $endDate])->sum('gross_profit'),
            'payments' => \App\Models\SalesDashboard::whereBetween('date', [$startDate, $endDate])->sum('payment'),
            'due' => \App\Models\SalesDashboard::whereBetween('date', [$startDate, $endDate])->sum('due'),
        ];

        // Get monthly data for the last 12 months (for chart)
        $monthlyChartData = [];
        for ($i = 11; $i >= 0; $i--) {
            $month = \Carbon\Carbon::now()->subMonths($i);
            $monthStart = $month->startOfMonth();
            $monthEnd = $month->endOfMonth();

            $monthlyChartData[] = [
                'month' => $month->format('M Y'),
                'sales' => \App\Models\SalesDashboard::whereBetween('date', [$monthStart, $monthEnd])->sum('sales'),
                'revenue' => \App\Models\SalesDashboard::whereBetween('date', [$monthStart, $monthEnd])->sum('revenue'),
                'expenses' => \App\Models\Transaction::where('type', 'expense')->whereBetween('date', [$monthStart, $monthEnd])->sum('amount'),
                'profit' => \App\Models\SalesDashboard::whereBetween('date', [$monthStart, $monthEnd])->sum('gross_profit'),
            ];
        }

        return view('super-admin.statistics-print', compact(
            'overallStats',
            'monthlyStats',
            'monthlyChartData',
            'filterMonth'
        ));
    }
}
