<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Sale; 
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use App\Services\AccountingService;

class DeliveryController extends Controller
{
    public function getTasks(Request $request)
    {
        $driver = auth('sanctum')->user();

        $deliveries = Sale::with(['customer', 'items'])
            ->withCount('items as total_items') 
            ->where('driver_id', $driver->id)
            ->whereIn('delivery_status', ['diproses', 'dikirim', 'selesai'])
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json([
            'status' => 'success',
            'data' => $deliveries,
            'driver' => [
                'name' => $driver->name,
                'vehicle' => $driver->vehicle_plate ?? 'Mobil Box'
            ]
        ]);
    }

    public function completeTask(Request $request, $id)
    {
        $driver = auth('sanctum')->user();
        $sale = Sale::find($id);
        
        if ($sale) {
            // PENAMBAHAN: Proteksi Pembajakan Tugas Lintas Supir (API Tampering)
            if ($sale->driver_id !== $driver->id) {
                return response()->json([
                    'status' => 'error', 
                    'message' => 'Akses ditolak: Surat Jalan ini bukan tugas pengiriman Anda.'
                ], 403);
            }

            // PENAMBAHAN: Cegah Double-Click atau Status Bentrok
            if ($sale->delivery_status === 'selesai' || $sale->delivery_status === 'void') {
                return response()->json([
                    'status' => 'error', 
                    'message' => 'Pesanan ini sudah diselesaikan atau dibatalkan sebelumnya.'
                ], 400);
            }

            $sale->delivery_status = 'selesai';
            
            if ($request->has('pod_photo')) $sale->pod_photo = $request->pod_photo;
            if ($request->has('pod_latitude')) $sale->pod_lat = $request->pod_latitude;
            if ($request->has('pod_longitude')) $sale->pod_lng = $request->pod_longitude;
            
            $sale->save();
            
            DB::table('delivery_logs')->insert([
                'sale_id' => $sale->id,
                'sales_order_id' => $sale->sales_order_id,
                'driver_id' => $sale->driver_id,
                'status' => 'delivered',
                'reason' => 'Pesanan telah diterima oleh pelanggan (Via Supir)',
                'latitude' => $request->pod_latitude ?? null,
                'longitude' => $request->pod_longitude ?? null,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now()
            ]);

            return response()->json(['status' => 'success', 'message' => 'Pengiriman selesai!']);
        }
        return response()->json(['status' => 'error', 'message' => 'Pesanan tidak ditemukan.'], 404);
    }

    public function failTask(Request $request, $id)
    {
        DB::beginTransaction();
        try {
            $driver = $request->user();
            $sale = Sale::with('items')->where('id', $id)->lockForUpdate()->first();
            
            if (!$sale) {
                throw new \Exception('Pesanan tidak ditemukan.');
            }

            // PENAMBAHAN: Proteksi Pembajakan Tugas Lintas Supir
            if ($sale->driver_id !== $driver->id) {
                throw new \Exception('Akses ditolak: Surat Jalan ini bukan tugas pengiriman Anda.');
            }

            if ($sale->delivery_status === 'void') {
                throw new \Exception('Gagal: Pesanan ini sudah dibatalkan sebelumnya.');
            }

            $totalCogs = 0; 

            foreach ($sale->items as $item) {
                $qtyToReturn = $item->quantity * ($item->base_conversion_factor ?? 1);

                $stockRecord = \App\Models\ProductStock::where('branch_id', $sale->branch_id)
                            ->where('product_id', $item->product_id)
                            ->first();

                if ($stockRecord) {
                    $stockRecord->quantity += $qtyToReturn;
                    $stockRecord->reserved_qty += $qtyToReturn; 
                    $stockRecord->save();
                } 

                $product = DB::table('products')->where('id', $item->product_id)->first();
                if ($product) {
                    $hpp = (isset($product->average_cost) && $product->average_cost > 0) ? $product->average_cost : ($product->buy_price ?? 0);
                    $totalCogs += ((float)$hpp * $qtyToReturn);
                }

                \App\Models\StockTransaction::create([
                    'branch_id' => $sale->branch_id,
                    'product_id' => $item->product_id,
                    'type' => 'sale_return', 
                    'input_quantity' => $item->quantity, 
                    'input_unit' => $item->unit ?? 'PCS',
                    'actual_quantity' => $qtyToReturn, 
                    'user_id' => $request->user()->id, 
                    'note' => 'Retur Gagal Kirim Supir (Reschedule): ' . $request->reason,
                ]);

                if ($sale->sales_order_id) {
                    DB::table('sales_order_items')
                        ->where('sales_order_id', $sale->sales_order_id)
                        ->where('product_id', $item->product_id)
                        ->update(['qty_delivered' => DB::raw("GREATEST(qty_delivered - " . $item->quantity . ", 0)")]);
                }
            }

            $sale->delivery_status = 'void';
            $sale->payment_status = 'void';
            $sale->save();

            if ($sale->sales_order_id) {
                $hasDeliveredItems = DB::table('sales_order_items')
                    ->where('sales_order_id', $sale->sales_order_id)
                    ->whereRaw('qty_delivered > 0')
                    ->exists();

                DB::table('sales_orders')->where('id', $sale->sales_order_id)->update([
                    'status' => $hasDeliveredItems ? 'partially_delivered' : 'reschedule',
                    'updated_at' => Carbon::now()
                ]);
            }

            DB::table('delivery_logs')->insert([
                'sale_id' => $sale->id,
                'sales_order_id' => $sale->sales_order_id,
                'driver_id' => $sale->driver_id,
                'status' => 'failed_reschedule',
                'reason' => 'Supir lapor gagal: ' . $request->reason,
                'latitude' => $request->latitude ?? null,
                'longitude' => $request->longitude ?? null,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now()
            ]);

            // ====================================================================
            // PERBAIKAN ENTERPRISE: STRICT GL MAPPING VALIDATION (HAPUS HARDCODE ID)
            // ====================================================================
            $accPiutang = AccountingService::getAccountId('receivable_account'); 
            $accPendapatan = AccountingService::getAccountId('sales_revenue_account'); 
            $accPpn = AccountingService::getAccountId('ppn_output_account'); 
            $accHpp = AccountingService::getAccountId('cost_of_goods_sold_account'); 
            $accPersediaan = AccountingService::getAccountId('inventory_account'); 

            if (!$accPiutang || !$accPendapatan || !$accHpp || !$accPersediaan) {
                throw new \Exception("Sistem Gagal: Master Akun Global (Piutang/Pendapatan/HPP/Persediaan) belum dikonfigurasi. Hubungi Admin Pusat.");
            }

            $journalItems = [];
            $pendapatanReverse = $sale->grand_total - ($sale->tax_amount ?? 0);
            
            // 1. Debit Pendapatan
            $journalItems[] = ['account_id' => $accPendapatan, 'debit' => $pendapatanReverse, 'credit' => 0];
            // 2. Debit PPN Keluaran
            if (($sale->tax_amount ?? 0) > 0 && $accPpn) {
                $journalItems[] = ['account_id' => $accPpn, 'debit' => $sale->tax_amount, 'credit' => 0];
            }
            // 3. Debit Persediaan Barang
            $journalItems[] = ['account_id' => $accPersediaan, 'debit' => $totalCogs, 'credit' => 0];
            
            // 4. Kredit Piutang (Menghapus Piutang)
            $journalItems[] = ['account_id' => $accPiutang, 'debit' => 0, 'credit' => $sale->grand_total];
            // 5. Kredit Harga Pokok Penjualan (HPP)
            $journalItems[] = ['account_id' => $accHpp, 'debit' => 0, 'credit' => $totalCogs];

            AccountingService::log([
                'branch_id'   => $sale->branch_id,
                'entry_date'  => Carbon::today()->toDateString(),
                'description' => 'Batal Kirim (Supir)/VOID SJ: ' . $sale->invoice_number,
                'reference'   => $sale->invoice_number . '-VOID',
                'source_type' => 'SALE_RETURN_VOID',
                'user_id'     => $request->user()->id,
                'items'       => $journalItems
            ]);

            DB::commit();
            return response()->json(['status' => 'success', 'message' => 'Pesanan dibatalkan. Stok dan Jurnal Keuangan berhasil direstorasi.']);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error("Driver Fail Task Error: " . $e->getMessage());
            return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }
}