<?php

namespace App\Http\Controllers\Modules\Manufacturing;

use App\Http\Controllers\Controller;
use App\Http\Traits\HasRoleViews;
use App\Models\QualityControl;
use App\Models\QcApproval;
use App\Models\RouteCard;
use App\Services\Manufacturing\QualityControlService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

/**
 * Unified Quality Controller
 *
 * Handles quality control management for all roles.
 * Reference: SuperAdminQualityController
 */
class QualityController extends Controller
{
    use HasRoleViews;

    protected QualityControlService $qualityService;

    public function __construct(QualityControlService $qualityService)
    {
        $this->qualityService = $qualityService;
    }

    /**
     * Display the QC page
     */
    public function index()
    {
        $routeCards = RouteCard::where('status', 'completed')->get();
        return $this->roleView('quality.qc_management', compact('routeCards'));
    }

    /**
     * Display the QC management page
     * Alias for backward compatibility
     */
    public function qcManagement()
    {
        return $this->index();
    }

    /**
     * Get QC data for DataTable (AJAX)
     */
    public function list(): JsonResponse
    {
        $qcRecords = QualityControl::with('routeCard')->orderBy('id', 'desc')->get();

        $data = [];
        foreach ($qcRecords as $i => $qc) {
            $data[] = [
                'slno' => $i + 1,
                'qc_no' => $qc->qc_no,
                'route_card_no' => $qc->routeCard ? $qc->routeCard->route_card_no : '',
                'inspection_date' => $qc->inspection_date ? date('d-m-Y', strtotime($qc->inspection_date)) : '',
                'inspector' => $qc->inspector,
                'status' => $qc->status,
                'result' => $qc->result,
            ];
        }

        return response()->json(['data' => $data]);
    }

    /**
     * Display the QC creation form
     */
    public function create()
    {
        $routeCards = RouteCard::where('status', 'completed')
            ->whereNotIn('id', QualityControl::pluck('route_card_id'))
            ->get();

        $qcNo = $this->qualityService->generateQcNumber();

        return $this->roleView('quality.create', compact('routeCards', 'qcNo'));
    }

    /**
     * Store a newly created QC record
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'qc_no' => 'required|string|unique:quality_controls,qc_no',
            'route_card_id' => 'required|exists:route_cards,id',
            'inspection_date' => 'required|date',
            'inspector' => 'required|string|max:255',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        try {
            DB::beginTransaction();

            $qc = QualityControl::create([
                'qc_no' => $request->qc_no,
                'route_card_id' => $request->route_card_id,
                'inspection_date' => $request->inspection_date,
                'inspector' => $request->inspector,
                'parameters' => $request->parameters ? json_encode($request->parameters) : null,
                'result' => $request->result ?? 'pending',
                'remarks' => $request->remarks,
                'status' => 'pending',
            ]);

            DB::commit();

            return $this->redirectToRoute('quality.index')
                ->with('success', 'Quality Control record created successfully.');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('QC Store Error: ' . $e->getMessage());
            return back()->with('error', 'Failed to create QC record.');
        }
    }

    /**
     * Display the specified QC record
     */
    public function show(int $id)
    {
        $qc = QualityControl::with('routeCard')->findOrFail($id);
        return $this->roleView('quality.show', compact('qc'));
    }

    /**
     * Display the edit form
     */
    public function edit(int $id)
    {
        $qc = QualityControl::with('routeCard')->findOrFail($id);
        $routeCards = RouteCard::where('status', 'completed')->get();

        return $this->roleView('quality.edit', compact('qc', 'routeCards'));
    }

    /**
     * Update the specified QC record
     */
    public function update(Request $request, int $id)
    {
        $qc = QualityControl::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'inspection_date' => 'required|date',
            'inspector' => 'required|string|max:255',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        try {
            $qc->update([
                'inspection_date' => $request->inspection_date,
                'inspector' => $request->inspector,
                'parameters' => $request->parameters ? json_encode($request->parameters) : $qc->parameters,
                'result' => $request->result ?? $qc->result,
                'remarks' => $request->remarks,
            ]);

            return $this->redirectToRoute('quality.index')
                ->with('success', 'Quality Control record updated successfully.');

        } catch (\Exception $e) {
            Log::error('QC Update Error: ' . $e->getMessage());
            return back()->with('error', 'Failed to update QC record.');
        }
    }

    /**
     * Remove the specified QC record
     */
    public function destroy(int $id): JsonResponse
    {
        // Authorization check - only SuperAdmin and Manager can delete
        if (!$this->isSuperAdmin() && !$this->isManager()) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized. Only SuperAdmin and Manager can delete QC records.'
            ], 403);
        }

        try {
            $qc = QualityControl::findOrFail($id);

            // Prevent deletion of approved QC records by non-SuperAdmin
            if ($qc->status === 'approved' && !$this->isSuperAdmin()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Cannot delete approved QC records. Contact SuperAdmin.'
                ], 403);
            }

            $qc->delete();

            return response()->json(['success' => true, 'message' => 'QC record deleted successfully.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Failed to delete.'], 500);
        }
    }

    /**
     * Mark QC as passed (SuperAdmin only)
     */
    public function markPassed(int $id): JsonResponse
    {
        if (!$this->isSuperAdmin()) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $qc = QualityControl::findOrFail($id);
        $qc->result = 'passed';
        $qc->status = 'completed';
        $qc->save();

        return response()->json(['success' => true, 'message' => 'QC marked as passed!']);
    }

    /**
     * Mark QC as failed (SuperAdmin only)
     */
    public function markFailed(int $id): JsonResponse
    {
        if (!$this->isSuperAdmin()) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $qc = QualityControl::findOrFail($id);
        $qc->result = 'failed';
        $qc->status = 'completed';
        $qc->save();

        return response()->json(['success' => true, 'message' => 'QC marked as failed!']);
    }

    /**
     * Generate QC number (AJAX)
     */
    public function generateQcNo(): JsonResponse
    {
        $qcNo = $this->qualityService->generateQcNumber();
        return response()->json(['qc_no' => $qcNo]);
    }

    /**
     * Print QC report
     */
    public function print(int $id)
    {
        $qc = QualityControl::with('routeCard')->findOrFail($id);
        return $this->roleView('quality.print', compact('qc'));
    }

    // ==================== QC APPROVAL ====================

    /**
     * Display the QC approval page
     */
    public function approvalIndex()
    {
        $qcRecords = QualityControl::where('status', 'completed')
            ->where('result', 'passed')
            ->get();

        return $this->roleView('quality.approval', compact('qcRecords'));
    }

    /**
     * Approve QC (SuperAdmin only)
     */
    public function approve(int $id): JsonResponse
    {
        if (!$this->isSuperAdmin()) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $qc = QualityControl::findOrFail($id);
        $qc->status = 'approved';
        $qc->approved_by = auth()->id();
        $qc->approved_at = now();
        $qc->save();

        return response()->json(['success' => true, 'message' => 'QC approved!']);
    }

    /**
     * Reject QC (SuperAdmin only)
     */
    public function reject(int $id): JsonResponse
    {
        if (!$this->isSuperAdmin()) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $qc = QualityControl::findOrFail($id);
        $qc->status = 'rejected';
        $qc->save();

        return response()->json(['success' => true, 'message' => 'QC rejected!']);
    }
}
