<?php

namespace App\Http\Controllers;

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

class ModuleProductionOrderDataController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    // public function get_moduleProductionOrder(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',
    //         'production-order',
    //         '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);
    //     }

    //     $validFilters = ['Today', 'Yesterday', 'This Week', 'This Month'];
    //     $filterHeader = $request->header('filter-name');

    //     if (!in_array($filterHeader, $validFilters)) {
    //         return response()->json([
    //             'status_code' => 'ERROR',
    //             'status_description' => "Invalid filter-name value! Accepted values are: " . implode(', ', $validFilters)
    //         ], 404);
    //     }

    //     $plantName  = $request->header('plant-name');
    //     $lineName   = $request->header('line-name');
    //     $orderValue = $request->header('production-order');
    //     $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 not found!'
    //         ], 404);
    //     }

    //      $lineType = $line->type;

    //     if ($lineType === 'FG Line')
    //     {
    //         $table = 'quality_validations';
    //     }
    //     else
    //     {
    //         $table = 'production_quantities';
    //     }

    //       // Time Range
    //     if ($filterName == 'yesterday') {
    //         $startDate = now()->subDay()->setTime(8, 0, 0);
    //         $endDate   = now()->setTime(8, 0, 0);
    //         $groupBy   = "EXTRACT(HOUR FROM $table.created_at)";
    //     } elseif ($filterName == 'this week') {
    //         $startDate = now()->startOfWeek()->setTime(8, 0, 0);
    //         $endDate   = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
    //         $groupBy   = "EXTRACT(DOW FROM $table.created_at)";
    //     } elseif ($filterName == 'this month') {
    //         $startDate = now()->startOfMonth();
    //         $endDate   = now()->endOfMonth();
    //         $groupBy   = "FLOOR((EXTRACT(DAY FROM $table.created_at) - 1) / 7) + 1";
    //     } else {
    //         $startDate = now()->setTime(8, 0, 0);
    //         $endDate   = now()->copy()->addDay()->setTime(8, 0, 0);
    //         $groupBy   = "EXTRACT(HOUR FROM $table.created_at)";
    //     }

    //     $query = \DB::table($table)
    //         ->join('plants', "$table.plant_id", '=', 'plants.id')
    //         ->join('lines', "$table.line_id", '=', 'lines.id')
    //         ->selectRaw("$groupBy AS time_unit, count(*) AS total_quantity")
    //         ->whereBetween("$table.created_at", [$startDate, $endDate])
    //         ->where('plants.id', $plant->id)
    //         ->where('lines.id', $line->id)
    //         ->where("$table.production_order", $orderValue)
    //         ->groupByRaw($groupBy)
    //         ->orderByRaw($groupBy)
    //         ->pluck('total_quantity', 'time_unit')
    //         ->toArray();

    //     if ($filterName == 'this month') {
    //         $weeksCount = ceil($endDate->day / 7);
    //         $allWeeks = array_fill(1, $weeksCount, 0);
    //         $data = array_replace($allWeeks, $query);

    //         $labels = [];
    //         for ($i = 1; $i <= $weeksCount; $i++) {
    //             $weekStart = $startDate->copy()->addDays(($i - 1) * 7)->format('d M');
    //             $weekEnd = $startDate->copy()->addDays($i * 7 - 1)->min($endDate)->format('d M');
    //             $labels[] = "Week $i ($weekStart - $weekEnd)";
    //         }

    //         $orderedData = array_values($data);
    //     } elseif ($filterName === 'this week') {
    //         $labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    //         $data = array_fill(0, 7, 0);
    //         foreach ($query as $dow => $count) {
    //             $data[$dow] = $count;
    //         }

    //         $orderedData = [
    //             $data[1] ?? 0, $data[2] ?? 0, $data[3] ?? 0,
    //             $data[4] ?? 0, $data[5] ?? 0, $data[6] ?? 0,
    //             $data[0] ?? 0,
    //         ];
    //     } else {
    //         $allHours = array_fill(0, 24, 0);
    //         $data = array_replace($allHours, $query);

    //         $shiftedData = [];
    //         foreach ($data as $hour => $count) {
    //             $nextHour = ($hour + 1) % 24;
    //             $shiftedData[$nextHour] = $count;
    //         }

    //         $shiftedKeys = array_merge(range(9, 23), range(0, 8));
    //         $orderedData = array_map(fn($hour) => $shiftedData[$hour] ?? 0, $shiftedKeys);
    //         $labels = array_map(fn ($hour) => date("g A", strtotime("$hour:00")), $shiftedKeys);
    //     }

    //     $orderedData = array_map(function ($value) {
    //         return ($value == 0 || is_null($value)) ? null : $value;
    //     }, $orderedData);

    //     return response()->json([
    //         'status_code' => 'SUCCESS',
    //         'datasets' => [
    //             [
    //                 'label' => match ($filterName) {
    //                     'this week' => $lineType == 'FG Line' ? "Daily Fg Production Order Count This Week" : "Daily Production Order Count This Week",
    //                     'this month' => $lineType == 'FG Line' ? "Weekly Fg Production Order Count This Month" : "Weekly Production Order Count This Month",
    //                     'yesterday' => $lineType == 'FG Line' ? "Yesterday's Hourly Fg Order Count Production" : "Yesterday's Hourly Order Count Production",
    //                     default => $lineType == 'FG Line' ? "Today's Hourly Fg Production Order Count" : "Today's Hourly Production Order Count",
    //                 },
    //                 'data' => $orderedData,
    //                 'borderColor' => 'rgba(75, 192, 192, 1)',
    //                 'backgroundColor' => 'rgba(75, 192, 192, 0.2)',
    //                 'fill' => false,
    //                 'tension' => 0.3,
    //             ]
    //         ],
    //         'labels' => $labels
    //     ], 200);
    // }

    public function get_moduleProductionOrder(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', 'production-order', '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);
        }

        $filterHeader = $request->header('filter-name');
        $validFilters = ['Today', 'Yesterday', 'This Week', 'This Month'];
        if (!in_array($filterHeader, $validFilters)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid filter-name value! Accepted values are: " . implode(', ', $validFilters)
            ], 404);
        }

        $plantName = $request->header('plant-name');
        $lineName  = $request->header('line-name');
        $orderVal  = $request->header('production-order');
        $filter    = strtolower($filterHeader);

        $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!"
            ], 404);
        }

        $lineType = $line->type;
        $table = ($lineType == 'FG Line') ? 'quality_validations' : 'production_quantities';

        if ($filter == 'today' || $filter == 'yesterday') {
            $hourlyCounts = [];

            $hourStart = $filter == 'today'
                ? now()->setTime(8, 0, 0)
                : now()->subDay()->setTime(8, 0, 0);
            $hourEndFinal = $hourStart->copy()->addDay();

            while ($hourStart < $hourEndFinal) {
                $hourEnd = $hourStart->copy()->addHour();
                $label = $hourStart->format('g:i A') . ' to ' . $hourEnd->format('g:i A');

                $count = DB::table($table)
                    ->where('plant_id', $plant->id)
                    ->where('line_id', $line->id)
                    ->where('production_order', $orderVal)
                    ->whereBetween('created_at', [$hourStart, $hourEnd])
                    ->count();

                $hourlyCounts[$label] = $count;
                $hourStart = $hourEnd;
            }

            return response()->json([
                'status_code' => 'SUCCESS',
                'datasets' => [
                    [
                        'label' => $filter == 'yesterday'
                            ? "Yesterday's Hourly Production Order Count"
                            : "Today's Hourly Production Order Count",
                        'data' => $hourlyCounts
                    ]
                ]
            ], 200);
        }

        // Weekly or Monthly
        if ($filter == 'this week') {
            $startDate = now()->startOfWeek()->setTime(8, 0, 0);
            $endDate   = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
            $groupBy   = "EXTRACT(DOW FROM $table.created_at)";
        } else {
            $startDate = now()->startOfMonth();
            $endDate   = now()->endOfMonth();
            $groupBy   = "FLOOR((EXTRACT(DAY FROM $table.created_at) - 1) / 7) + 1";
        }

        $query = DB::table($table)
            ->where('plant_id', $plant->id)
            ->where('line_id', $line->id)
            ->where('production_order', $orderVal)
            ->whereBetween('created_at', [$startDate, $endDate])
            ->selectRaw("$groupBy as group_key, COUNT(*) as total")
            ->groupByRaw("group_key")
            ->pluck('total', 'group_key')
            ->toArray();

        if ($filter == 'this week') {
            $labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
            $data = array_fill(0, 7, 0);

            foreach ($query as $dow => $count) {
                $data[$dow] = $count;
            }

            $orderedData = [
                $data[1] ?? 0, $data[2] ?? 0, $data[3] ?? 0,
                $data[4] ?? 0, $data[5] ?? 0, $data[6] ?? 0,
                $data[0] ?? 0,
            ];
        } else {
            $weeksCount = ceil($endDate->day / 7);
            $allWeeks = array_fill(1, $weeksCount, 0);
            $data = array_replace($allWeeks, $query);

            $labels = [];
            for ($i = 1; $i <= $weeksCount; $i++) {
                $weekStart = $startDate->copy()->addDays(($i - 1) * 7)->format('d M');
                $weekEnd = $startDate->copy()->addDays($i * 7 - 1)->min($endDate)->format('d M');
                $labels[] = "Week $i ($weekStart - $weekEnd)";
            }

            $orderedData = array_values($data);
        }

        return response()->json([
            'status_code' => 'SUCCESS',
            'datasets' => [
                [
                    'label' => match ($filter) {
                        'this week' => $lineType == 'FG Line'
                            ? "Daily Fg Production Order Count This Week"
                            : "Daily Production Order Count This Week",
                        'this month' => $lineType == 'FG Line'
                            ? "Weekly Fg Production Order Count This Month"
                            : "Weekly Production Order Count This Month",
                    },
                    'data' => $orderedData
                ]
            ],
            'labels' => $labels ?? []
        ], 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)
    {
        //
    }
}
