<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Machines;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Illuminate\Support\Facades\Log;
use PhpOffice\PhpSpreadsheet\Writer\Csv;

class MachineController extends Controller
{
    // Show Add Machine Form
    public function addMachine()
    {
        return view('admin.machine.addmachine');
    }

    // Store Machine Data
    public function storeMachine(Request $request)
    {
        $request->validate([
            'machine_id'     => 'required|unique:machines',
            'machine_sl_no'  => 'nullable',
            'diameter'       => 'nullable',
            'length'         => 'nullable',
            'weight'         => 'nullable',
        ]);

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

        return redirect()->route('admin.machine.machinedetails')->with('success', 'Machine added successfully.');
    }

    // List All Machines
    public function machineDetails()
    {
        $machines = Machines::latest()->get();
        return view('admin.machine.machinedetails', compact('machines'));
    }

    // Show Edit Machine Form
    public function editMachine($id)
    {
        $machine = Machines::findOrFail($id);
        return view('admin.machine.editmachine', compact('machine'));
    }

    // Update Machine Data
    public function updateMachine(Request $request, $id)
    {
        $machine = Machines::findOrFail($id);

        $request->validate([
            'machine_id'     => 'required|unique:machines,machine_id,' . $machine->id,
            'machine_sl_no'  => 'nullable',
            'diameter'       => 'nullable',
            'length'         => 'nullable',
            'weight'         => 'nullable',
        ]);

        $machine->update($request->all());

        return redirect()->route('admin.machine.machinedetails')->with('success', 'Machine updated successfully.');
    }

    // Delete Machine
    public function deleteMachine($id)
    {
        $machine = Machines::findOrFail($id);
        $machine->delete();

        return response()->json(['success' => true]);
    }
    public function importMachines(Request $request)
    {
        $request->validate([
            'excel_file' => 'required|file|mimes:xlsx',
        ]);

        $file = $request->file('excel_file');
        Log::info('Bulk machine import started by user.', [
            'user_id' => auth()->id(), // Or add user name if needed
            'filename' => $file->getClientOriginalName(),
            'timestamp' => now()->toDateTimeString()
        ]);

        try {
            $spreadsheet = IOFactory::load($file->getRealPath());
            $worksheet = $spreadsheet->getActiveSheet();
            $rows = $worksheet->toArray(null, true, true, true);

            // Assume first row is headers
            // Get header row values (ignore keys 'A','B',...) and re-index as numeric
            $headerRow = array_map('strtolower', array_map('trim', array_values($rows[1])));
            $expectedHeaders = [
                'machine_id',
                'machine_name',
                'machine_sl_no',
                'make',
                'model_type',
                'diameter',
                'length',
                'weight',
                'remarks'
            ];

            // Validate headers (strict check, order matters)
            if ($headerRow !== $expectedHeaders) {
                Log::error('Invalid template format detected during bulk import.', [
                    'provided_header' => $headerRow,
                    'expected_header' => $expectedHeaders
                ]);
                return back()->with('error', 'Invalid template format. Please use the provided sample template.');
            }


            $successCount = 0;
            $errorCount = 0;
            $errorRows = [];

            DB::beginTransaction();

            foreach (array_slice($rows, 1) as $index => $row) {
                if ($index == 0) continue; // skip header

                $rowData = array_combine($expectedHeaders, array_map('trim', array_values($row)));

                $validator = Validator::make($rowData, [
                    'machine_id'     => 'required|unique:machines,machine_id',
                    'machine_sl_no'  => 'nullable',
                    'diameter'       => 'nullable',
                    'length'         => 'nullable',
                    'weight'         => 'nullable',
                ]);

                if ($validator->fails()) {
                    $errorCount++;
                    $errorMsg = "Row " . ($index + 1) . ": " . implode('; ', $validator->errors()->all());
                    $errorRows[] = $errorMsg;
                    Log::warning('Validation failed for machine import row.', [
                        'row_number' => $index + 1,
                        'errors' => $validator->errors()->all(),
                        'row_data' => $rowData
                    ]);
                    continue;
                }

                try {
                    Machines::create($rowData);
                    $successCount++;
                } catch (\Exception $e) {
                    $errorCount++;
                    $errorMsg = "Row " . ($index + 1) . ": " . $e->getMessage();
                    $errorRows[] = $errorMsg;
                    Log::error('Exception while importing machine row.', [
                        'row_number' => $index + 1,
                        'row_data' => $rowData,
                        'exception' => $e->getMessage()
                    ]);
                }
            }

            DB::commit();

            Log::info('Bulk machine import completed.', [
                'user_id' => auth()->id(),
                'imported_count' => $successCount,
                'error_count' => $errorCount
            ]);

            $message = "{$successCount} machines imported.";
            if ($errorCount > 0) {
                $message .= " {$errorCount} errors. See below.";
                Log::warning('Bulk import finished with errors.', [
                    'error_rows' => $errorRows
                ]);
                return back()->with('success', $message)->with('errorRows', $errorRows);
            }

            return back()->with('success', $message);
        } catch (\Exception $e) {
            Log::critical('Bulk machine import failed with exception.', [
                'exception' => $e->getMessage(),
                'file' => $file ? $file->getClientOriginalName() : null,
                'user_id' => auth()->id()
            ]);
            return back()->with('error', 'Failed to import: ' . $e->getMessage());
        }
    }
}
