<?php

namespace App\Http\Controllers\Api;

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

class ExecutiveDashboardController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $today = Carbon::today();
        $startOfMonth = Carbon::now()->startOfMonth();

        // PENAMBAHAN: Variabel Scope Cabang
        $branchId = ($user->role !== 'owner') ? $user->branch_id : null;

        // 1. Penjualan Hari Ini (Omset)
        $todaySalesQuery = DB::table('sales')
            ->whereDate('created_at', $today)
            ->where('payment_status', '!=', 'cancelled');
        
        if ($branchId) $todaySalesQuery->where('branch_id', $branchId);
        
        $todaySales = $todaySalesQuery->sum('grand_total');

        // 2. Kalkulasi Piutang Overdue & Top 5 Overdue
        $overdueSalesQuery = DB::table('sales')
            ->leftJoin('debt_payments', 'sales.id', '=', 'debt_payments.sale_id')
            ->select(
                'sales.id', 
                'sales.invoice_number', 
                'sales.customer_name', 
                'sales.grand_total', 
                'sales.due_date', 
                DB::raw('COALESCE(SUM(debt_payments.amount), 0) as paid_amount')
            )
            ->where('sales.payment_status', 'pending')
            ->whereDate('sales.due_date', '<', $today);
            
        if ($branchId) $overdueSalesQuery->where('sales.branch_id', $branchId);
            
        $overdueSales = $overdueSalesQuery->groupBy('sales.id', 'sales.invoice_number', 'sales.customer_name', 'sales.grand_total', 'sales.due_date')
            ->get();

        $overduePiutang = 0;
        $topOverdueList = [];

        foreach ($overdueSales as $sale) {
            $rem = $sale->grand_total - $sale->paid_amount;
            if ($rem > 0) {
                $overduePiutang += $rem;
                $topOverdueList[] = [
                    'toko' => $sale->customer_name ?? 'Pelanggan Umum',
                    'inv' => $sale->invoice_number,
                    'amount' => $rem,
                    'days' => Carbon::parse($sale->due_date)->diffInDays($today)
                ];
            }
        }
        
        usort($topOverdueList, fn($a, $b) => $b['amount'] <=> $a['amount']);
        $topOverdueList = array_slice($topOverdueList, 0, 5);

        // 3. Antrean Pengiriman (Sales Order)
        $pendingDeliveryQuery = DB::table('sales_orders')
            ->whereIn('status', ['pending', 'partially_delivered', 'dikirim']);
        
        if ($branchId) $pendingDeliveryQuery->where('branch_id', $branchId);
        
        $pendingDelivery = $pendingDeliveryQuery->count();

        // 4. Saldo Kas & Bank
        $cashBalanceQuery = DB::table('journal_items')
            // Join ke header jurnal dan akun
            ->join('journal_entries', 'journal_items.journal_entry_id', '=', 'journal_entries.id')
            ->join('accounts', 'journal_items.account_id', '=', 'accounts.id');
            
        if ($branchId) {
            // =========================================================================
            // PERBAIKAN ENTERPRISE: Logika Saldo Buku Besar (GL Balance Logic)
            // =========================================================================
            // Mengambil daftar akun bank valid untuk cabang yang sedang aktif
            $mappedAccountIds = DB::table('branch_accounts')
                ->where('branch_id', $branchId)
                ->where('is_active', 1) // PROTEKSI: Pastikan mapping masih aktif
                ->whereIn('type', ['kas_kecil', 'kas_besar', 'bank_utama', 'bank_operasional'])
                ->pluck('account_id')
                ->toArray();

            if (!empty($mappedAccountIds)) {
                // Filter murni berdasarkan pergerakan di akun yang di-mapping.
                // PERHATIAN: Tidak memfilter journal_entries.branch_id agar transfer Drop Dana dari Pusat
                // tetap terbaca sebagai saldo penambah di Dashboard cabang.
                $cashBalanceQuery->whereIn('journal_items.account_id', $mappedAccountIds);
            } else {
                // Keamanan: Jika mapping cabang belum disetting, pastikan saldo tampil 0 
                $cashBalanceQuery->where('journal_items.account_id', 0);
            }
            // =========================================================================
        } else {
            // Jika eksekutif/owner (Pusat), hitung seluruh aset Kas & Bank (Awalan 10)
            $cashBalanceQuery->where('accounts.code', 'like', '10%');
        }
        
        $cashBalance = $cashBalanceQuery->sum(DB::raw('debit - credit'));

        // 5. Trend Penjualan 7 Hari Terakhir
        $trendQuery = DB::table('sales')
            ->select(DB::raw('DATE(created_at) as date'), DB::raw('SUM(grand_total) as total'))
            ->where('created_at', '>=', Carbon::now()->subDays(6)->startOfDay())
            ->where('payment_status', '!=', 'cancelled');
            
        if ($branchId) $trendQuery->where('branch_id', $branchId);
            
        $trend = $trendQuery->groupBy('date')
            ->orderBy('date', 'ASC')
            ->get();

        // 6. Kinerja Salesman Terbaik Bulan Ini
        $topSalesmenQuery = DB::table('sales')
            ->join('customers', 'sales.customer_id', '=', 'customers.id')
            ->join('salesmen', 'customers.salesman_id', '=', 'salesmen.id')
            ->join('users', 'salesmen.user_id', '=', 'users.id')
            ->select(
                'users.name', 
                'salesmen.area_cakupan as area', 
                DB::raw('SUM(sales.grand_total) as omset')
            )
            ->whereBetween('sales.created_at', [$startOfMonth, Carbon::now()->endOfDay()])
            ->where('sales.payment_status', '!=', 'cancelled');
            
        if ($branchId) $topSalesmenQuery->where('sales.branch_id', $branchId);
            
        $topSalesmenRaw = $topSalesmenQuery->groupBy('salesmen.id', 'users.name', 'salesmen.area_cakupan')
            ->orderByDesc('omset')
            ->limit(5)
            ->get();
        
        $topSalesmen = [];
        foreach ($topSalesmenRaw as $sm) {
            $target = 500000000;
            $pct = min(100, round(($sm->omset / $target) * 100, 2));
            
            $topSalesmen[] = [
                'name' => $sm->name,
                'area' => $sm->area ?? 'Area Umum',
                'omset' => $sm->omset,
                'target_percent' => $pct
            ];
        }

        return response()->json([
            'success' => true,
            'data' => [
                'kpi' => [
                    'today_sales' => $todaySales,
                    'overdue_piutang' => $overduePiutang,
                    'pending_delivery' => $pendingDelivery,
                    'cash_balance' => $cashBalance
                ],
                'trend' => $trend,
                'top_salesmen' => $topSalesmen,
                'top_overdue' => $topOverdueList
            ]
        ]);
    }
}