<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Imports\ProductsImport;
use App\Imports\ProductsImportGeneral;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class ImportController extends Controller
{
    public function importProducts(Request $request)
    {
        $request->validate([
            'company' => 'required',
            'file' => 'required|mimes:csv,xls,xlsx|max:2048'
        ]);

        Excel::import(new ProductsImport($request->company), $request->file('file'));

        return redirect()->back()->with('success', 'CSV Imported Successfully!');
    }
    public function importProductsGeneral(Request $request)
    {
        try {
            // Validate file input
            $request->validate([
                'file' => 'required|mimes:csv,xls,xlsx|max:2048'
            ]);

            $file = $request->file('file');

            // Perform import
            Excel::import(new ProductsImportGeneral, $request->file('file'));

            return redirect()->back()->with('success', 'CSV Imported Successfully!');
        } catch (ValidationException $e) {
            return redirect()->back()->withErrors($e->errors())->withInput();
        } catch (ExcelValidationException $e) {
            // Catch Excel validation errors (like bad headers)
            $failures = $e->failures();
            foreach ($failures as $failure) {
                Log::error("Excel Import Error", [
                    'row' => $failure->row(),
                    'attribute' => $failure->attribute(),
                    'errors' => $failure->errors(),
                    'values' => $failure->values(),
                ]);
            }

            return redirect()->back()->withErrors(['file' => 'Excel import failed. Please check the file format and contents.'])->withInput();
        } catch (\Exception $e) {
            // Log general errors
            Log::error("Product import failed: " . $e->getMessage());

            return redirect()->back()->withErrors(['file' => 'Something went wrong while uploading the file.'])->withInput();
        }
    }
}
