<?php

namespace App\Http\Controllers\Manager;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\QcApproval;
use App\Models\RouteCardProcess;
use App\Models\RouteCard;

class ManagerQualityController extends Controller
{
    // Show the QC Kanban board (blade view)
    public function qualityControlBoard($routeCard)
    {
        $routeCard = \App\Models\RouteCard::findOrFail($routeCard);
        return view('manager.quality.qualitycontrol', compact('routeCard'));
    }

    public function qcManagement()
    {
        // "Show only Projects which are assigned as started in Production"
        $routeCards = \App\Models\RouteCard::whereIn('status', ['In Production', 'in_production'])
            ->with(['processes' => function ($q) {
                // Eager load QC approvals for performance
                $q->with('qcApprovals');
            }])
            ->orderByDesc('updated_at')
            ->get();

        return view('manager.quality.qc_management', compact('routeCards'));
    }

    public function updateQCStatus(Request $request, $id)
    {
        $qc = QcApproval::find($id);
        if (!$qc) {
            return response()->json(['success' => false, 'message' => 'QC record not found.']);
        }

        $oldStatus = $qc->status;
        $newStatus = strtolower(str_replace(' ', '_', $request->input('status')));

        // Valid transitions
        $allowedTransitions = [
            'pending' => ['in_progress', 'rejected'],
            'in_progress' => ['completed', 'rejected'],
            'completed' => ['approved', 'rejected'],
            'rejected' => ['pending'], // Rework submitted?
        ];
        
        // Skip validation for now to allow flexible testing, or uncomment above.

        // Update QC Approval status
        $qc->status = $newStatus;
        $qc->save();

        if ($newStatus === 'approved') {
             // Sync Process Status based on QC Stage
            $process = $qc->process;
            if ($process) {
                if ($qc->stage === 'after') {
                    $process->status = 'completed';
                    $process->save();
                }
                // 'before' and 'during' don't auto-complete the process, they unlock steps.
            }
        } elseif ($newStatus === 'rejected') {
            // Trigger Rework
             $process = $qc->process;
             if ($process) {
                 $process->status = 'rework';
                 $process->save();
             }
        }

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



    // Return all QC approval data for Kanban and table
    // Controller: qualityControlData
    public function qualityControlData($routeCard)
    {
        $statusMap = [
            'pending' => 'Pending',
            'in_progress' => 'In Progress',
            'completed' => 'Completed',
            'approved' => 'Approved',
        ];

        // Only fetch the specific RouteCard and its QC approvals
        $rc = \App\Models\RouteCard::with(['processes.qcApprovals'])->findOrFail($routeCard);

        $data = [];
        foreach ($rc->processes as $process) {
            foreach ($process->qcApprovals as $qc) {
                $code = strtolower($qc->status);
                $display = $statusMap[$code] ?? ucfirst($qc->status);

                $data[] = [
                    'id' => $qc->id,
                    'customer' => $rc->company_name ?? '',
                    'project_no' => $rc->route_no ?? '',
                    'material_no' => $rc->material_no ?? '',
                    'part_no' => $process->process ?? '',
                    'document_value' => $process->drawing_no ?? '',
                    'status' => $display,
                    'status_code' => $code,
                ];
            }
        }
        return response()->json($data);
    }
}
