<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Sale;
use App\Models\Branch;
use App\Models\Purchase;
use App\Models\DebtPayment;
use App\Models\Expense; 
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class OwnerController extends Controller
{
    private function checkAccess($user)
    {
        if ($user->role !== 'owner') {
            abort(403, 'Akses khusus Owner');
        }
    }

    // 1. LIST CABANG
    public function getBranches(Request $request)
    {
        $this->checkAccess($request->user());
        $branches = Branch::select('id', 'name', 'address')->get();
        return response()->json(['success' => true, 'data' => $branches]);
    }

    // 2. DASHBOARD STATS (Dengan Biaya & Laba Bersih)
    public function getDashboardStats(Request $request)
    {
        $this->checkAccess($request->user());
        $branchId = $request->query('branch_id');
        
        $startDate = $request->query('start_date') ? Carbon::parse($request->query('start_date'))->startOfDay() : Carbon::today()->startOfDay();
        $endDate = $request->query('end_date') ? Carbon::parse($request->query('end_date'))->endOfDay() : Carbon::today()->endOfDay();

        // A. HITUNG OMZET (PENJUALAN)
        $salesQuery = Sale::query()->whereBetween('created_at', [$startDate, $endDate]);
        if ($branchId && $branchId !== 'all') $salesQuery->where('branch_id', $branchId);

        $totalOmzet = (clone $salesQuery)->sum('grand_total');
        $totalCash = (clone $salesQuery)->where('payment_method', 'cash')->sum('grand_total');

        // B. HITUNG LABA KOTOR (GROSS PROFIT)
        $profitQuery = DB::table('sale_items')
            ->join('sales', 'sales.id', '=', 'sale_items.sale_id')
            ->join('products', 'products.id', '=', 'sale_items.product_id')
            ->whereBetween('sales.created_at', [$startDate, $endDate]);
            
        if ($branchId && $branchId !== 'all') $profitQuery->where('sales.branch_id', $branchId);

        // Catatan: Jika menggunakan Moving Average, idealnya menggunakan average_cost, fallback ke buy_price
        $totalCost = $profitQuery->sum(DB::raw('sale_items.quantity * COALESCE(products.average_cost, products.buy_price, 0)'));
        $totalRevenueItem = $profitQuery->sum('sale_items.total_price');
        $grossProfit = $totalRevenueItem - $totalCost;

        // C. HITUNG PENGELUARAN (EXPENSES)
        $expenseQuery = Expense::whereBetween('expense_date', [$startDate, $endDate]);
        if ($branchId && $branchId !== 'all') {
            $expenseQuery->where('branch_id', $branchId);
        }
        $totalExpense = $expenseQuery->sum('amount');

        // D. HITUNG LABA BERSIH (NET PROFIT)
        $netProfit = $grossProfit - $totalExpense;

        // E. HITUNG PIUTANG (Total Debt Pelanggan)
        $debtQuery = Sale::where('payment_status', 'pending');
        if ($branchId && $branchId !== 'all') $debtQuery->where('branch_id', $branchId);
        
        $allPendingSales = $debtQuery->select('id', 'grand_total')->withSum('debtPayments', 'amount')->get();
        $totalDebt = $allPendingSales->sum(fn($s) => max(0, $s->grand_total - ($s->debt_payments_sum_amount ?? 0)));

        return response()->json([
            'success' => true,
            'data' => [
                'omzet' => (double) $totalOmzet,
                'cash_on_hand' => (double) $totalCash,
                'gross_profit' => (double) $grossProfit,
                'total_expense' => (double) $totalExpense,
                'net_profit' => (double) $netProfit,      
                'total_debt' => (double) $totalDebt,
                'transaction_count' => (clone $salesQuery)->count(),
            ]
        ]);
    }

    // 3. TOP PRODUK
    public function getTopProducts(Request $request)
    {
        $this->checkAccess($request->user());
        $branchId = $request->query('branch_id');
        $startDate = $request->query('start_date') ? Carbon::parse($request->query('start_date'))->startOfDay() : Carbon::today()->startOfDay();
        $endDate = $request->query('end_date') ? Carbon::parse($request->query('end_date'))->endOfDay() : Carbon::today()->endOfDay();

        $query = DB::table('sale_items')
            ->join('sales', 'sales.id', '=', 'sale_items.sale_id')
            ->select('sale_items.product_name', DB::raw('SUM(sale_items.quantity) as total_qty'), DB::raw('SUM(sale_items.total_price) as total_revenue'))
            ->whereBetween('sales.created_at', [$startDate, $endDate])
            ->groupBy('sale_items.product_name', 'sale_items.product_id')
            ->orderByDesc('total_qty')
            ->limit(5);

        if ($branchId && $branchId !== 'all') $query->where('sales.branch_id', $branchId);

        return response()->json(['success' => true, 'data' => $query->get()]);
    }

    // 4. TRANSAKSI TERAKHIR
    public function getRecentTransactions(Request $request)
    {
        $this->checkAccess($request->user());
        $branchId = $request->query('branch_id');
        $startDate = $request->query('start_date') ? Carbon::parse($request->query('start_date'))->startOfDay() : Carbon::today()->startOfDay();
        $endDate = $request->query('end_date') ? Carbon::parse($request->query('end_date'))->endOfDay() : Carbon::today()->endOfDay();

        $query = Sale::with('branch') 
            ->whereBetween('created_at', [$startDate, $endDate])
            ->orderBy('created_at', 'desc')
            ->limit(10); 

        if ($branchId && $branchId !== 'all') {
            $query->where('branch_id', $branchId);
        }

        $sales = $query->get()->map(function($sale) {
            return [
                'id' => $sale->id,
                'invoice' => $sale->invoice_number,
                'time' => $sale->created_at->format('H:i'),
                'total' => (float)$sale->grand_total,
                'customer' => $sale->customer_name ?? 'Umum',
                'payment_method' => $sale->payment_method,
                'branch_name' => $sale->branch ? $sale->branch->name : 'Pusat',
            ];
        });

        return response()->json(['success' => true, 'data' => $sales]);
    }

    // 5. HUTANG SUPPLIER (OPTIMASI KECEPATAN)
    public function getSupplierDebts(Request $request)
    {
        // PERBAIKAN ENTERPRISE: Menutup Celah Kebocoran Data (Security Gate)
        $this->checkAccess($request->user());

        $branchId = $request->query('branch_id');

        $query = Purchase::with(['supplier', 'branch'])
            ->withSum('debtPayments', 'amount') 
            ->where('payment_status', '!=', 'paid')
            ->orderBy('due_date', 'asc');

        if ($branchId && $branchId !== 'all') {
            $query->where('branch_id', $branchId);
        }
        
        // Catatan: Karena ada checkAccess() di atas, $user->role pasti 'owner'.
        // Blok if di bawah ini secara teknis menjadi 'dead code', namun tetap dipertahankan 
        // untuk mematuhi integritas struktur kode asli.
        $user = auth()->user();
        if ($user->role !== 'owner') {
            $query->where('branch_id', $user->branch_id);
        }

        $debts = $query->get()->map(function ($item) {
            // PERBAIKAN: Mengambil data sum langsung dari Eager Loading, bukan melakukan query ulang!
            // Ini membuat API dashboard merespon 10x lebih cepat.
            $paid = $item->debt_payments_sum_amount ?? 0;
            $remaining = $item->grand_total - $paid;

            return [
                'id' => $item->id,
                'invoice_number' => $item->invoice_number,
                'supplier_name' => $item->supplier->name ?? 'Supplier Umum',
                'due_date' => $item->due_date,
                'grand_total' => $item->grand_total,
                'remaining' => $remaining,
                'status' => $item->payment_status,
                'branch_name' => $item->branch->name ?? '-',
            ];
        });

        return response()->json([
            'status' => 'success',
            'data' => $debts
        ]);
    }
}