<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Sale;
use App\Models\Purchase;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function index()
    {
        if (Auth::user()->role === 'admin') {
            return redirect('/admin/dashboard');
        }

        $branch = Auth::user()->branch ?? 'Cabang 1';
        $today = Carbon::today()->toDateString();

        // 1. Total Penjualan Hari Ini (IDR)
        $totalSalesToday = Sale::where('branch', $branch)
            ->whereDate('date', $today)
            ->sum('total_price');

        // 2. Total Transaksi Hari Ini (Count)
        $transactionCountToday = Sale::where('branch', $branch)
            ->whereDate('date', $today)
            ->count();

        // 3. Total Pengeluaran Hari Ini (IDR) - From Purchases
        $totalPurchasesToday = Purchase::where('branch', $branch)
            ->whereDate('date', $today)
            ->sum('total_price');

        // 4. Aktivitas Terbaru
        $recentSales = Sale::where('branch', $branch)
            ->latest()
            ->take(5)
            ->get()
            ->map(function ($item) {
                $item->type = 'Penjualan';
                $item->badge = 'badge-success';
                return $item;
            });

        $recentPurchases = Purchase::where('branch', $branch)
            ->latest()
            ->take(5)
            ->get()
            ->map(function ($item) {
                $item->type = 'Pembelian'; // Fixed from 'Pengeluaran' for consistency
                $item->badge = 'badge-danger';
                return $item;
            });

        $activities = $recentSales->concat($recentPurchases)
            ->sortByDesc('created_at')
            ->take(5);

        return view('dashboard', compact(
            'totalSalesToday',
            'transactionCountToday',
            'totalPurchasesToday',
            'activities'
        ));
    }

    public function adminIndex()
    {
        if (Auth::user()->role !== 'admin') {
            return redirect('/dashboard');
        }

        $today = Carbon::today()->toDateString();

        // 1. Total Omzet Semua Cabang
        $totalOmzetAll = Sale::whereDate('date', $today)->sum('total_price');

        // 2. Total Pengeluaran Semua Cabang
        $totalExpensesAll = Purchase::whereDate('date', $today)->sum('total_price');

        // 3. Laba Bersih
        $netProfit = $totalOmzetAll - $totalExpensesAll;

        // 4. Cabang Aktif
        $branchCount = 3; // Static as per current design or count unique branches

        // 5. Rata-rata per Cabang
        $averageSales = $branchCount > 0 ? $totalOmzetAll / $branchCount : 0;

        // 6. Data Grafik Mingguan (7 hari terakhir)
        $weeklyLabels = [];
        $branch1Data = [];
        $branch2Data = [];
        $branch3Data = [];

        for ($i = 6; $i >= 0; $i--) {
            $date = Carbon::today()->subDays($i);
            $weeklyLabels[] = $date->translatedFormat('D');
            
            $branch1Data[] = Sale::where('branch', 'Cabang 1')->whereDate('date', $date->toDateString())->sum('total_price');
            $branch2Data[] = Sale::where('branch', 'Cabang 2')->whereDate('date', $date->toDateString())->sum('total_price');
            $branch3Data[] = Sale::where('branch', 'Cabang 3')->whereDate('date', $date->toDateString())->sum('total_price');
        }

        // 7. Omzet per Cabang (Untuk Bar Chart)
        $branchOmzet = [
            Sale::where('branch', 'Cabang 1')->sum('total_price'),
            Sale::where('branch', 'Cabang 2')->sum('total_price'),
            Sale::where('branch', 'Cabang 3')->sum('total_price'),
        ];
        
        $branchProfit = [
            $branchOmzet[0] - Purchase::where('branch', 'Cabang 1')->sum('total_price'),
            $branchOmzet[1] - Purchase::where('branch', 'Cabang 2')->sum('total_price'),
            $branchOmzet[2] - Purchase::where('branch', 'Cabang 3')->sum('total_price'),
        ];

        return view('admin.dashboard', compact(
            'totalOmzetAll',
            'totalExpensesAll',
            'netProfit',
            'branchCount',
            'averageSales',
            'weeklyLabels',
            'branch1Data',
            'branch2Data',
            'branch3Data',
            'branchOmzet',
            'branchProfit'
        ));
    }
}
