<?php

namespace App\Http\Controllers\Manager;

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 ManagerProductionController 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]

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

    /**
     * Start a process (actual production start).
     */
    public function startProcess(Request $request, $processId)
    {
        $process = RouteCardProcess::findOrFail($processId);

        if ($process->status !== 'pending') {
            return response()->json(['error' => 'Process already started or completed.'], 422);
        }

        // 1. Strict Gating: Previous process must be COMPLETED & APPROVED
        if ($process->previous_process_id) {
            $prev = RouteCardProcess::find($process->previous_process_id);
            if ($prev && $prev->status != 'approved') {
                return response()->json(['error' => 'Previous process not fully approved yet.'], 422);
            }
        }

        // 2. 3-Stage QC Logic: "Before" Stage
        // Check if "Before" QC exists
        $preQc = $process->qcApprovals()->where('stage', 'before')->first();

        if (!$preQc) {
            // Create PRE-QC entry
            $process->qcApprovals()->create([
                'stage' => 'before',
                'level' => 1,
                'status' => 'pending'
            ]);
            return response()->json(['message' => 'Pre-Process QC Initiated. Waiting for Approval.', 'status' => 'qc_before']);
        }

        if ($preQc->status === 'pending') {
            return response()->json(['error' => 'Pre-Process QC is Pending. Cannot start.'], 422);
        }
        if ($preQc->status === 'rejected') {
            return response()->json(['error' => 'Pre-Process QC Rejected. Check Remarks.'], 422);
        }

        // 3. If Pre-QC is Approved, START Production
        $process->actual_start = now();
        $process->status = 'in_production'; 
        $process->operator = $request->operator ?? auth()->id();
        $process->save();

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

        return response()->json(['success' => true, 'message' => 'Process Started. In-Process QC Initiated.', 'process' => $process]);
    }


    public function endProcess(Request $request, $processId)
    {
        $process = RouteCardProcess::findOrFail($processId);

        if ($process->status !== 'in_production') {
            return response()->json(['error' => 'Process is not in production.'], 422);
        }
        if ($process->actual_end) {
            return response()->json(['error' => 'Process already ended.'], 422);
        }

        // 1. Check "During" QC
        $duringQc = $process->qcApprovals()->where('stage', 'during')->first();
        if (!$duringQc || $duringQc->status !== 'approved') {
            return response()->json(['error' => 'In-Process (During) QC not approved yet.'], 422);
        }

        // 2. Mark End Time & Move to Post-QC
        $process->actual_end = now();
        $process->status = 'qc_check'; // Waiting for Final QC
        $process->save();

        // 3. Initiate "After" QC
        $process->qcApprovals()->create([
            'stage' => 'after',
            'level' => 1,
            'status' => 'pending'
        ]);

        return response()->json(['success' => true, 'message' => 'Process Ended. Post-Process QC Initiated.', 'process' => $process]);
    }



    public function approveQC(Request $request, $qcId)
    {
        $qc = QcApproval::find($qcId);

        if (!$qc) {
            return response()->json(['error' => 'QC approval not found.'], 404);
        }
        if ($qc->status === 'approved') {
            return response()->json(['error' => 'QC already approved.'], 422);
        }

        $qc->status = 'approved';
        $qc->approved_by = auth()->id();
        $qc->approved_at = now();
        $qc->remarks = $request->remarks ?? null;
        $qc->parameters = $request->parameters ?? null; // Save checked values
        $qc->save();

        // Stage-specific logic
        $process = $qc->process;
        if ($qc->stage === 'after') {
            // Final QC Approved -> Process Completed
            $process->status = 'completed'; // or 'approved'
            $process->save();
        } elseif ($qc->stage === 'before') {
            // Unlocks Start
        } elseif ($qc->stage === 'during') {
            // Unlocks End
        }

        Log::info("QC Approved", ['qc_id' => $qcId, 'stage' => $qc->stage]);

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

    public function rejectQC(Request $request, $qcId)
    {
        $qc = QcApproval::find($qcId);

        if (!$qc) {
            return response()->json(['error' => 'QC approval not found.'], 404);
        }

        $qc->status = 'rejected';
        $qc->approved_by = auth()->id();
        $qc->approved_at = now();
        $qc->remarks = $request->remarks ?? null;
        $qc->rejection_reason = $request->rejection_reason ?? 'Quality Standards Not Met';
        $qc->save();

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

        Log::info("QC Rejected", ['qc_id' => $qcId, 'stage' => $qc->stage]);

        return response()->json(['success' => true, 'qc' => $qc]);
    }
    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('manager.manufacturing.production_inprogress_list', compact('routeCards'));
    }

    public function updateMachineOperator(Request $request, $processId)
    {
        $process = RouteCardProcess::findOrFail($processId);
        $process->machine = $request->machine;
        $process->operator = $request->operator;
        // Log reason? Using MachineLog for breakdown, but maybe simple activity log here?
        // User asked for "Reason Logging". Let's assume we log it to a text field or activity log.
        // For now, updating is the key.
        $process->save();
        
        return response()->json(['success' => true, 'message' => 'Resource updated successfully.']);
    }

    public function reportBreakdown(Request $request)
    {
        // $request->machine_id, $request->reason, $request->minutes
        \App\Models\MachineLog::create([
            'machine_id' => $request->machine_id,
            'reason' => $request->reason,
            'reported_by' => auth()->id(),
            'start_time' => now(),
            // 'end_time' => now()->addMinutes($request->minutes) // Optional estimation
        ]);

        return response()->json(['success' => true, 'message' => 'Breakdown reported.']);
    }

    public function viewRouteCard($id)
    {
        $routeCard = RouteCard::with('processes')->findOrFail($id);
        $employees = \App\Models\EmployeeDetails::pluck('name', 'id');
        return view('manager.manufacturing.route_card_view', compact('routeCard', 'employees'));
    }
}
