<?php

namespace App\Http\Controllers;

use App\Models\DriverMaster;
use App\Models\VehicleMaster;
use Illuminate\Http\Request;
use Str;
use Illuminate\Support\Facades\Schema;

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'identification1' => 'nullable|string',
            'identification2' => 'nullable|string',
            'identification3' => 'nullable|string',
            'contact_number' => 'nullable|string',
            'alternate_number' => 'nullable|string',
        ]);

        DriverMaster::create($request->all());

        return response()->json(['success' => true]);
    }

    public function getSapData(Request $request)
    {

    }

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

        $plantCode = $request->header('plant-code');

         if ($plantCode == null || $plantCode == '')
        {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code can't be empty!"
            ], 400);
        }
        else if (Str::length($plantCode) < 4 || !is_numeric($plantCode) || !preg_match('/^[1-9]\d{3,}$/', $plantCode))
        {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid plant code found!"
            ], 400);
        }

        $path = "/LaserPRD/{$plantCode}";

        // $isDir = is_dir($path);
        // $isReadable = is_readable($path);

        // Check if folder exists
        if (!is_dir($path)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Folder for plant-code {$plantCode} not found!"
            ], 404);
        }

        if (!is_readable($path)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Folder for plant-code {$plantCode} exists but is not readable!"
            ], 500);
        }

        // Scan folder
        $allFiles = scandir($path);
        if ($allFiles === false) {
            return response()->json([
                'status' => 'error',
                'status_description' => 'Failed to scan directory',
            ], 500);
        }

        $files = array_filter($allFiles, function($item) use ($path) {
            $fullPath = $path . '/' . $item;
            return @is_file($fullPath) && pathinfo($item, PATHINFO_EXTENSION) === 'txt';
        });

        if (empty($files)) {
            return response()->json([
                'status' => 'error',
                'status_description' => 'No text files found',
            ], 404);
        }

        // $data = [];
        // foreach ($files as $file)
        // {
        //     $filePath = $path . '/' . $file;

        //     $content = file_get_contents($filePath);

        //     $data[] = [
        //         'filename' => $file,
        //         'content' => $content,
        //     ];
        // }

        // return response()->json([
        //     'status' => 'success',
        //     'files' => $data,
        // ]);

        //$fileName = 'RMGLAS02-1725800-1.txt';
        $fileName = array_values($files)[0];
        $filePath = $path . '/' . $fileName;

        $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $headerLine = array_shift($lines); // removes first line

        if (!$lines) {
            return response()->json(['status' => 'ERROR', 'message' => 'File is empty'], 400);
        }

        // Debug: return first 5 lines to check reading
        // return response()->json([
        //     'status' => 'DEBUG_LINES',
        //     'file' => $fileName,
        //     'lines_sample' => array_slice($lines, 0, 5) // first 5 lines
        // ]);

        if (!file_exists($filePath) || !is_readable($filePath)) {
            return response()->json([
                'status' => 'ERROR',
                'message' => "File {$fileName} not found or not readable"
            ], 500);
        }

        // Prepare arrays
        // $serialNumbers = [];
        // $remainingRows = [];

        // foreach ($lines as $line)
        // {
        //     $values = str_getcsv($line);

        //     // Debug: make sure CSV split is correct
        //     if (count($values) < 6) {
        //         return response()->json([
        //             'status' => 'ERROR',
        //             'message' => 'In text file has fewer than 6 columns',
        //             'line' => $line
        //         ], 400);
        //     }

        //     $serialNumbers[] = $values[5] ?? null;

        //     $remainingRow = $values;
        //     unset($remainingRow[5]);
        //     // $remainingRow = array_values($remainingRow); // reindex
        //     // $remainingRows[] = $remainingRow;
        //      $remainingRow = array_values($remainingRow); // reindex

        //     // Only add unique remaining rows
        //     if (!in_array($remainingRow, $remainingRows, true)) {
        //         $remainingRows[] = $remainingRow;
        //     }
        // }

        // return response()->json([
        //     'status' => 'SUCCESS',
        //     'serial_numbers' => $serialNumbers,
        //     'remaining_rows_sample' => array_slice($remainingRows, 0, 5), // just first 5 for debug
        // ]);

        $serialNumbers = [];
        $remainingRow = null;
        $invalidSerials = [];

        foreach ($lines as $line) {
            $values = str_getcsv($line);

            if (count($values) < 6) {
                return response()->json([
                    'status' => 'ERROR',
                    'message' => 'Text file row has fewer than 6 columns',
                    'line' => $line
                ], 400);
            }

            // Collect serial number
           // $serialNumbers[] = $values[5] ?? null;
             $serial = $values[5] ?? null;
             $serialNumbers[] = $serial;

             if ($serial == null || strlen($serial) < 13) {
                $invalidSerials[] = $serialNumbers;
            }

            // Store remaining row only once
            if ($remainingRow == null) {
                $remainingRow = $values;
                unset($remainingRow[5]); // remove serial number
                $remainingRow = array_values($remainingRow); // reindex
            }
        }

        if (!empty($invalidSerials)) {
            return response()->json([
                'status' => 'ERROR',
                'status_description' => 'serial numbers are invalid (less than 13 characters)',
                'invalid_serials' => $invalidSerials
            ], 400);
        }

        return response()->json([
            'status' => 'SUCCESS',
            'serial_numbers' => $serialNumbers,
            'remaining_row' => $remainingRow, // only one copy
        ]);
    }



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