<?php

namespace App\Http\Controllers;

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

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

    // public function get_invoiceQuantityData(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 = [];

    // }


    /**
     * Store a newly created resource in storage.
     */

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

        $types = ['individual_invoice', 'serial_invoice', 'bundle_invoice'];
        if ($selectedInvoice != 'all invoice') {
            $types = [str_replace(' ', '_', $selectedInvoice)];
        }

        $labels = ['Total Invoices', 'Scanned Invoices'];
        $datasets = [];

        $totals = [];
        $scanneds = [];

        foreach ($types as $type) {
            $query = InvoiceValidation::where('plant_id', $selectedPlant)
                ->whereBetween('created_at', [$startDate, $endDate]);

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

            if ($type == 'individual_invoice') {
                $query->where('quantity', 1);
                $completedQuery->where('quantity', 1)
                    ->whereNotNull('serial_number')
                    ->where('serial_number', '!=', '');
            } elseif ($type == 'serial_invoice') {
                $query->whereNull('quantity');
                $completedQuery->where('scanned_status', 'Scanned')
                    ->where(function ($q) {
                        $q->whereNull('quantity')->orWhere('quantity', 0);
                    });
            } elseif ($type == 'bundle_invoice') {
                $query->where('quantity', '>', 1);
                $completedQuery->where('quantity', '>', 1)
                    ->whereNotNull('serial_number')
                    ->where('serial_number', '!=', '');
            }

            $totals[] = $query->count();
            $scanneds[] = $completedQuery->count();
        }

        // if (count($types) == 1) {
        //     $datasets[] = [
        //         'label' => 'Invoices',
        //         'data' => [$totals[0], $scanneds[0]],
        //     ];
        // }
        if (count($types) == 1)
        {
            $invoiceLabel = ucwords(str_replace('_invoice', '', str_replace('_', ' ', $types[0])));
            $datasets[] = [
                'label' => $invoiceLabel, // e.g., Serial Invoice
                'data' => [$totals[0], $scanneds[0]],
            ];
        }
        else
        {
            $datasets[] = [
                'label' => 'Total Invoices',
                'data' => $totals,
            ];
            $datasets[] = [
                'label' => 'Scanned Invoices',
                'data' => $scanneds,
            ];
            $labels = array_map(function ($type) {
                return ucwords(str_replace('_invoice', '', str_replace('_', ' ', $type)));
            }, $types);
        }

        foreach ($datasets as &$dataset) {
            $dataset['data'] = array_map(function ($value) {
                return $value ?? 0;
            }, $dataset['data']);
        }

        return response()->json([
            'status_code' => 'SUCCESS',
            'labels' => $labels,
            'datasets' => $datasets,
        ], 200);
    }
    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)
    {
        //
    }
}
