<?php

namespace App\Http\Controllers\Admin;

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 ProductionController 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('admin.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' => 'Already started or not allowed.'], 422);
        }
        if ($process->previous_process_id) {
            $prev = RouteCardProcess::find($process->previous_process_id);
            if ($prev && $prev->status != 'approved') {
                return response()->json(['error' => 'Previous process not approved.'], 422);
            }
        }

        $process->actual_start = now();
        $process->status = 'qc'; // Immediately move to QC
        $process->operator = $request->operator ?? auth()->id();
        $process->save();

        if ($process->qcApprovals()->count() == 0) {
            $process->qcApprovals()->create([
                'level' => 1,
                'status' => 'pending'
            ]);
        }

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


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

        // Allow end process if status is 'qc' or 'approved' (but not already ended)
        if (!in_array($process->status, ['qc', 'approved'])) {
            return response()->json(['error' => 'Process not in QC or Approved stage.'], 422);
        }
        if ($process->actual_end) {
            return response()->json(['error' => 'Process already ended.'], 422);
        }

        // Only allow if all QCs are approved
        $allApproved = $process->qcApprovals()->where('status', 'approved')->count() == $process->qcApprovals()->count();
        if (!$allApproved) {
            return response()->json(['error' => 'QC not approved yet.'], 422);
        }

        $process->actual_end = now();
        $process->status = 'approved'; // Mark as fully approved
        $process->save();

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



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

        if (!$qc) {
            Log::error("Approve QC: QCApproval ID $qcId not found.", ['user_id' => Auth::id()]);
            return response()->json(['error' => 'QC approval not found.'], 404);
        }

        if ($qc->status === 'approved') {
            Log::info("Approve QC: QCApproval $qcId already approved.", ['user_id' => Auth::id()]);
            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->save();

        Log::info("Approve QC: QCApproval $qcId approved by user.", [
            'qc_id' => $qcId,
            'user_id' => Auth::id()
        ]);

        // DO NOT set process status to 'completed' here. Only after endProcess.
        // You may leave this block empty, or notify if you want.

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

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

        if (!$qc) {
            Log::error("Reject QC: QCApproval ID $qcId not found.", ['user_id' => Auth::id()]);
            return response()->json(['error' => 'QC approval not found.'], 404);
        }

        if ($qc->status !== 'pending') {
            Log::warning("Reject QC: QCApproval $qcId already processed.", ['user_id' => Auth::id()]);
            return response()->json(['error' => 'QC already processed.'], 422);
        }

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

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

        Log::info("Reject QC: QCApproval $qcId rejected, process {$process->id} set to rework.", [
            'qc_id' => $qcId,
            'process_id' => $process->id,
            'user_id' => Auth::id()
        ]);

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