<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class HandoverController extends Controller
{
    /**
     * Display orders ready for handover
     */
    public function index(Request $request)
    {
        $query = Order::with(['user', 'product', 'production', 'sale'])
            ->whereHas('production', function ($q) {
                // Produksi selesai (status = selesai) atau completion sudah approved
                $q->where(function($sub) {
                    $sub->where('status', 'selesai')
                        ->orWhere('completion_status', 'approved');
                });
            });

        // Filter by status - jika status diisi, filter berdasarkan status tersebut
        // Jika tidak, ambil semua status yang valid (termasuk null yang akan dianggap sebagai pending)
        if ($request->filled('status') && in_array($request->status, ['pending', 'ready', 'delivered', 'confirmed'])) {
            if ($request->status === 'pending') {
                // Untuk pending, include yang null juga
                $query->where(function($q) {
                    $q->where('handover_status', 'pending')
                      ->orWhereNull('handover_status');
                });
            } else {
                $query->where('handover_status', $request->status);
            }
        } else {
            // Jika tidak ada filter status, ambil semua status yang valid
            $query->where(function($q) {
                $q->whereIn('handover_status', ['pending', 'ready', 'delivered', 'confirmed'])
                  ->orWhereNull('handover_status');
            });
        }

        // Search - perbaiki dengan grouping yang benar
        if ($request->filled('search') && trim($request->search) !== '') {
            $searchTerm = trim($request->search);
            $query->where(function ($q) use ($searchTerm) {
                $q->where('customer_name', 'like', "%{$searchTerm}%")
                  ->orWhere('customer_email', 'like', "%{$searchTerm}%");
                // Tambahkan pencarian ID jika search adalah numerik
                if (is_numeric($searchTerm)) {
                    $q->orWhere('id', $searchTerm);
                } else {
                    $q->orWhere('id', 'like', "%{$searchTerm}%");
                }
            });
        }

        $itemsPerPage = (int) Setting::get('items_per_page', 10);
        $orders = $query->latest()->paginate($itemsPerPage)->withQueryString();

        return view('admin.handover.index', compact('orders'));
    }

    /**
     * Show handover form for specific order
     */
    public function show(Order $order)
    {
        $order->load(['user', 'product', 'production.teknisi', 'production.supervisor', 'sale']);

        // Validasi: Pastikan produksi sudah selesai (status = selesai dan completion_status = approved)
        if (!$order->production) {
            return back()->withErrors(['production' => 'Order ini belum memiliki data produksi.']);
        }

        if ($order->production->status !== 'selesai') {
            return back()->withErrors(['production' => 'Produksi belum selesai. Status produksi: ' . $order->production->status_label]);
        }

        if ($order->production->completion_status !== 'approved') {
            return back()->withErrors(['production' => 'Penyelesaian produksi belum disetujui supervisor.']);
        }

        return view('admin.handover.show', compact('order'));
    }

    /**
     * Prepare handover (set status to ready)
     */
    public function prepare(Request $request, Order $order)
    {
        // Validasi: Pastikan produksi sudah selesai
        if (!$order->production) {
            return back()->withErrors(['production' => 'Order ini belum memiliki data produksi.']);
        }

        if ($order->production->status !== 'selesai') {
            return back()->withErrors(['production' => 'Produksi belum selesai. Status produksi: ' . $order->production->status_label]);
        }

        if ($order->production->completion_status !== 'approved') {
            return back()->withErrors(['production' => 'Penyelesaian produksi belum disetujui supervisor.']);
        }

        $request->validate([
            'handover_notes' => 'nullable|string|max:2000',
            'handover_photos' => 'nullable|array',
            'handover_photos.*' => 'image|mimes:jpeg,png,jpg,webp|max:5120',
        ]);

        $photos = [];

        // Handle photo uploads
        if ($request->hasFile('handover_photos')) {
            foreach ($request->file('handover_photos') as $photo) {
                $path = $photo->store('handover', 'uploads');
                $photos[] = $path;
            }
        }

        $order->update([
            'handover_status' => 'ready',
            'handover_notes' => $request->handover_notes,
            'handover_photos' => $photos,
        ]);

        \Log::info('Handover prepared by admin', [
            'order_id' => $order->id,
            'admin_id' => Auth::id(),
            'admin_name' => Auth::user()->name,
            'handover_status' => 'ready',
        ]);

        // Kirim notifikasi ke user
        try {
            $notificationService = new \App\Services\NotificationService();
            $notificationService->notifyHandoverReady($order->fresh());
        } catch (\Exception $e) {
            \Log::error('Failed to send handover ready notification: ' . $e->getMessage());
        }

        return back()->with('success', 'Order siap untuk diserahkan ke customer.');
    }

    /**
     * Complete handover (deliver to customer)
     */
    public function deliver(Request $request, Order $order)
    {
        if ($order->handover_status !== 'ready') {
            return back()->withErrors(['status' => 'Order belum siap untuk diserahkan.']);
        }

        // Validasi tambahan: Pastikan produksi sudah selesai
        if (!$order->production || $order->production->status !== 'selesai') {
            return back()->withErrors(['production' => 'Produksi belum selesai. Tidak dapat melanjutkan serah terima.']);
        }

        $request->validate([
            'handover_notes' => 'nullable|string|max:2000',
            'additional_photos' => 'nullable|array',
            'additional_photos.*' => 'image|mimes:jpeg,png,jpg,webp|max:5120',
        ]);

        $photos = $order->handover_photos ?? [];

        // Handle additional photo uploads
        if ($request->hasFile('additional_photos')) {
            foreach ($request->file('additional_photos') as $photo) {
                $path = $photo->store('handover', 'uploads');
                $photos[] = $path;
            }
        }

        $order->update([
            'handover_status' => 'delivered',
            'handover_at' => now(),
            'handover_by' => Auth::id(),
            'handover_notes' => $request->handover_notes ?? $order->handover_notes,
            'handover_photos' => $photos,
        ]);

        \Log::info('Handover delivered by admin', [
            'order_id' => $order->id,
            'production_id' => $order->production?->id,
            'admin_id' => Auth::id(),
            'admin_name' => Auth::user()->name,
            'handover_at' => now()->toDateTimeString(),
            'customer_email' => $order->customer_email,
            'confirmation_link' => route('user.orders.confirm-delivery', $order),
        ]);

        // Kirim notifikasi ke user
        try {
            $notificationService = new \App\Services\NotificationService();
            $notificationService->notifyHandoverDelivered($order->fresh());
        } catch (\Exception $e) {
            \Log::error('Failed to send handover delivered notification: ' . $e->getMessage());
        }

        return back()->with('success', 'Order telah diserahkan ke customer. Menunggu konfirmasi customer.');
    }

    /**
     * Force complete (admin confirms on behalf of customer - emergency case)
     */
    public function forceComplete(Request $request, Order $order)
    {
        if ($order->handover_status !== 'delivered') {
            return back()->withErrors(['status' => 'Order belum diserahkan ke customer.']);
        }

        $request->validate([
            'admin_notes' => 'required|string|max:1000',
        ]);

        $order->update([
            'handover_status' => 'confirmed',
            'customer_confirmed_at' => now(),
            'customer_feedback' => 'Dikonfirmasi oleh admin: ' . $request->admin_notes,
            'status' => 'selesai', // Final payment status
        ]);

        // Reload order untuk mendapatkan data terbaru
        $order->refresh();
        
        // Validasi: Sale hanya dibuat jika status pembayaran = selesai DAN status produksi = selesai
        // Ini memastikan bahwa penjualan hanya terjadi ketika semua proses selesai
        $canCreateSale = $order->status === 'selesai' && 
                        $order->production_status === 'selesai' &&
                        !$order->sale;

        // Buat Sale record jika semua kondisi terpenuhi
        if ($canCreateSale) {
            \App\Models\Sale::create([
                'order_id' => $order->id,
                'product_id' => $order->product_id,
                'user_id' => $order->user_id,
                'quantity' => $order->quantity,
                'unit_price' => $order->price,
                'total_price' => $order->total_price,
                'sale_date' => now(),
                'payment_method' => $order->payment_method,
                'status' => 'selesai',
                'notes' => 'Penjualan selesai - Dikonfirmasi oleh admin (force complete)',
            ]);
            
            // Kirim notifikasi ke admin
            if ($order->production) {
                try {
                    $notificationService = new \App\Services\NotificationService();
                    $notificationService->notifyProductionCompletedAndSold($order->production->fresh());
                } catch (\Exception $e) {
                    \Log::error('Failed to send production completed and sold notification: ' . $e->getMessage());
                }
            }
            
            \Log::info('Sale created after admin force complete handover', [
                'order_id' => $order->id,
                'production_status' => $order->production_status,
                'payment_status' => $order->status,
            ]);
        } else {
            \Log::warning('Sale not created after admin force complete - conditions not met', [
                'order_id' => $order->id,
                'payment_status' => $order->status,
                'production_status' => $order->production_status,
                'sale_exists' => $order->sale ? true : false,
            ]);
        }

        // Kirim notifikasi ke admin
        try {
            $notificationService = new \App\Services\NotificationService();
            $notificationService->notifyHandoverConfirmed($order->fresh());
        } catch (\Exception $e) {
            \Log::error('Failed to send handover confirmed notification: ' . $e->getMessage());
        }

        return redirect()->route('admin.handover.index')
            ->with('success', 'Order telah dikonfirmasi selesai oleh admin. Sale record telah dibuat.');
    }

    /**
     * Print handover document
     */
    public function printDocument(Order $order)
    {
        $order->load(['user', 'product', 'production.teknisi', 'handoverBy']);

        $pdf = \PDF::loadView('admin.handover.print', compact('order'));
        
        return $pdf->download("serah-terima-order-{$order->id}.pdf");
    }
}

