<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class MasterFileController extends Controller
{

    public function index()
    {
        $menu = 'MasterFile';
        $currentContent = 'MasterFile';
        return view('home', compact('menu', 'currentContent'));
    }
    public function processFile(Request $request)
    {
        // Ensure the file is uploaded
        if (!$request->hasFile('data') || !$request->file('data')->isValid()) {
            return redirect()->back()->with('error', 'Invalid file upload.');
        }

        // Get file details
        $file = $request->file('data');
        $filePath = $file->getRealPath();
        $fileSize = $file->getSize();
        $filename = $file->getClientOriginalName();

        $timestampEEC = now()->format('Y-m-d');
        $actDateTime = now()->format('Y-m-d H:i:s');

        // Fetch format name
        $format = $request->input('format');
        $config = DB::table('conf_format_file')
            ->where('file', $format)
            ->whereNotNull('ac')
            ->first();

        if (!$config) {
            return redirect()->back()->with('error', 'MasterFile Not config to EEC');
        }

        $typeEEC = $config->ac;

        // Send file to EEC if applicable
        if ($request->input('sendtoeec') === 'on' && !empty($typeEEC)) {
            $response = Http::attach('file', fopen($filePath, 'r'), $filename)
                ->post(env('URL_MASTERFILE_EEC'), [
                    'type' => $typeEEC,
                    'timestamp' => $timestampEEC,
                ]);

            $respStatus = $response->status();
            $respData = $response->body();

            DB::table('ecc_transactions')->insert([
                'uid' => $request->input('UID'),
                'type_eec' => $typeEEC,
                'filename' => $filename,
                'request_data' => json_encode([
                    'type' => $typeEEC,
                    'file' => $filename,
                    'timestamp' => $timestampEEC,
                ]),
                'act_datetime' => $actDateTime,
                'response_status' => $respStatus,
                'response_data' => $respData,
            ]);

            if ($respStatus === 200) {
                return redirect()->back()->with('success', 'Send MasterFile To EEC');
            } else {
                return redirect()->back()->with('error', 'Cannot Send MasterFile To EEC');
            }
        }

        // Process file and create patches
        if ($request->input('createpatch') === 'on') {
            $data = $this->readTxt($filePath, $format, $request->input('ac'), $request->input('sizerow'), $request->input('notsplit'));

            foreach ($data as $key => $sqlPack) {
                $patchCode = $this->generatePatchCode($sqlPack);

                DB::table('conf_smartupdate')->insert([
                    'patchname' => "Update Master File {$config->name} วันที่ " . now()->format('j') . ' เดือน ' . now()->format('n') . ' ปี ' . now()->format('Y') . ' Part ' . ($key + 1),
                    'pdate' => now(),
                    'plevel' => 'Critical',
                    'pcode' => 'SHIPPINGNET',
                    'major_version' => 'ALL',
                    'pdesc' => $config->name,
                    'powner' => $request->input('UID'),
                    'ptype' => 'UPDATE MASTER',
                    'papprovedate' => now(),
                    'patchcode' => $patchCode,
                    'uninstall' => 'DONE=1;',
                    'patchcode_server' => 'DONE=1;',
                ]);
            }

            return redirect()->back()->with('success', 'Successful Created Patch.');
        }

        return redirect()->back()->with('error', 'File processing failed.');
    }

    private function readTxt($filePath, $format, $ac, $sizeRow, $notSplit)
    {
        // Implement file reading and SQL generation logic
        // This method should return an array of SQL packs
    }

    private function generatePatchCode($sqlPack)
    {
        // Implement patch code generation logic
        // This method should return a string of patch code
    }
}
