<?php

namespace App\Http\Controllers\Api;

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

class SupervisorMobileController extends Controller
{
    /**
     * MENGAMBIL DAFTAR PESANAN YANG TERTUNGGU (OVERLIMIT / CREDIT HOLD)
     */
    public function getCreditApprovals(Request $request)
    {
        $user = $request->user();

        // Validasi Otorisasi: Hanya Supervisor Sales yang boleh mengakses
        if ($user->role !== 'supervisor_sales' && $user->role !== 'owner') {
            return response()->json(['success' => false, 'message' => 'Akses ditolak. Fitur ini khusus untuk Supervisor.'], 403);
        }

        try {
            // Ambil SO yang statusnya ditahan karena limit kredit di cabang supervisor tersebut
            $orders = DB::table('sales_orders')
                ->where('status', 'credit_hold')
                ->where('branch_id', $user->branch_id)
                ->orderBy('created_at', 'desc')
                ->get()
                ->map(function($order) {
                    return [
                        'id' => $order->id,
                        'so_number' => $order->so_number,
                        'customer_name' => $order->customer_name,
                        'grand_total' => (float) $order->grand_total,
                        'payment_method' => $order->payment_method,
                        'status' => $order->status,
                        'created_at' => $order->created_at,
                    ];
                });

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

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

    /**
     * MEMPROSES OTORISASI (APPROVE / REJECT) DENGAN VALIDASI PIN/PASSWORD
     */
    public function processCreditApproval(Request $request)
    {
        $request->validate([
            'sales_order_id' => 'required|exists:sales_orders,id',
            'action' => 'required|in:approve,reject',
            'security_pin' => 'required'
        ]);

        $user = $request->user();

        // 1. Validasi PIN atau Password Supervisor (Tanda Tangan Digital)
        if (!Hash::check($request->security_pin, $user->password)) {
            return response()->json([
                'success' => false, 
                'message' => 'Otorisasi ditolak: PIN / Password yang Anda masukkan salah.'
            ], 400);
        }

        DB::beginTransaction();
        try {
            $so = DB::table('sales_orders')->where('id', $request->sales_order_id)->lockForUpdate()->first();
            
            if (!$so || $so->status !== 'credit_hold') {
                throw new \Exception("Data Sales Order tidak valid atau sudah diproses sebelumnya.");
            }

            if ($so->branch_id !== $user->branch_id && $user->role !== 'owner') {
                throw new \Exception("Otorisasi ditolak: Dokumen ini bukan dari cabang Anda.");
            }

            if ($request->action === 'approve') {
                // APPROVE: Loloskan ke antrean Gudang (pending)
                DB::table('sales_orders')->where('id', $so->id)->update([
                    'status' => 'pending',
                    'note' => $so->note . " | [APPROVED BY: {$user->name}]",
                    'updated_at' => Carbon::now()
                ]);
            } else {
                // REJECT: Batalkan pesanan (void) dan kembalikan stok yang di-reserve (ditahan)
                DB::table('sales_orders')->where('id', $so->id)->update([
                    'status' => 'void',
                    'note' => $so->note . " | [REJECTED BY: {$user->name}]",
                    'updated_at' => Carbon::now()
                ]);

                // Logika Enterprise: Melepaskan kembali (release) stok reserved ke Gudang
                $items = DB::table('sales_order_items')->where('sales_order_id', $so->id)->get();
                
                foreach ($items as $item) {
                    $product = DB::table('products')->where('id', $item->product_id)->first();
                    
                    if ($product) {
                        $multiplier = 1;
                        $uName = strtoupper(trim($item->unit_name));
                        
                        if ($uName === strtoupper(trim($product->buy_unit ?? $product->satuan_besar ?? ''))) $multiplier = $product->conversion_factor ?? 1;
                        elseif ($uName === strtoupper(trim($product->unit_3_name ?? $product->satuan_l3 ?? ''))) $multiplier = $product->conversion_3_qty ?? 1;
                        elseif ($uName === strtoupper(trim($product->unit_4_name ?? $product->satuan_l4 ?? ''))) $multiplier = $product->conversion_4_qty ?? 1;
                        
                        $baseQtyToRelease = (float)$item->qty * (float)$multiplier;

                        DB::table('product_stocks')
                            ->where('branch_id', $so->branch_id)
                            ->where('product_id', $product->id)
                            ->update([
                                'reserved_qty' => DB::raw("GREATEST(0, reserved_qty - {$baseQtyToRelease})")
                            ]);
                    }
                }
            }

            DB::commit();
            return response()->json([
                'success' => true,
                'message' => $request->action === 'approve' ? 'Pesanan berhasil disetujui.' : 'Pesanan telah ditolak dan stok dikembalikan.'
            ], 200);

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