<?php

namespace App\Http\Controllers\Api;

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

class ReportController extends Controller
{
    public function pnl(Request $request)
    {
        $validated = $request->validate([
            'store_id' => 'required|exists:stores,id',
        ]);

        try {
            // KUNCI: Cek apakah user boleh melihat fitur laporan PnL
            $this->checkFeatureAccess($request, $validated['store_id'], 'pnl_report', 'can_view');

            $storeId = $validated['store_id'];

            $totalIncome = TransactionLedger::where('store_id', $storeId)
                            ->where('type', 'income')
                            ->sum('amount');

            $totalExpense = TransactionLedger::where('store_id', $storeId)
                            ->where('type', 'expense')
                            ->sum('amount');

            $netProfit = $totalIncome - $totalExpense;

            $details = TransactionLedger::select('category', DB::raw('SUM(amount) as total'))
                            ->where('store_id', $storeId)
                            ->groupBy('category')
                            ->get();

            // KUNCI MUTLAK: Tarik data pengeluaran dan gabungkan (JOIN) dengan tabel suppliers
            $supplierExpenses = \App\Models\PurchaseHistory::select(
                                'suppliers.name as supplier_name', 
                                DB::raw('SUM(purchase_histories.total_cost) as total')
                            )
                            ->leftJoin('suppliers', 'purchase_histories.supplier_id', '=', 'suppliers.id')
                            ->where('purchase_histories.store_id', $storeId)
                            ->groupBy('suppliers.name')
                            ->get();

            return response()->json([
                'status' => 'success',
                'message' => 'Data Laba/Rugi berhasil ditarik.',
                'data' => [
                    'total_income'      => $totalIncome,
                    'total_expense'     => $totalExpense,
                    'net_profit'        => $netProfit,
                    'details'           => $details,
                    'supplier_expenses' => $supplierExpenses // Alirkan data ini ke Frontend
                ]
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'status'  => 'error',
                'message' => $e->getMessage()
            ], 400);
        }
    }

    private function checkFeatureAccess($request, $storeId, $feature, $action)
    {
        $user = $request->user();
        if (!$user) {
            throw new \Exception('Sesi tidak valid. Harap login kembali.');
        }

        $storeUser = DB::table('store_user')
            ->where('store_id', $storeId)
            ->where('user_id', $user->id)
            ->first();

        if (!$storeUser) {
            throw new \Exception('Anda tidak terdaftar di toko ini.');
        }

        if ($storeUser->role === 'owner') {
            return true;
        }

        $permission = DB::table('store_role_permissions')
            ->where('store_id', $storeId)
            ->where('role', $storeUser->role)
            ->where('feature', $feature)
            ->first();

        if (!$permission || !$permission->{$action}) {
            throw new \Exception("Akses ditolak. Jabatan Anda tidak punya izin {$action} pada fitur {$feature}.");
        }

        return true;
    }
}