<?php

namespace App\Http\Controllers;

use App\Models\Line;
use App\Models\Plant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ModuleProductionLineStopController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }
    public function get_moduleProductionLineStop(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw   = env('API_AUTH_PW');

        $header_auth = $request->header('Authorization');
        $expectedToken = $expectedUser . ':' . $expectedPw;

        if ("Bearer " . $expectedToken != $header_auth) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!'
            ], 403);
        }

        $requiredHeaders = ['module-name', 'chart-name', 'plant-name', 'line-name', 'filter-name'];

        $missingHeaders = [];
        foreach ($requiredHeaders as $header) {
            if (empty($request->header($header))) {
                $missingHeaders[] = $header;
            }
        }

        if (!empty($missingHeaders)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Missing required headers: ' . implode(', ', $missingHeaders)
            ], 404);
        }

        $plantName   = $request->header('plant-name');
        $lineName    = $request->header('line-name');
        $filterName  = strtolower(trim($request->header('filter-name')));

        $plant = Plant::where('name', $plantName)->first();
        if (!$plant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant '{$plantName}' not found!"
            ], 404);
        }

        $line = Line::where('name', $lineName)->where('plant_id', $plant->id)->first();
        if (!$line) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Line '{$lineName}' not found for plant '{$plantName}'"
            ], 404);
        }

        // Set time range
        if ($filterName == 'yesterday') {
            $startDate = now()->subDay()->setTime(8, 0, 0);
            $endDate = now()->setTime(8, 0, 0);
        } elseif ($filterName == 'this week') {
            $startDate = now()->startOfWeek()->setTime(8, 0, 0);
            $endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
        } elseif ($filterName == 'this month') {
            $startDate = now()->startOfMonth();
            $endDate = now()->endOfMonth();
        } else {
            $startDate = now()->setTime(8, 0, 0);
            $endDate = now()->copy()->addDay()->setTime(8, 0, 0);
        }

        $query = DB::table('production_line_stops')
            ->join('line_stops as ls', 'production_line_stops.linestop_id', '=', 'ls.id')
            ->join('lines', 'production_line_stops.line_id', '=', 'lines.id')
            ->join('plants', 'production_line_stops.plant_id', '=', 'plants.id')
            ->select(
                'ls.code',
                'ls.reason',
                DB::raw("SUM(production_line_stops.stop_hour) as total_stop_hours"),
                DB::raw("SUM(production_line_stops.stop_min) as total_stop_minutes")
            )
            ->where('plants.id', $plant->id)
            ->where('lines.id', $line->id)
            ->whereBetween('production_line_stops.created_at', [$startDate, $endDate])
            ->groupBy('ls.code', 'ls.reason')
            ->get();

        if ($query->isEmpty()) {
            return response()->json([
                'status_code' => 'SUCCESS',
                'labels' => ['No Data'],
                'data' => [1],
            ], 200);
        }

        $labels = [];
        $data = [];
        $totalStopMinutes = 0;

        foreach ($query as $row) {
            $stopHours = $row->total_stop_hours;
            $stopMinutes = $row->total_stop_minutes;
            $visualTotal = $stopHours + ($stopMinutes / 100);

            $labels[] = "{$row->code} - {$row->reason}";
            $data[] = $visualTotal;

            $totalStopMinutes += ($stopHours * 60) + $stopMinutes;
        }

        // Calculate available runtime
        $remainingMinutes = 1440 - $totalStopMinutes;
        $runtimeHours = floor($remainingMinutes / 60);
        $runtimeMinutes = $remainingMinutes % 60;
        $runtimeVisual = $runtimeHours + ($runtimeMinutes / 100);

        $labels[] = 'Available Runtime';
        $data[] = $runtimeVisual;

        return response()->json([
            'status_code' => 'SUCCESS',
            'labels' => $labels,
            'data' => $data,
        ], 200);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
