<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}" dir="{{ app()->getLocale() == 'ar' ? 'rtl' : 'ltr' }}">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>{{ __('Sas Radius Pro Dashboard') }}</title>
    <link rel="stylesheet" href="{{ asset('css/style.css') }}" />
    <!-- Bootstrap -->
    <link rel="stylesheet" href="{{ asset('css/bootstrap.css') }}" />
    <script src="{{ asset('js/bootstrap.js') }}"></script>
    <!-- Font Awesome -->
    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
        integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
        crossorigin="anonymous"
        referrerpolicy="no-referrer"
    />
    <style>
        .textarea-container {
            margin-top: 30px;
        }
        .textarea-container textarea {
            width: 100%;
            height: 200px;
            margin-bottom: 20px;
            resize: vertical;
        }
    </style>
</head>
<body>
    <main>
        <div class="overflow_sidebar"></div>
        <!-- Start sidebar -->
        <div class="sidebar">
            @include('include.sidebar')
        </div>
        <!-- End sidebar -->

        <div class="content_page">
            <div class="header">
                <div class="left">
                    <div class="icon_menu">
                        <!-- Menu Icon SVG -->
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
                        </svg>
                    </div>
                    <div class="logo_header">
                        <img src="{{ asset('images/logo.png') }}" alt="{{ __('logo') }}" loading="lazy" />
                    </div>
                    <div class="input_search">
                        <input type="text" placeholder="{{ __('Search...') }}" />
                        <!-- Search Icon SVG -->
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
                        </svg>
                    </div>
                </div>
                <div class="right">
                    @include('include.translation')
                    <div class="notification">
                        <div class="head">
                            <div class="icon">
                                <!-- Notification Icon SVG -->
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0M3.124 7.5A8.969 8.969 0 015.292 3m13.416 0a8.969 8.969 0 012.168 4.5" />
                                </svg>
                            </div>
                        </div>
                    </div>
                    <div class="nav_item">
                        <div class="head">
                            <img class="img_profile" src="{{ asset('images/user-1.jpg') }}" alt="user-1" loading="lazy" />
                        </div>
                        @include('include.profile')
                    </div>
                </div>
            </div>

            <div class="following_data_section">
                <div class="head">
                    <h4>{{ __('following_data_section.title') }}</h4>
                </div>
                <div class="content">
                    <div role="alert" class="alert alert-info">
                        <strong>{{ __('alerts.country_code_info') }}</strong>
                    </div>

                    <div class="line_inputs">
                        <div class="row">
                            <div class="col-12 col-md-6">
                                <div class="input_item">
                                    <label for="savebygrp">{{ __('labels.save_by_group') }}</label>
                                    <input id="savebygrp" type="text" placeholder="{{ __('placeholders.save_by_group') }}" />
                                </div>
                            </div>
                            <div class="col-12 col-md-6">
                                <div class="input_item">
                                    <label for="sascntNum">{{ __('labels.country_code') }}</label>
                                    <input id="sascntNum" type="text" placeholder="{{ __('placeholders.country_code') }}" />
                                </div>

                                <!-- Upload Excel Form -->
                                <div class="container mt-5">
                                    <h2>Upload Excel File</h2>

                                    @if ($errors->any())
                                        <div class="alert alert-danger">
                                            <strong>Whoops!</strong> There were some issues with your upload.<br><br>
                                            <ul>
                                                @foreach ($errors->all() as $error)
                                                    <li>{{ $error }}</li>
                                                @endforeach
                                            </ul>
                                        </div>
                                    @endif

                                    @if (session('success'))
                                        <div class="alert alert-success">
                                            {{ session('success') }}
                                        </div>
                                    @endif

                                    <form action="{{ route('upload.excel') }}" method="POST" enctype="multipart/form-data">
                                        @csrf
                                        <div class="form-group">
                                            <label for="excel_file">Choose Excel File:</label>
                                            <input type="file" name="excel_file" class="form-control" accept=".xlsx,.xls" required>
                                        </div>
                                        <button type="submit" class="btn btn-primary mt-3">Upload</button>
                                    </form>
                                </div>

                                <!-- Display Extracted Data -->
                                @if(isset($idgroups, $names, $countryCodes, $phoneNumbers))
                                    <div class="container mt-5">
                                        <h3>Extracted Data:</h3>
                                        <div class="textarea-container">
                                            <div class="form-group">
                                                <label for="idgroup">ID Group</label>
                                                <textarea id="idgroup" class="form-control" readonly>{{ implode(PHP_EOL, array_filter($idgroups)) }}</textarea>
                                            </div>

                                            <div class="form-group">
                                                <label for="name">Name</label>
                                                <textarea id="name" class="form-control" readonly>{{ implode(PHP_EOL, array_filter($names)) }}</textarea>
                                            </div>

                                            <div class="form-group">
                                                <label for="country_code">Country Code</label>
                                                <textarea id="country_code" class="form-control" readonly>{{ implode(PHP_EOL, array_filter($countryCodes)) }}</textarea>
                                            </div>

                                            <div class="form-group">
                                                <label for="phone_number">Phone Number</label>
                                                <textarea id="phone_number" class="form-control" readonly>{{ implode(PHP_EOL, array_filter($phoneNumbers)) }}</textarea>
                                            </div>
                                        </div>
                                    </div>
                                @endif

                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
     </main>
    <script>
        const codeinput = document.getElementById('sascntNum');
        const savebygrp = document.getElementById('savebygrp');
        const data = {
            'codeinput': '',
            'savebygrp': '',
            'operation': 'importsasuser/created',
        };
        
        function sendData() {
            fetch('/sas-config-customers', {
                method: 'post',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify(data)
            })
            .then(response => {
                if (!response.ok) {
                    console.log("Response unsuccessful");
                    return response.json().then(errorData => {
                        throw errorData;
                    });
                }
                logdata();
                console.log("Response successful");
                return response.json();
            })
            .then(responseData => {
                console.log("Response data:", responseData);
            })
            .catch(error => {
                console.error("Error:", error);
            });
            
            function logdata(){
                fetch('/data-logged', {
                    method: 'post',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify(data)
                });
            }
        }
        
        codeinput.addEventListener('input', function(event) {
            data['codeinput'] = event.target.value;
            sendData();
            console.log(data);
        });
        
        savebygrp.addEventListener('input', function(event) {
            data['savebygrp'] = event.target.value;
            sendData();
            console.log(data);
        });
        
        window.addEventListener('load', function() {
            if (codeinput.value) data['codeinput'] = codeinput.value;
            if (savebygrp.value) data['savebygrp'] = savebygrp.value;
        });
    </script>
    <script src="{{ asset('js/boxs-header.js') }}"></script>
    <script src="{{ asset('js/sidebar.js') }}"></script>
    <script src="{{ asset('js/nav-profile.js') }}"></script>
</body>
</html> <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Imports\YourDataImport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Storage;

class ExcelController extends Controller
{
    // Show the upload form
    public function showUploadForm()
    {
        return view('upload'); // Ensure this matches your Blade template name
    }

    // Handle the uploaded Excel file
    public function uploadExcel(Request $request)
    {
        // Validate the uploaded file
        $validator = Validator::make($request->all(), [
            'excel_file' => 'required|file|mimes:xlsx,xls',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        // Handle the uploaded file
        if ($request->hasFile('excel_file')) {
            $file = $request->file('excel_file');

            // Optionally, store the file in the 'public' disk (storage/app/public/uploads)
            $path = $file->store('uploads', 'public');

            try {
                // Create a new import instance
                $import = new YourDataImport;

                // Import the file from the stored path
                Excel::import($import, $path, 'public');

                // Access the data
                $idgroups = $import->getIdGroups();
                $names = $import->getNames();
                $countryCodes = $import->getCountryCodes();
                $phoneNumbers = $import->getPhoneNumbers();

                // Pass the data to the view
                return view('upload', compact('idgroups', 'names', 'countryCodes', 'phoneNumbers'))->with('success', 'Excel file uploaded and data extracted successfully.');
            } catch (\Exception $e) {
                return redirect()->back()->with('error', 'Error processing Excel file: ' . $e->getMessage());
            }
        }

        return redirect()->back()->with('error', 'No file uploaded.');
    }
} <?php

namespace App\Imports;

use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Collection;

class YourDataImport implements ToCollection, WithHeadingRow
{
    public $idgroups = [];
    public $names = [];
    public $countryCodes = [];
    public $phoneNumbers = [];

    public function collection(Collection $collection)
    {
        foreach ($collection as $row) {
            $this->idgroups[] = $row['idgroup'] ?? null;
            $this->names[] = $row['name'] ?? null;
            $this->countryCodes[] = $row['country_code'] ?? null;
            $this->phoneNumbers[] = $row['phone_number'] ?? null;
        }
    }

    public function getIdGroups() { return $this->idgroups; }
    public function getNames() { return $this->names; }
    public function getCountryCodes() { return $this->countryCodes; }
    public function getPhoneNumbers() { return $this->phoneNumbers; }
} when i add the excel to the file upload the page just refreshes and not show the textareas  so it doesnt wokr add error logging and fix that