<?php

namespace App\Http\Controllers\SuperAdmin;

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

class SuperAdminManufacturingPlanningController extends Controller
{
    public function index()
    {
        return response()->json(ManufacturingPlan::all());
    }

    public function show($id)
    {
        return response()->json(ManufacturingPlan::findOrFail($id));
    }
    public function planPage()
    {
        // You can pass anything to the view if needed, but the page will fetch RC+processes with AJAX
        $operators = \App\Models\EmployeeDetails::pluck('name', 'id')->toArray();
        return view('superadmin.manufacturing.plan', compact('operators'));
    }

    public function rcProcesses($id)
    {
        // Get RC + processes
        $rc = \App\Models\RouteCard::with('processes')->findOrFail($id);
        return response()->json($rc);
    }

    public function planPageWithId($id)
{
    $operators = \App\Models\EmployeeDetails::pluck('name', 'id')->toArray();
    $routeCard = \App\Models\RouteCard::with('processes')->findOrFail($id);

    // Machine & Operator Availability Logic
    $now = \Carbon\Carbon::now();

    $machines = \App\Models\Machines::all();
    $employees = \App\Models\EmployeeDetails::all();

    $machineAvailability = [];
    foreach ($machines as $machine) {
        $maxEndDate = \DB::table('route_card_processes')
            ->where('machine', $machine->machine_id)
            ->max('end_date');
        if ($maxEndDate && \Carbon\Carbon::parse($maxEndDate)->gt($now)) {
            $availDate = 'Available from: ' . \Carbon\Carbon::parse($maxEndDate)->format('d-m-Y H:i');
        } else {
            $availDate = 'Available now';
        }
        $machineAvailability[$machine->machine_id] = $availDate;
    }

    $operatorAvailability = [];
    foreach ($employees as $emp) {
        $maxEndDate = \DB::table('route_card_processes')
            ->where('operator', $emp->id)
            ->max('end_date');
        if ($maxEndDate && \Carbon\Carbon::parse($maxEndDate)->gt($now)) {
            $availDate = 'Available from: ' . \Carbon\Carbon::parse($maxEndDate)->format('d-m-Y H:i');
        } else {
            $availDate = 'Available now';
        }
        $operatorAvailability[$emp->id] = $availDate;
    }

    return view('superadmin.manufacturing.plan', compact(
        'operators', 'routeCard', 'id', 'machineAvailability', 'operatorAvailability'
    ));
}



    public function store(Request $request)
    {
        $data = $request->validate([
            'rc_id' => 'required|string',
            'company_name' => 'required|string',
            'status' => 'nullable|string',
            'rc_date' => 'nullable|date',
            'approved_by' => 'nullable|string',
            'plan_by' => 'nullable|string',
            'plan_date' => 'nullable|date',
            'machine' => 'nullable|string',
            'process' => 'nullable|string',
            'operator' => 'nullable|string',
            'ct_hours' => 'nullable|string',
            'ct_minutes' => 'nullable|string',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date',
        ]);
        $plan = ManufacturingPlan::create($data);
        return response()->json($plan, 201);
    }

    public function updateProcess(Request $request, $id)
    {
        $process = RouteCardProcess::findOrFail($id);
        $data = $request->validate([
            'description' => 'nullable|string',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date',
            'operator' => 'nullable|string',
            'machine' => 'nullable|string',
            'process' => 'nullable|string',
            'cycle_hours' => 'nullable|integer',
            'cycle_minutes' => 'nullable|integer',
            'source' => 'nullable|string',
            'previous_process' => 'nullable|string',
        ]);
        $process->update($data);
        return response()->json(['success' => true, 'process' => $process]);
    }

    public function destroy($id)
    {
        $plan = ManufacturingPlan::findOrFail($id);
        $plan->delete();
        return response()->json(['message' => 'Deleted']);
    }
    public function ganttPage()
    {
        return view('superadmin.manufacturing.gantt');
    }

    public function ganttData(Request $request)
    {
        $query = RouteCard::with(['processes' => function($q) {
            $q->orderBy('start_date');
        }]);

        if ($request->has('status') && $request->status != 'all') {
             $query->where('status', $request->status);
        }

        $cards = $query->orderBy('project_start_date')->get();
        
        $tasks = [];
        foreach($cards as $rc) {
             // Calculate Project End if not process exists, assume 1 day?
             // Or calculate from processes.
             $projectEnd = $rc->route_date;
             if($rc->processes->count() > 0) {
                 $maxEnd = $rc->processes->max('end_date');
                 if($maxEnd > $projectEnd) $projectEnd = $maxEnd;
             }
             
             // Project Task
             $tasks[] = [
                 'id' => 'rc-' . $rc->id,
                 'name' => $rc->route_no, // Short name for Gantt
                 '_full_name' => $rc->route_no . ' - ' . $rc->company_name, // Custom valid for tooltip
                 'start' => $rc->project_start_date ?? date('Y-m-d'),
                 'end' => $projectEnd ?? date('Y-m-d', strtotime('+1 day')),
                 'progress' => 0, // Logic: AVG(process progress)?
                 'custom_class' => 'gantt-project', 
                 'dependencies' => '' // No dependencies for root
             ];

             foreach($rc->processes as $proc) {
                 $dependencies = 'rc-' . $rc->id;
                 if ($proc->previous_process_id) {
                     $dependencies .= ', p-' . $proc->previous_process_id;
                 }
                 
                 // ensure valid dates
                 $start = $proc->start_date ? date('Y-m-d', strtotime($proc->start_date)) : date('Y-m-d');
                 $end = $proc->end_date ? date('Y-m-d', strtotime($proc->end_date)) : $start;
                 if($end < $start) $end = $start;

                 $tasks[] = [
                     'id' => 'p-' . $proc->id,
                     'name' => $proc->process,
                     'description' => "Machine: {$proc->machine}, Operator: " . ($proc->operator ?? 'N/A'),
                     'start' => $start,
                     'end' => $end,
                     'progress' => ($proc->status == 'approved' || $proc->status == 'completed' ? 100 : ($proc->status == 'in_progress' ? 50 : 0)),
                     'dependencies' => $dependencies,
                     'custom_class' => 'gantt-process ' . ($proc->status == 'completed' || $proc->status == 'approved' ? 'is-completed' : ($proc->status == 'in_progress' ? 'is-running' : 'is-pending'))
                 ];
             }
        }
        return response()->json($tasks);
    }
}
