<?php

namespace App\Http\Controllers;

use App\Models\InvoiceValidation;
use App\Models\ModuleList;
use App\Models\Plant;
use Illuminate\Http\Request;

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

    public function get_invoiceFilter(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);
        }

        $filterName = $request->header('filter-name');

        if (empty($filterName))
        {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Filter Name can't be empty!"
            ], 404);
        }

        $headerValue = $request->header('filter-name');

        if ($headerValue != 'Filter List') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid value for 'module-name' header!"
            ], 404);
        }

        $uniqueModules = ModuleList::select('filter_name', 'created_at')
            ->orderBy('created_at', 'asc')
            ->get()
            ->unique('filter_name')
            ->pluck('filter_name')
            ->values();

             if ($uniqueModules->isEmpty()) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Filter names not found'
            ], 404);
        }


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

    // public function get_invoiceCountData(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);
    //         }

    //         $moduleName = $request->header('invoice-name');

    //         if (empty($moduleName))
    //         {
    //             return response()->json([
    //                 'status_code' => 'ERROR',
    //                 'status_description' => "Invoice name can't be empty!"
    //             ], 404);
    //         }

    //         $plantName   = $request->header('plant-name');
    //         $selectedInvoice = strtolower(trim($request->header('invoice-name')));
    //         $activeFilter    = 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);
    //         }

    //         $selectedPlant = $plant->id;

    //         if (empty($selectedInvoice) || empty($selectedPlant) || empty($activeFilter)) {
    //             return response()->json([
    //                 'status_code' => 'ERROR',
    //                 'status_description' => 'Missing required headers: invoice-name, plant-name, or filter-name'
    //             ], 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);
    //         }

    //         $validInvoiceFilters = ['All Invoice', 'Serial Invoice', 'Individual Invoice', 'Bundle Invoice'];
    //         $filterInvoice = $request->header('invoice-name');

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

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

    //         $labels = [];
    //         $datasets = [];

    //         if ($activeFilter == 'yesterday' || $activeFilter == 'today')
    //         {

    //             // === Imported Invoices ===
    //             $importedQuery = InvoiceValidation::where('plant_id', $selectedPlant)
    //                 ->whereBetween('created_at', [$startDate, $endDate]);

    //             if ($selectedInvoice == 'individual invoice') {
    //                 $importedQuery->where('quantity', 1);
    //             } elseif ($selectedInvoice == 'serial invoice') {
    //                 $importedQuery->whereNull('quantity');
    //             } elseif ($selectedInvoice == 'bundle invoice') {
    //                 $importedQuery->where('quantity', '>', 1);
    //             }

    //             $importedCount = $importedQuery->distinct('invoice_number')->count('invoice_number');



    //             // === Completed Invoices ===
    //             $completedQuery = InvoiceValidation::select('invoice_number')
    //                 ->where('plant_id', $selectedPlant)
    //                 ->whereBetween('updated_at', [$startDate, $endDate]);

    //             if ($selectedInvoice == 'individual invoice') {
    //                 $completedQuery->where('quantity', 1)
    //                     ->groupBy('invoice_number')
    //                     ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
    //             } elseif ($selectedInvoice == 'serial invoice') {
    //                 $completedQuery->whereNull('quantity')
    //                     ->groupBy('invoice_number')
    //                     ->havingRaw("COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)");
    //             } elseif ($selectedInvoice == 'bundle invoice') {
    //                 $completedQuery->where('quantity', '>', 1)
    //                     ->groupBy('invoice_number')
    //                     ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
    //             }

    //             $completedCount = $completedQuery->count();

    //             $labels = ['Imported Invoice', 'Completed Invoice'];
    //             $datasets = [[
    //                 'label' => 'Invoices',
    //                 'data' => [$importedCount, $completedCount],
    //             ]];


    //         }

    //         elseif ($activeFilter == 'this week') {
    //             $labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    //             $imported = array_fill(0, 7, 0);
    //             $completed = array_fill(0, 7, 0);

    //             for ($i = 0; $i < 7; $i++) {
    //                 $dayStart = now()->startOfWeek()->addDays($i)->setTime(8, 0, 0);
    //                 $dayEnd = $dayStart->copy()->addDay()->setTime(8, 0, 0);

    //                 $importedQuery = InvoiceValidation::where('plant_id', $selectedPlant)
    //                     ->whereBetween('created_at', [$dayStart, $dayEnd]);

    //                 $completedQuery = InvoiceValidation::select('invoice_number')
    //                     ->where('plant_id', $selectedPlant)
    //                     ->whereBetween('updated_at', [$dayStart, $dayEnd]);

    //                 if ($selectedInvoice == 'individual invoice') {
    //                     $importedQuery->where('quantity', 1);
    //                     $completedQuery->where('quantity', 1)
    //                         ->groupBy('invoice_number')
    //                         ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
    //                 } elseif ($selectedInvoice == 'serial invoice') {
    //                     $importedQuery->whereNull('quantity');
    //                     $completedQuery->whereNull('quantity')
    //                         ->groupBy('invoice_number')
    //                         ->havingRaw("COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)");
    //                 } elseif ($selectedInvoice == 'bundle invoice') {
    //                     $importedQuery->where('quantity', '>', 1);
    //                     $completedQuery->where('quantity', '>', 1)
    //                         ->groupBy('invoice_number')
    //                         ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
    //                 }

    //                 $imported[$i] = $importedQuery->distinct('invoice_number')->count('invoice_number');
    //                 $completed[$i] = $completedQuery->count();
    //             }

    //             $datasets = [
    //                 ['label' => 'Imported Invoices', 'data' => $imported],
    //                 ['label' => 'Completed Invoices', 'data' => $completed],
    //             ];
    //         }

    //         elseif ($activeFilter == 'this month') {
    //             $startOfMonth = now()->startOfMonth()->setTime(8, 0, 0);
    //             $endOfMonth = now()->endOfMonth()->addDay()->setTime(8, 0, 0);

    //             $labels = [];
    //             $imported = [];
    //             $completed = [];

    //             $weekStart = $startOfMonth->copy();
    //             while ($weekStart < $endOfMonth) {
    //                 $weekEnd = $weekStart->copy()->addDays(7);
    //                 $label = $weekStart->format('M') . ' (' . $weekStart->format('j') . '-' . $weekEnd->subDay()->format('j') . ')';
    //                 $labels[] = $label;

    //                 $importedQuery = InvoiceValidation::where('plant_id', $selectedPlant)
    //                     ->whereBetween('created_at', [$weekStart, $weekEnd]);

    //                 $completedQuery = InvoiceValidation::select('invoice_number')
    //                     ->where('plant_id', $selectedPlant)
    //                     ->whereBetween('updated_at', [$weekStart, $weekEnd]);

    //                 if ($selectedInvoice == 'individual invoice') {
    //                     $importedQuery->where('quantity', 1);
    //                     $completedQuery->where('quantity', 1)
    //                         ->groupBy('invoice_number')
    //                         ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
    //                 } elseif ($selectedInvoice == 'serial invoice') {
    //                     $importedQuery->whereNull('quantity');
    //                     $completedQuery->whereNull('quantity')
    //                         ->groupBy('invoice_number')
    //                         ->havingRaw("COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)");
    //                 } elseif ($selectedInvoice == 'bundle invoice') {
    //                     $importedQuery->where('quantity', '>', 1);
    //                     $completedQuery->where('quantity', '>', 1)
    //                         ->groupBy('invoice_number')
    //                         ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
    //                 }

    //                 $imported[] = $importedQuery->distinct('invoice_number')->count('invoice_number');
    //                 $completed[] = $completedQuery->count();

    //                 $weekStart = $weekEnd;
    //             }

    //             $datasets = [
    //                 ['label' => 'Imported Invoices', 'data' => $imported],
    //                 ['label' => 'Completed Invoices', 'data' => $completed],
    //             ];
    //         }

    //         // Clean zero values to null
    //         foreach ($datasets as &$dataset) {
    //             $dataset['data'] = array_map(function ($value) {
    //                 return ($value === null) ? 0 : $value;
    //             }, $dataset['data']);
    //         }


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

    /**
     * Store a newly created resource in storage.
     */
    public function get_invoiceCountData(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);
        }

        $plantName       = $request->header('plant-name');
        $filterHeader    = $request->header('filter-name');
        $invoiceHeader   = $request->header('invoice-name');

        if (empty($plantName) || empty($invoiceHeader) || empty($filterHeader)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Missing required headers: plant-name, invoice-name, or filter-name"
            ], 404);
        }

        $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);
        }

        $validInvoiceFilters = ['All Invoice', 'Serial Invoice', 'Individual Invoice', 'Bundle Invoice'];
        if (!in_array($invoiceHeader, $validInvoiceFilters)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid invoice-name value! Accepted values are: " . implode(', ', $validInvoiceFilters)
            ], 404);
        }

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

        $selectedPlant = $plant->id;
        $activeFilter = strtolower(trim($filterHeader));
        $selectedInvoice = strtolower(trim($invoiceHeader));

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

        $labels = [];
        $datasets = [];

        // Map types for All Invoice
        $invoiceTypes = $selectedInvoice == 'all invoice'
            ? [
                'Individual Invoice' => fn($q) => $q->where('quantity', 1),
                'Serial Invoice'     => fn($q) => $q->whereNull('quantity'),
                'Bundle Invoice'     => fn($q) => $q->where('quantity', '>', 1)
            ]
            : [
                ucfirst($selectedInvoice) => match ($selectedInvoice) {
                    'individual invoice' => fn($q) => $q->where('quantity', 1),
                    'serial invoice'     => fn($q) => $q->whereNull('quantity'),
                    'bundle invoice'     => fn($q) => $q->where('quantity', '>', 1),
                }
            ];

        foreach ($invoiceTypes as $labelPrefix => $queryModifier) {
            if ($activeFilter == 'yesterday' || $activeFilter == 'today') {
                $importedQuery = InvoiceValidation::where('plant_id', $selectedPlant)
                    ->whereBetween('created_at', [$startDate, $endDate]);

                $queryModifier($importedQuery);
                $importedCount = $importedQuery->distinct('invoice_number')->count('invoice_number');

                $completedQuery = InvoiceValidation::select('invoice_number')
                    ->where('plant_id', $selectedPlant)
                    ->whereBetween('updated_at', [$startDate, $endDate]);

                if ($selectedInvoice == 'serial invoice' || $labelPrefix == 'Serial Invoice') {
                    $queryModifier($completedQuery)
                        ->groupBy('invoice_number')
                        ->havingRaw("COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)");
                } else {
                    $queryModifier($completedQuery)
                        ->groupBy('invoice_number')
                        ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
                }

                $completedCount = $completedQuery->count();

                $labels = ['Imported Invoice', 'Completed Invoice'];
                $datasets[] = [
                    'label' => "$labelPrefix",
                    'data' => [$importedCount, $completedCount],
                ];
            }

            elseif ($activeFilter == 'this week') {
                $labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
                $imported = array_fill(0, 7, 0);
                $completed = array_fill(0, 7, 0);

                for ($i = 0; $i < 7; $i++) {
                    $dayStart = now()->startOfWeek()->addDays($i)->setTime(8, 0, 0);
                    $dayEnd = $dayStart->copy()->addDay()->setTime(8, 0, 0);

                    $importedQuery = InvoiceValidation::where('plant_id', $selectedPlant)
                        ->whereBetween('created_at', [$dayStart, $dayEnd]);
                    $queryModifier($importedQuery);
                    $imported[$i] = $importedQuery->distinct('invoice_number')->count('invoice_number');

                    $completedQuery = InvoiceValidation::select('invoice_number')
                        ->where('plant_id', $selectedPlant)
                        ->whereBetween('updated_at', [$dayStart, $dayEnd]);

                    if ($selectedInvoice == 'serial invoice' || $labelPrefix == 'Serial Invoice') {
                        $queryModifier($completedQuery)
                            ->groupBy('invoice_number')
                            ->havingRaw("COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)");
                    } else {
                        $queryModifier($completedQuery)
                            ->groupBy('invoice_number')
                            ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
                    }

                    $completed[$i] = $completedQuery->count();
                }

                $datasets[] = ['label' => "$labelPrefix Imported", 'data' => $imported];
                $datasets[] = ['label' => "$labelPrefix Completed", 'data' => $completed];
            }

            elseif ($activeFilter == 'this month') {
                $startOfMonth = now()->startOfMonth()->setTime(8, 0, 0);
                $endOfMonth = now()->endOfMonth()->addDay()->setTime(8, 0, 0);
                $labels = [];
                $imported = [];
                $completed = [];

                $weekStart = $startOfMonth->copy();
                while ($weekStart < $endOfMonth) {
                    $weekEnd = $weekStart->copy()->addDays(7);
                    $label = $weekStart->format('M') . ' (' . $weekStart->format('j') . '-' . $weekEnd->subDay()->format('j') . ')';
                    $labels[] = $label;

                    $importedQuery = InvoiceValidation::where('plant_id', $selectedPlant)
                        ->whereBetween('created_at', [$weekStart, $weekEnd]);
                    $queryModifier($importedQuery);
                    $imported[] = $importedQuery->distinct('invoice_number')->count('invoice_number');

                    $completedQuery = InvoiceValidation::select('invoice_number')
                        ->where('plant_id', $selectedPlant)
                        ->whereBetween('updated_at', [$weekStart, $weekEnd]);

                    if ($selectedInvoice == 'serial invoice' || $labelPrefix == 'Serial Invoice') {
                        $queryModifier($completedQuery)
                            ->groupBy('invoice_number')
                            ->havingRaw("COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)");
                    } else {
                        $queryModifier($completedQuery)
                            ->groupBy('invoice_number')
                            ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
                    }

                    $completed[] = $completedQuery->count();
                    $weekStart = $weekEnd;
                }

                $datasets[] = ['label' => "$labelPrefix Imported", 'data' => $imported];
                $datasets[] = ['label' => "$labelPrefix Completed", 'data' => $completed];
            }
        }

        // Ensure 0 instead of null
        foreach ($datasets as &$dataset) {
            $dataset['data'] = array_map(fn($val) => $val === null ? 0 : $val, $dataset['data']);
        }

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

    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)
    {
        //
    }
}
