<?php

namespace App\Http\Admin;

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

class AdminController extends Controller
{
    /**
     * Dashboard Admin
     */
   public function dashboard(Request $request)
{
    // Stats hari ini
    $today = DB::table('transactions')
        ->selectRaw('
            COUNT(*) as total_transactions,
            SUM(CASE WHEN payment_status = "PAID" THEN 1 ELSE 0 END) as success_count,
            SUM(CASE WHEN payment_status = "UNPAID" THEN 1 ELSE 0 END) as pending_count,
            SUM(CASE WHEN payment_status = "PAID" THEN total_amount ELSE 0 END) as revenue,
            SUM(CASE WHEN payment_status = "PAID" THEN margin_amount ELSE 0 END) as profit
        ')
        ->first();

    // ✅ NEW: Chart Data (Last 7 Days)
    $chartData = [];
    $chartLabels = [];
    
    for ($i = 6; $i >= 0; $i--) {
        $date = now()->subDays($i);
        $chartLabels[] = $date->format('d M');
        
        $revenue = DB::table('transactions')
            ->whereDate('created_at', $date)
            ->where('payment_status', 'PAID')
            ->sum('total_amount');
        
        $chartData[] = (int) $revenue;
    }
    
    // ✅ NEW: Top Products (This Month)
    $topProducts = DB::table('transactions')
        ->select('product_name')
        ->selectRaw('COUNT(*) as total_orders')
        ->selectRaw('SUM(total_amount) as total_revenue')
        ->where('payment_status', 'PAID')
        ->whereMonth('created_at', now()->month)
        ->groupBy('product_name')
        ->orderByDesc('total_orders')
        ->limit(5)
        ->get();

    // API Balance
    $apiBalance = DB::table('settings')
        ->where('key_name', 'vipreseller_balance')
        ->value('value') ?? 0;

    // Recent transactions
    $recentTransactions = DB::table('transactions')
        ->select(
            'id',
            'invoice_number',
            'product_name',
            'total_amount',
            'status',
            'payment_status',
            'created_at'
        )
        ->orderBy('created_at', 'desc')
        ->limit(10)
        ->get();
    
    // ✅ NEW: AJAX Response for auto-refresh
    if ($request->ajax()) {
        return response()->json([
            'today' => $today,
            'chartData' => $chartData,
            'topProducts' => $topProducts,
        ]);
    }

    return view('account.dashboard', compact(
        'today', 
        'apiBalance', 
        'recentTransactions',
        'chartData',
        'chartLabels',
        'topProducts'
    ));
}

    /**
     * Transactions Management
     */
    public function transactions()
    {
        $transactions = DB::table('transactions')
            ->leftJoin('products', 'transactions.product_id', '=', 'products.id')
            ->select(
                'transactions.*',
                DB::raw('COALESCE(products.name, transactions.product_name, "Unknown Product") as product_name')
            )
            ->orderBy('transactions.created_at', 'desc')
            ->paginate(20);

        return view('admin.transactions.index', compact('transactions'));
    }

    /**
     * Products Management
     */
    public function products()
    {
        $products = DB::table('products')
            ->join('categories', 'products.category_id', '=', 'categories.id')
            ->select('products.*', 'categories.name as category_name')
            ->orderBy('categories.sort_order')
            ->get();

        return view('admin.products.index', compact('products'));
    }

    /**
     * Update Product
     */
    public function updateProduct(Request $request, $id)
    {
        $request->validate([
            'selling_price' => 'required|numeric|min:0'
        ]);

        DB::table('products')
            ->where('id', $id)
            ->update([
                'selling_price' => $request->selling_price,
                'is_active' => $request->has('is_active'),
                'updated_at' => now()
            ]);

        return redirect()->back()->with('success', 'Product updated!');
    }

    /**
     * Sync Prices
     */
    public function syncPrices()
    {
        // Logic sync prices here
        return redirect()->back()->with('success', 'Prices synced!');
    }

    /**
     * Settings
     */
    public function settings()
    {
        $settings = DB::table('settings')->get()->pluck('value', 'key_name');
        return view('admin.settings.index', compact('settings'));
    }

    /**
     * Update Settings
     */
    public function updateSettings(Request $request)
    {
        foreach ($request->except('_token', '_method') as $key => $value) {
            DB::table('settings')
                ->where('key_name', $key)
                ->update(['value' => $value, 'updated_at' => now()]);
        }

        return redirect()->back()->with('success', 'Settings updated!');
    }

    /**
     * Users Management
     */
    public function users()
    {
        $users = DB::table('users')->orderBy('created_at', 'desc')->paginate(20);
        return view('admin.users.index', compact('users'));
    }

    /**
     * Update User
     */
    public function updateUser(Request $request, $id)
    {
        DB::table('users')
            ->where('id', $id)
            ->update([
                'name' => $request->name,
                'email' => $request->email,
                'role' => $request->role,
                'updated_at' => now()
            ]);

        return redirect()->back()->with('success', 'User updated!');
    }
    public function reviews()
{
    $reviews = DB::table('reviews')
        ->join('products', 'reviews.product_id', '=', 'products.id')
        ->join('orders', 'reviews.order_id', '=', 'orders.id')
        ->select('reviews.*', 'products.name as product_name', 'orders.id as order_number')
        ->orderBy('reviews.created_at', 'desc')
        ->paginate(20);
    
    $stats = [
        'total' => DB::table('reviews')->count(),
        'pending' => DB::table('reviews')->where('status', 'pending')->count(),
        'approved' => DB::table('reviews')->where('status', 'approved')->count(),
    ];
    
    return view('admin.reviews', compact('reviews', 'stats'));
}
}