<?php

namespace App\Http\Controllers\Admin;

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

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

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

        return view('admin.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')));

        // (Optional) Only allow certain transitions!
        $allowedTransitions = [
            'pending' => ['in_progress'],
            'in_progress' => ['completed'],
            'completed' => ['approved'],
        ];
        if (!isset($allowedTransitions[$oldStatus]) || !in_array($newStatus, $allowedTransitions[$oldStatus])) {
            return response()->json(['success' => false, 'message' => 'Invalid status transition.']);
        }

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

        // Also update related process status
        $process = $qc->process;
        if ($process) {
            $process->status = $newStatus;
            $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 =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);
    }
}
