<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\RouteCard;
use App\Models\RouteCardProcess;
use App\Models\QcApproval;
use App\Models\EmployeeDetails;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class SuperAdminProductionController extends Controller
{
    /**
     * Show the production board for a Route Card.
     */
    public function productionBoard($rcId)
    {
        $routeCard = RouteCard::with([
            'processes.qcApprovals',
            // 'processes.operator' // Not needed for this quick fix
        ])->findOrFail($rcId);

        $employees = \App\Models\EmployeeDetails::pluck('name', 'id'); // [id => name]
        $skus = \App\Models\SkuMaster::select('id', 'item_name', 'current_stock')->get();

        return view('superadmin.manufacturing.production_board', compact('routeCard', 'employees', 'skus'));
    }

    /**
     * Start a process (actual production start).
     */
    /**
     * Start a process (actual production start).
     * Logic:
     * 1. Check if 'Before' QC exists. If no, create it and set status to 'qc_before'.
     * 2. If 'Before' QC is pending, returned error.
     * 3. If 'Before' QC is approved, allow start (set status 'in_progress').
     */
    public function startProcess(Request $request, $processId)
    {
        $process = RouteCardProcess::findOrFail($processId);

        // Dependency Check
        if ($process->previous_process_id) {
            $prev = RouteCardProcess::find($process->previous_process_id);
            if ($prev && $prev->status != 'approved') {
                return response()->json(['error' => 'Previous process not completely approved yet.'], 422);
            }
        }

        // 1. Initial State -> Request Before QC
        if ($process->status == 'pending') {
            // Create 'Before' QC if not exists
            $qc = $process->qcApprovals()->where('stage', 'before')->first();
            if (!$qc) {
                $process->qcApprovals()->create([
                    'level' => 1,
                    'stage' => 'before', // NEW
                    'status' => 'pending'
                ]);
            }
            $process->status = 'qc_before'; 
            $process->operator = $request->operator ?? auth()->id();
            $process->save();
            return response()->json(['success' => true, 'message' => 'Before-Process QC Requested', 'process' => $process, 'status' => 'qc_before']);
        }

        // 2. QC Before Phase
        if ($process->status == 'qc_before') {
            $qc = $process->qcApprovals()->where('stage', 'before')->latest()->first();
            if ($qc && $qc->status == 'pending') {
                return response()->json(['error' => 'Waiting for Before-Production QC Approval.'], 422);
            }
            if ($qc && $qc->status == 'rejected') {
                return response()->json(['error' => 'Before-Production QC Rejected. Please fix and re-request.'], 422);
            }
            if ($qc && $qc->status == 'approved') {
                // QC Passed, NOW start production
                $process->actual_start = now();
                $process->status = 'in_progress';
                $process->operator = $request->operator ?? auth()->id();
                $process->save();
                return response()->json(['success' => true, 'message' => 'Production Started', 'process' => $process, 'status' => 'in_progress']);
            }
        }
        
        // 3. Already Started?
         if ($process->status == 'in_progress') {
             return response()->json(['error' => 'Process already in progress.'], 422);
         }

        return response()->json(['error' => 'Invalid status transition form ' . $process->status], 422);
    }

    /**
     * End a process.
     * Logic:
     * 1. Move status to 'qc_after'.
     * 2. Create 'After' QC record.
     */
    public function endProcess(Request $request, $processId)
    {
        $process = RouteCardProcess::findOrFail($processId);

        if ($process->status != 'in_progress') {
             return response()->json(['error' => 'Process must be In Progress to end.'], 422);
        }

        if ($process->actual_end) {
            return response()->json(['error' => 'Process already active ended.'], 422);
        }

        // Create 'After' QC
        $qc = $process->qcApprovals()->where('stage', 'after')->where('status', 'pending')->first();
        if (!$qc) {
            $process->qcApprovals()->create([
                'level' => 1,
                'stage' => 'after', // NEW
                'status' => 'pending'
            ]);
        }

        $process->actual_end = now();
        $process->status = 'qc_after'; // Waiting for final approval
        $process->save();

        return response()->json(['success' => true, 'message' => 'Process Ended. Sent for Final QC.', 'process' => $process, 'status' => 'qc_after']);
    }

    // Trigger a random check during production
    public function requestDuringQC(Request $request, $processId)
    {
        $process = RouteCardProcess::findOrFail($processId);
        if ($process->status != 'in_progress') {
             return response()->json(['error' => 'Process must be In Progress to request Random QC.'], 422);
        }

        $process->qcApprovals()->create([
            'level' => 1,
            'stage' => 'during',
            'status' => 'pending'
        ]);

        return response()->json(['success' => true, 'message' => 'Random QC Requested']);
    }


    public function approveQC(Request $request, $qcId)
    {
        $qc = QcApproval::find($qcId);
        if (!$qc) return response()->json(['error' => 'QC not found'], 404);

        $qc->status = 'approved';
        $qc->approved_by = auth()->id();
        $qc->approved_at = now();
        $qc->remarks = $request->remarks;
        $qc->save();

        // Update Process Status based on Stage
        $process = $qc->process;
        if ($process) {
            if ($qc->stage == 'before') {
                // Unblock start button, effectively. Status stays 'qc_before' but frontend sees 'approved' qc.
                // Or we can move to 'ready_to_start'? Let's keep 'qc_before' for simplicity, frontend checks last qc status.
                // Actually, let's auto-start? No, operator should start.
                // So no process status change needed? But user needs to know.
                // Let's set process status to 'before_qc_approved' so frontend knows to show "Start" button again?
                // Or just use the QC record status in frontend logic.
                // Reverting logic: Start button simply checks startProcess again.
            }
            if ($qc->stage == 'after') {
                // Final approval -> Process Complete
                // Check if ALL 'after' QCs are approved (in case multiple were generated?)
                // Usually one.
                $process->status = 'approved'; 
                $process->save();
            }
             if ($qc->stage == 'during') {
                // Just log it. Status remains 'in_progress'.
            }
        }

        return response()->json(['success' => true]);
    }

    public function rejectQC(Request $request, $qcId)
    {
        $qc = QcApproval::find($qcId);
        if (!$qc) return response()->json(['error' => 'QC not found'], 404);

        $qc->status = 'rejected';
        $qc->approved_by = auth()->id();
        $qc->approved_at = now();
        $qc->remarks = $request->remarks;
        $qc->save();

        $process = $qc->process;
        if ($process) {
            $process->status = 'rework';
            $process->save();
        }

        return response()->json(['success' => true]);
    }
    
    // Machine Breakdown Log
    public function logMachineBreakdown(Request $request) {
        $request->validate([
            'machine_id' => 'required',
            'reason' => 'required',
            'start_time' => 'required|date'
        ]);
        
        // Lookup machine ID if the input is a string (Name)
        $machineId = $request->machine_id;
        if (!is_numeric($machineId)) {
            // Try to find machine by name or custom ID string
            $machine = \App\Models\Machines::where('machine_name', $machineId)
                        ->orWhere('machine_id', $machineId)->first();
            if ($machine) {
                $machineId = $machine->id;
            } else {
                 // Fallback or error? If table requires int, this will fail.
                 // Assuming partial match or just 0 if not found? 
                 // Better to be safe:
                 // return response()->json(['error' => 'Machine not found'], 404);
            }
        }

        \App\Models\MachineLog::create([
            'machine_id' => $machineId,
            'reason' => $request->reason, 
            'start_time' => $request->start_time,
            'reported_by' => auth()->id()
        ]);

        return response()->json(['success' => true]);
    }

    // Material Consumption
    public function consumeMaterial(Request $request)
    {
        $request->validate([
            'sku_id' => 'required|exists:skumaster,id',
            'quantity' => 'required|numeric|min:0.01',
            'process_id' => 'required'
        ]);

        $sku = \App\Models\SkuMaster::find($request->sku_id);
        
        if($sku->current_stock < $request->quantity) {
             return response()->json(['success'=>false, 'message' => 'Insufficient Stock! Available: ' . $sku->current_stock]);
        }

        $sku->current_stock -= $request->quantity;
        $sku->save();

        // Log Movement
        \App\Models\SkuMovement::create([
            'reference' => 'PROD-' . $request->process_id,
            'sku_id' => $sku->id,
            'product' => $sku->item_name,
            'type' => 'outbound',
            'quantity' => $request->quantity,
            'from_location' => 'Inventory',
            'to_location' => 'Production',
            'date' => now(),
            'status' => 'completed',
            'notes' => 'Consumed in Process #' . $request->process_id
        ]);

        return response()->json(['success' => true, 'message' => 'Material Consumed', 'new_stock' => $sku->current_stock]);
    }

    public function inProgressList()
    {
        // Show all route cards currently "in production" (status == 'production' or 'In Production')
        $routeCards = \App\Models\RouteCard::whereIn('status', ['production', 'In Production'])->get();
        return view('superadmin.manufacturing.production_inprogress_list', compact('routeCards'));
    }
}
