<?php

namespace App\Http\Controllers\Teknisi;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ProductInquiry;
use App\Services\NotificationService;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;
use App\Models\Material;
use App\Models\Sparepart;

class QuotationController extends Controller
{
    public function index()
    {
        $inquiries = ProductInquiry::with(['product', 'supervisor'])
            ->where('status', 'teknisi_review')
            ->orderBy('is_read', 'asc') // Unread di atas
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        // Statistik
        $totalInquiries = ProductInquiry::where('status', 'teknisi_review')->count();
        $unreadCount = ProductInquiry::where('status', 'teknisi_review')
            ->where('is_read', false)
            ->count();
        $readCount = ProductInquiry::where('status', 'teknisi_review')
            ->where('is_read', true)
            ->count();

        // Dropdown sumber data seperti di admin create production
        $materials = Material::orderBy('name')->get(['id','name','unit','price','stock']);
        $spareparts = Sparepart::orderBy('name')->get(['id','name','unit','price','stock']);
        
        return view('teknisi.quotations.index', compact('inquiries','materials','spareparts','totalInquiries','unreadCount','readCount'));
    }

    public function markAsRead($id)
    {
        try {
            $inquiry = ProductInquiry::findOrFail($id);
            
            // Validasi: hanya bisa mark as read jika status teknisi_review
            if ($inquiry->status !== 'teknisi_review') {
                return response()->json([
                    'success' => false,
                    'message' => 'Hanya penawaran dengan status teknisi_review yang bisa ditandai sebagai dibaca.',
                ], 422);
            }
            
            $inquiry->update(['is_read' => true]);

            if (request()->ajax() || request()->wantsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Penawaran ditandai sebagai dibaca.',
                ]);
            }

            return redirect()->back()->with('success', 'Penawaran sudah ditandai sebagai dibaca.');
        } catch (\Exception $e) {
            if (request()->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Error: ' . $e->getMessage(),
                ], 500);
            }
            return redirect()->back()->with('error', 'Terjadi kesalahan: ' . $e->getMessage());
        }
    }

    public function estimate(Request $request, $id)
    {
        $request->validate([
            'estimated_days' => 'required|integer|min:1',
            'labor_cost' => 'required|numeric|min:0',
            'materials_breakdown' => 'nullable', // JSON string [{name,qty,unit,unit_cost}]
            'spareparts_breakdown' => 'nullable', // JSON string [{name,qty,unit,unit_cost}]
            'teknisi_note' => 'nullable|string|max:1000',
        ]);

        $inquiry = ProductInquiry::findOrFail($id);

        // Parse breakdown JSON
        $materials = json_decode($request->materials_breakdown ?: '[]', true) ?: [];
        $spareparts = json_decode($request->spareparts_breakdown ?: '[]', true) ?: [];

        $materialsTotal = 0;
        foreach ($materials as &$m) {
            $qty = isset($m['qty']) ? (float)$m['qty'] : 0;
            $unitCost = isset($m['unit_cost']) ? (float)$m['unit_cost'] : 0;
            $m['total_cost'] = $qty * $unitCost;
            $materialsTotal += $m['total_cost'];
        }

        $sparepartsTotal = 0;
        foreach ($spareparts as &$s) {
            $qty = isset($s['qty']) ? (float)$s['qty'] : 0;
            $unitCost = isset($s['unit_cost']) ? (float)$s['unit_cost'] : 0;
            $s['total_cost'] = $qty * $unitCost;
            $sparepartsTotal += $s['total_cost'];
        }

        $labor = (float)$request->labor_cost;
        $totalCost = $materialsTotal + $sparepartsTotal + $labor;

        // Usulan teknisi mengikuti total biaya internal (tanpa margin tambahan)
        $engineerSuggested = $totalCost;

        $inquiry->update([
            'estimated_days' => $request->estimated_days,
            'labor_cost' => $labor,
            'materials_breakdown' => $materials,
            'spareparts_breakdown' => $spareparts,
            'materials_total_cost' => $materialsTotal,
            'spareparts_total_cost' => $sparepartsTotal,
            'labor_cost_total' => $labor,
            'total_cost' => $totalCost,
            'engineer_suggested_price' => $engineerSuggested,
            'teknisi_note' => $request->teknisi_note,
            'teknisi_id' => auth()->id(),
            'teknisi_estimated_at' => now(),
            'status' => 'admin_review', // Admin review dulu, lalu kirim ke user untuk approval sebelum ke supervisor
            'is_read' => false, // Set is_read = false agar admin mendapat notifikasi
        ]);

        // Notifikasi admin via email (ringkas)
        try {
            Mail::send('emails.teknisi-estimate', [ 'inquiry' => $inquiry ], function ($mail) use ($inquiry) {
                $mail->to(config('mail.from.address'), 'Admin')
                    ->subject('Estimasi Teknisi Siap Ditinjau - ' . ($inquiry->product->product_title ?? 'Produk'))
                    ->from(config('mail.from.address'), config('mail.from.name'));
            });
        } catch (\Exception $e) { }

        // Kirim notifikasi ke admin setelah teknisi memberikan estimasi
        try {
            $notificationService = new NotificationService();
            $notificationService->notifyTeknisiEstimateSubmitted($inquiry->fresh());
            // Notifikasi ke admin bahwa estimasi teknisi sudah siap untuk direview dan dikirim ke user
            $notificationService->notifyInquiryStatusChanged($inquiry->fresh(), 'teknisi_review', 'admin_review');
        } catch (\Exception $e) {
            Log::error('Failed to send admin notification after teknisi estimate: ' . $e->getMessage());
        }

        return back()->with('success', 'Estimasi pengerjaan berhasil disimpan. Admin akan melakukan review dan mengirim penawaran ke customer.');
    }

    public function materialsSearch(Request $request)
    {
        $q = trim($request->get('q', ''));
        $items = Material::query()
            ->when($q, function ($qb) use ($q) {
                $qb->where('name', 'like', "%{$q}%")
                   ->orWhere('code', 'like', "%{$q}%")
                   ->orWhere('supplier', 'like', "%{$q}%");
            })
            ->orderBy('name')
            ->limit(15)
            ->get(['id','name','code','unit','price','stock','image_path']);

        return response()->json([
            'data' => $items->map(function($m){
                return [
                    'id' => $m->id,
                    'name' => $m->name,
                    'code' => $m->code,
                    'unit' => $m->unit,
                    'unit_price' => (float) $m->price,
                    'stock' => (float) $m->stock,
                    'image_url' => $m->image_path ? asset('storage/materials/'.$m->image_path) : asset('images/no-image.png'),
                ];
            }),
        ]);
    }

    public function sparepartsSearch(Request $request)
    {
        $q = trim($request->get('q', ''));
        $items = Sparepart::query()
            ->when($q, function ($qb) use ($q) {
                $qb->where('name', 'like', "%{$q}%")
                   ->orWhere('code', 'like', "%{$q}%")
                   ->orWhere('brand', 'like', "%{$q}%");
            })
            ->orderBy('name')
            ->limit(15)
            ->get(['id','name','code','unit','price','stock','image_path']);

        return response()->json([
            'data' => $items->map(function($s){
                return [
                    'id' => $s->id,
                    'name' => $s->name,
                    'code' => $s->code,
                    'unit' => $s->unit,
                    'unit_price' => (float) $s->price,
                    'stock' => (float) $s->stock,
                    'image_url' => $s->image_path ? asset('uploads/spareparts/'.$s->image_path) : asset('images/no-image.png'),
                ];
            }),
        ]);
    }
}





