<?php

namespace App\Http\Controllers\SuperAdmin;

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

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

    public function qcManagement()
    {
        // List only route cards that have QC processes or all route cards as needed
        $routeCards = \App\Models\RouteCard::withCount(['processes as qc_count' => function ($q) {
            $q->whereHas('qcApprovals');
        }])->orderBy('created_at', 'desc')->get();

        return view('superadmin.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.']);
        }

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

        // Allow 'approved' and 'rejected' transitions from any active state for manual override if needed, 
        // or enforce strict flow. Let's allow manual action from modal.
        
        $qc->status = $newStatus;
        if($remarks) $qc->remarks = $remarks;
        
        if (in_array($newStatus, ['approved', 'rejected'])) {
            $qc->approved_by = auth()->id();
            $qc->approved_at = now();
        }
        $qc->save();

        // Process Status Sync
        $process = $qc->process;
        if ($process) {
            if ($newStatus == 'rejected') {
                // If QC rejected -> Process needs Rework
                $process->status = 'rework';
                $process->save();
            } elseif ($newStatus == 'approved') {
                 // If 'After' QC approved -> Process Approved (Completed)
                 if ($qc->stage == 'after') {
                     $process->status = 'approved';
                     $process->save();
                 }
                 // If 'Before' QC approved -> Process ready for In Progress
                 // (We leave it as 'qc_before' or move to 'in_progress'? 
                 //  Better to let user click Start again to confirm moving to in_progress/actual start time.)
            }
        }

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

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

        // 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->project_no ?? '',  // Use project_no from RC
                    'material_no' => $rc->material_no ?? '',
                    'part_no' => $process->process ?? '',
                    'document_value' => $process->drawing_no ?? '',
                    'status' => $display,
                    'status_code' => $code,
                    'stage' => $qc->stage ?? 'before', // Pass stage to frontend
                    'approved_by' => $qc->approver ? $qc->approver->name : '-', // Assuming relationship exists or nullable
                    'remarks' => $qc->remarks
                ];
            }
        }
        return response()->json($data);
    }
}
