<?php

namespace App\Http\Controllers\Api;

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

class DeliveryReportController extends Controller
{
    /**
     * Menarik laporan performa pengiriman untuk Driver dan Helper
     * DIKONVERSI KE SATUAN LEVEL 2 (KARTON / DUS)
     */
    public function getPerformanceReport(Request $request)
    {
        try {
            $user = $request->user();

            // Default filter: Bulan ini
            $startDate = $request->query('start_date', Carbon::now()->startOfMonth()->toDateString());
            $endDate = $request->query('end_date', Carbon::now()->endOfMonth()->toDateString());
            
            // PENAMBAHAN: Proteksi Isolasi Laporan Cabang
            // Memaksa admin cabang hanya bisa melihat data armada di cabangnya sendiri
            if ($user && $user->role !== 'owner') {
                $branchId = $user->branch_id;
            } else {
                $branchId = $request->query('branch_id');
            }

            // =========================================================
            // 1. MENGAMBIL & MENGHITUNG DATA DRIVER
            // =========================================================
            $driverQuery = User::where('role', 'driver');
            if ($branchId) {
                $driverQuery->where('branch_id', $branchId);
            }
            $drivers = $driverQuery->get();

            $driverReport = [];
            foreach ($drivers as $driver) {
                // PENAMBAHAN ENTERPRISE: Mengunci query sales ke cabang untuk mencegah kebocoran 
                // data performa jika driver pernah dimutasi dari cabang lain.
                $salesQuery = DB::table('sales')
                    ->where('driver_id', $driver->id)
                    ->where('delivery_status', 'delivered')
                    ->whereBetween(DB::raw('DATE(delivery_date)'), [$startDate, $endDate]);
                    
                if ($branchId) {
                    $salesQuery->where('branch_id', $branchId);
                }
                
                $sales = $salesQuery->get();

                $totalTrips = $sales->count();
                $totalQtyKarton = 0;

                foreach ($sales as $sale) {
                    $items = DB::table('sale_items')
                        ->join('products', 'sale_items.product_id', '=', 'products.id')
                        ->where('sale_items.sale_id', $sale->id)
                        ->select(
                            'sale_items.quantity', 
                            'sale_items.base_conversion_factor', 
                            'products.conversion_factor'
                        )
                        ->get();

                    foreach ($items as $item) {
                        // PERBAIKAN: Menghapus keyword 'clone' yang menyebabkan Fatal Error di PHP
                        // Pastikan operasi matematika berjalan sebagai float/numeric
                        $totalBasePcs = (float)$item->quantity * (float)$item->base_conversion_factor;
                        
                        // Konversi ke Level 2 (Karton)
                        $kartonFactor = $item->conversion_factor > 0 ? $item->conversion_factor : 1;
                        $totalQtyKarton += ($totalBasePcs / $kartonFactor);
                    }
                }

                $driverReport[] = [
                    'id' => $driver->id,
                    'name' => $driver->name,
                    'role' => 'DRIVER',
                    'total_trips' => $totalTrips,
                    'total_qty' => round($totalQtyKarton, 2)
                ];
            }

            // =========================================================
            // 2. MENGAMBIL & MENGHITUNG DATA HELPER
            // =========================================================
            $helperQuery = User::where('role', 'helper');
            if ($branchId) {
                $helperQuery->where('branch_id', $branchId);
            }
            $helpers = $helperQuery->get();

            $helperReport = [];
            foreach ($helpers as $helper) {
                // PENAMBAHAN ENTERPRISE: Mengunci query sales helper ke cabang yang sesuai
                $salesQueryHelper = DB::table('sales')
                    ->where('helper_id', $helper->id)
                    ->where('delivery_status', 'delivered')
                    ->whereBetween(DB::raw('DATE(delivery_date)'), [$startDate, $endDate]);
                    
                if ($branchId) {
                    $salesQueryHelper->where('branch_id', $branchId);
                }
                
                $sales = $salesQueryHelper->get();

                $totalTrips = $sales->count();
                $totalQtyKarton = 0;

                foreach ($sales as $sale) {
                    $items = DB::table('sale_items')
                        ->join('products', 'sale_items.product_id', '=', 'products.id')
                        ->where('sale_items.sale_id', $sale->id)
                        ->select(
                            'sale_items.quantity', 
                            'sale_items.base_conversion_factor', 
                            'products.conversion_factor'
                        )
                        ->get();

                    foreach ($items as $item) {
                        // PERBAIKAN: Menghapus keyword 'clone' untuk menghindari Fatal Error
                        $totalBasePcs = (float)$item->quantity * (float)$item->base_conversion_factor;
                        
                        // Konversi ke Level 2 (Karton)
                        $kartonFactor = $item->conversion_factor > 0 ? $item->conversion_factor : 1;
                        $totalQtyKarton += ($totalBasePcs / $kartonFactor);
                    }
                }

                $helperReport[] = [
                    'id' => $helper->id,
                    'name' => $helper->name,
                    'role' => 'HELPER',
                    'total_trips' => $totalTrips,
                    'total_qty' => round($totalQtyKarton, 2)
                ];
            }

            // Urutkan berdasarkan Qty Karton terbanyak (Kinerja Terbaik)
            usort($driverReport, function($a, $b) { return $b['total_qty'] <=> $a['total_qty']; });
            usort($helperReport, function($a, $b) { return $b['total_qty'] <=> $a['total_qty']; });

            return response()->json([
                'success' => true,
                'period' => [
                    'start' => $startDate,
                    'end' => $endDate
                ],
                'data' => [
                    'drivers' => $driverReport,
                    'helpers' => $helperReport
                ]
            ]);

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