<?php

namespace App\Http\Controllers\Supervisor;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\Production;
use App\Models\Purchase;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ApprovalController extends Controller
{
    public function index()
    {
        // Statistik untuk dashboard summary
        // CATATAN: Order approval dilakukan oleh Admin, bukan Supervisor
        // Supervisor hanya approve Production Planning dan Purchase
        $stats = [
            // Pending Productions (Planning & Completion)
            'pending_planning_count' => Production::where('planning_status', 'pending_approval')->count(),
            'pending_completion_count' => Production::where('completion_status', 'pending_approval')->count(),
            'total_productions' => Production::where(function($query) {
                $query->where('planning_status', 'pending_approval')
                      ->orWhere('completion_status', 'pending_approval');
            })->count(),
            
            // Pending Purchases
            'pending_purchases_count' => Purchase::where('status', 'pending')->count(),
        ];

        return view('supervisor.approvals.index', compact('stats'));
    }

    public function orders()
    {
        // Hanya tampilkan orders dengan status 'menunggu' yang perlu di-approve
        $orders = Order::with(['product', 'user'])
            ->where('order_status', 'menunggu')
            ->latest()
            ->paginate(20);
        
        return view('supervisor.approvals.orders', compact('orders'));
    }

    public function approveOrder(Request $request, $order)
    {
        $request->validate([
            'feedback' => 'nullable|string|max:1000',
        ]);

        $order = Order::findOrFail($order);
        
        $order->update([
            'order_status' => 'diterima'
        ]);

        // Buat production jika order diterima (gunakan firstOrCreate untuk mencegah duplikasi)
        if ($order->order_status === 'diterima') {
            \App\Models\Production::firstOrCreate(
                ['order_id' => $order->id],
                [
                    'product_id' => $order->product_id,
                    'quantity' => $order->quantity,
                    'status' => 'menunggu',
                    'planning_status' => 'planning',
                ]
            );
        }

        return back()->with('success', 'Order #' . $order->id . ' berhasil diapprove. Production akan dibuat otomatis.');
    }

    public function approveProduction($production)
    {
        // Logic ini akan di-handle di ProductionController
        return back()->with('success', 'Production berhasil diapprove');
    }

    public function approvePurchase(Request $request, $purchase)
    {
        $request->validate([
            'feedback' => 'nullable|string|max:1000',
        ]);

        $purchase = Purchase::with('items')->findOrFail($purchase);
        
        DB::beginTransaction();
        try {
            // Update status purchase
            $purchase->update([
                'status' => 'approved',
                'approved_at' => now(),
                'approved_by' => Auth::id(),
                'supervisor_feedback' => $request->feedback,
            ]);

            // Update stock untuk setiap item di purchase
            foreach ($purchase->items as $purchaseItem) {
                $quantity = $purchaseItem->quantity;
                $itemId = $purchaseItem->item_id;
                
                // Gunakan item_type dari purchaseItem untuk menentukan material atau sparepart
                if ($purchaseItem->item_type === 'material') {
                    $material = \App\Models\Material::find($itemId);
                    if ($material) {
                        $material->increment('stock', $quantity);
                    }
                } elseif ($purchaseItem->item_type === 'sparepart') {
                    $sparepart = \App\Models\Sparepart::find($itemId);
                    if ($sparepart) {
                        $sparepart->increment('stock', $quantity);
                    }
                }
            }

            DB::commit();
            return back()->with('success', 'Purchase #' . $purchase->id . ' berhasil diapprove dan stock telah diperbarui.');
        } catch (\Exception $e) {
            DB::rollBack();
            \Illuminate\Support\Facades\Log::error('Purchase Approval Error: ' . $e->getMessage());
            return back()->with('error', 'Gagal menyetujui purchase: ' . $e->getMessage());
        }
    }

    public function rejectOrder(Request $request, $order)
    {
        $request->validate([
            'feedback' => 'required|string|max:1000',
        ]);

        $order = Order::findOrFail($order);
        
        $order->update([
            'order_status' => 'ditolak'
        ]);

        return back()->with('success', 'Order #' . $order->id . ' ditolak.');
    }

    public function rejectPurchase(Request $request, $purchase)
    {
        $request->validate([
            'feedback' => 'required|string|max:1000',
        ]);

        $purchase = Purchase::findOrFail($purchase);
        
        $purchase->update([
            'status' => 'rejected',
            'supervisor_feedback' => $request->feedback,
        ]);

        return back()->with('success', 'Purchase #' . $purchase->id . ' ditolak.');
    }
}






