<?php

namespace App\Http\Controllers\Api;

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

class PurchaseReportController extends Controller
{
    /**
     * 1. LAPORAN PURCHASE ORDER (PO)
     */
    public function poReport(Request $request)
    {
        $user = $request->user();
        // PERBAIKAN ENTERPRISE: Amankan scope cabang
        $branchId = ($user && $user->role !== 'owner') ? $user->branch_id : $request->query('branch_id');

        $startDate = $request->query('start_date', Carbon::now()->startOfMonth()->toDateString());
        $endDate = $request->query('end_date', Carbon::now()->endOfMonth()->toDateString());

        $data = DB::table('purchases')
            ->join('suppliers', 'purchases.supplier_id', '=', 'suppliers.id')
            ->whereBetween('purchases.po_date', [$startDate, $endDate])
            ->when(!empty($branchId) && $branchId !== 'all' && $branchId !== 'null', function ($query) use ($branchId) {
                return $query->where('purchases.branch_id', $branchId);
            })
            ->select(
                'purchases.po_number',
                'purchases.po_date',
                'suppliers.name as supplier_name',
                'purchases.status',
                'purchases.grand_total',
                'purchases.dp_amount'
            )
            ->orderBy('purchases.po_date', 'asc')
            ->get();

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

    /**
     * 2. LAPORAN PENERIMAAN BARANG (SURAT JALAN SUPPLIER)
     */
    public function receiptReport(Request $request)
    {
        $user = $request->user();
        $branchId = ($user && $user->role !== 'owner') ? $user->branch_id : $request->query('branch_id');

        $startDate = $request->query('start_date', Carbon::now()->startOfMonth()->toDateString());
        $endDate = $request->query('end_date', Carbon::now()->endOfMonth()->toDateString());

        $data = DB::table('purchase_receipts')
            ->join('purchases', 'purchase_receipts.purchase_id', '=', 'purchases.id')
            ->join('suppliers', 'purchases.supplier_id', '=', 'suppliers.id')
            ->whereBetween('purchase_receipts.receipt_date', [$startDate, $endDate])
            ->when(!empty($branchId) && $branchId !== 'all' && $branchId !== 'null', function ($query) use ($branchId) {
                // Filter menggunakan branch_id dari tabel pembelian (purchases)
                return $query->where('purchases.branch_id', $branchId);
            })
            ->select(
                'purchase_receipts.receipt_number',
                'purchase_receipts.receipt_date',
                'purchase_receipts.supplier_delivery_number as surat_jalan',
                'purchases.po_number',
                'suppliers.name as supplier_name'
            )
            ->orderBy('purchase_receipts.receipt_date', 'asc')
            ->get();

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

    /**
     * 3. ANALISA UMUR HUTANG (ACCOUNT PAYABLE AGING REPORT) 
     */
    public function apAgingReport(Request $request)
    {
        $user = $request->user();
        $branchId = ($user && $user->role !== 'owner') ? $user->branch_id : $request->query('branch_id');
        $today = Carbon::now();

        $query = DB::table('purchases')
            ->join('suppliers', 'purchases.supplier_id', '=', 'suppliers.id')
            ->where('purchases.status', 'invoiced')
            ->whereIn('purchases.payment_status', ['pending', 'partial', 'unpaid'])
            ->when(!empty($branchId) && $branchId !== 'all' && $branchId !== 'null', function ($q) use ($branchId) {
                return $q->where('purchases.branch_id', $branchId);
            })
            ->select(
                'purchases.id',
                'purchases.invoice_number',
                'purchases.due_date',
                'purchases.grand_total',
                'purchases.paid_amount',
                'purchases.dp_amount',
                'suppliers.name as supplier_name'
            )
            ->get();

        $purchaseIds = $query->pluck('id')->toArray();
        $pendingGiros = DB::table('debt_payments')
            ->whereIn('purchase_id', $purchaseIds)
            ->where('payment_type', 'giro')
            ->where('giro_status', 'pending')
            ->select('purchase_id', DB::raw('SUM(amount) as total_pending'))
            ->groupBy('purchase_id')
            ->pluck('total_pending', 'purchase_id');

        $agingData = [];

        foreach ($query as $row) {
            $pendingGiro = $pendingGiros[$row->id] ?? 0;
            $actualPaid = max((float)$row->paid_amount, (float)$row->dp_amount);
            $sisaHutang = (float)$row->grand_total - $actualPaid - (float)$pendingGiro;

            if ($sisaHutang <= 0) continue; 

            $dueDate = Carbon::parse($row->due_date);
            $daysOverdue = $today->diffInDays($dueDate, false); 

            $category = 'Belum Jatuh Tempo';
            if ($daysOverdue < 0) {
                $absDays = abs($daysOverdue);
                if ($absDays <= 30) {
                    $category = 'Overdue 1-30 Hari';
                } elseif ($absDays <= 60) {
                    $category = 'Overdue 31-60 Hari';
                } else {
                    $category = 'Overdue > 60 Hari (Kritis)';
                }
            }

            $agingData[] = [
                'invoice_number' => $row->invoice_number,
                'supplier_name'  => $row->supplier_name,
                'due_date'       => $row->due_date,
                'sisa_hutang'    => $sisaHutang,
                'kategori_umur'  => $category,
                'hari_lewat'     => $daysOverdue < 0 ? abs($daysOverdue) : 0
            ];
        }

        usort($agingData, function($a, $b) {
            return $b['hari_lewat'] <=> $a['hari_lewat'];
        });

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

    /**
     * 4. LAPORAN PEMBAYARAN KAS KELUAR (PAYMENT REPORT)
     */
    public function paymentReport(Request $request)
    {
        $user = $request->user();
        $branchId = ($user && $user->role !== 'owner') ? $user->branch_id : $request->query('branch_id');

        $startDate = $request->query('start_date', Carbon::now()->startOfMonth()->toDateString());
        $endDate = $request->query('end_date', Carbon::now()->endOfMonth()->toDateString());

        $data = DB::table('debt_payments')
            ->join('purchases', 'debt_payments.purchase_id', '=', 'purchases.id')
            ->join('suppliers', 'purchases.supplier_id', '=', 'suppliers.id')
            ->join('accounts', 'debt_payments.account_id', '=', 'accounts.id')
            ->whereBetween('debt_payments.payment_date', [$startDate, $endDate])
            ->when(!empty($branchId) && $branchId !== 'all' && $branchId !== 'null', function ($q) use ($branchId) {
                return $q->where('purchases.branch_id', $branchId);
            })
            ->select(
                'debt_payments.payment_date',
                'purchases.invoice_number',
                'suppliers.name as supplier_name',
                'debt_payments.payment_type',
                'accounts.name as bank_name',
                'debt_payments.amount',
                'debt_payments.giro_status'
            )
            ->orderBy('debt_payments.payment_date', 'asc')
            ->get();

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

    /**
     * 5. LAPORAN RETUR PEMBELIAN
     */
    public function returnReport(Request $request)
    {
        $user = $request->user();
        $branchId = ($user && $user->role !== 'owner') ? $user->branch_id : $request->query('branch_id');

        $startDate = $request->query('start_date', Carbon::now()->startOfMonth()->toDateString());
        $endDate = $request->query('end_date', Carbon::now()->endOfMonth()->toDateString());

        $data = DB::table('purchase_returns')
            ->join('purchases', 'purchase_returns.purchase_id', '=', 'purchases.id')
            ->join('suppliers', 'purchase_returns.supplier_id', '=', 'suppliers.id')
            ->whereBetween('purchase_returns.return_date', [$startDate, $endDate])
            ->when(!empty($branchId) && $branchId !== 'all' && $branchId !== 'null', function ($q) use ($branchId) {
                return $q->where('purchases.branch_id', $branchId);
            })
            ->select(
                'purchase_returns.return_number',
                'purchase_returns.return_date',
                'purchases.po_number',
                'suppliers.name as supplier_name',
                'purchase_returns.return_type',
                'purchase_returns.total_amount'
            )
            ->orderBy('purchase_returns.return_date', 'asc')
            ->get();

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

    /**
     * 6. FUNGSI DRILL-DOWN DETAILS (POPUP ITEM BARANG)
     */
    public function getReportDetails(Request $request, $type, $ref)
    {
        $user = $request->user();
        $branchId = ($user && $user->role !== 'owner') ? $user->branch_id : null;

        try {
            $items = [];
            
            if ($type === 'po' || $type === 'invoice') {
                $column = $type === 'po' ? 'po_number' : 'invoice_number';
                
                // PERBAIKAN ENTERPRISE: Amankan pencarian dokumen lintas cabang
                $purchase = DB::table('purchases')
                    ->where($column, $ref)
                    ->when(!empty($branchId) && $branchId !== 'all' && $branchId !== 'null', function ($q) use ($branchId) {
                        return $q->where('branch_id', $branchId);
                    })
                    ->first();
                    
                if (!$purchase) throw new \Exception('Dokumen tidak ditemukan atau Anda tidak memiliki akses ke cabang dokumen ini.');

                $items = DB::table('purchase_items')
                    ->join('products', 'purchase_items.product_id', '=', 'products.id')
                    ->where('purchase_items.purchase_id', $purchase->id)
                    ->select(
                        'purchase_items.*', 
                        'products.name as product_name', 
                        'products.variant_name', 
                        'products.sku as product_code'
                    )
                    ->get();

            } elseif ($type === 'receipt') {
                $receipt = DB::table('purchase_receipts')
                    ->join('purchases', 'purchase_receipts.purchase_id', '=', 'purchases.id')
                    ->where('purchase_receipts.receipt_number', $ref)
                    ->when(!empty($branchId) && $branchId !== 'all' && $branchId !== 'null', function ($q) use ($branchId) {
                        return $q->where('purchases.branch_id', $branchId);
                    })
                    ->select('purchase_receipts.*') // Ambil data receipt utamanya saja
                    ->first();
                    
                if (!$receipt) throw new \Exception('Dokumen tidak ditemukan atau Anda tidak memiliki akses.');

                $items = DB::table('purchase_receipt_items')
                    ->join('products', 'purchase_receipt_items.product_id', '=', 'products.id')
                    ->where('purchase_receipt_items.purchase_receipt_id', $receipt->id)
                    ->select(
                        'purchase_receipt_items.*', 
                        'products.name as product_name', 
                        'products.variant_name', 
                        'products.sku as product_code'
                    )
                    ->get();

            } elseif ($type === 'return') {
                $return = DB::table('purchase_returns')
                    ->join('purchases', 'purchase_returns.purchase_id', '=', 'purchases.id')
                    ->where('purchase_returns.return_number', $ref)
                    ->when(!empty($branchId) && $branchId !== 'all' && $branchId !== 'null', function ($q) use ($branchId) {
                        return $q->where('purchases.branch_id', $branchId);
                    })
                    ->select('purchase_returns.*')
                    ->first();
                    
                if (!$return) throw new \Exception('Dokumen tidak ditemukan atau Anda tidak memiliki akses.');

                $items = DB::table('purchase_return_items')
                    ->join('products', 'purchase_return_items.product_id', '=', 'products.id')
                    ->where('purchase_return_items.purchase_return_id', $return->id)
                    ->select(
                        'purchase_return_items.*', 
                        'products.name as product_name', 
                        'products.variant_name', 
                        'products.sku as product_code'
                    )
                    ->get();
            }

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

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