<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ProductsImport;
use App\Imports\ProductsSheetImport;
use App\Imports\MultiUnitsImport;
use App\Imports\CapitalGoodsImport;
use App\Imports\CapitalImport;
use App\Imports\MultiUnitsSheetImport;
use App\Imports\StockOpnameImport;
use Symfony\Component\HttpFoundation\Response;

class ImportController extends Controller
{
    public function importProduct(Request $request)
    {
        // Validate the file input
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls|max:10240',
        ]);

        try {
            $import = new ProductsSheetImport;
            Excel::import($import, $request->file('file'));

            // Get the results of the import
            $results = $import->getResults();

            // Return success response with details of successful and failed rows
            return response()->json([
                'success' => true,
                'message' => 'Products imported successfully!',
                'successfulRows' => $results['successfulRows'],
                'failedRows' => $results['failedRows'],
            ], Response::HTTP_OK);
        } catch (\Exception $e) {
            // Handle exceptions and return error response
            return response()->json([
                'success' => false,
                'message' => 'Failed to import products: ' . $e->getMessage(),
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public function importMultiUnit(Request $request)
    {
        // Validasi file input
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls|max:2048',
        ]);

        $successfulRows = [];
        $failedRows = [];

        try {
            // Import hanya sheet "import_multi_satuan"
            Excel::import(
                new MultiUnitsSheetImport($successfulRows, $failedRows),
                $request->file('file')
            );

            // Kalau sheet tidak ada sama sekali
            if (empty($successfulRows) && empty($failedRows)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Sheet "import_multi_satuan" tidak ditemukan pada file Excel.',
                ], Response::HTTP_BAD_REQUEST);
            }

            // Return sukses
            return response()->json([
                'success' => true,
                'message' => 'Multi units imported successfully!',
                'successfulRows' => $successfulRows,
                'failedRows' => $failedRows,
            ], Response::HTTP_OK);
        } catch (\Exception $e) {
            // Tangkap error & return response gagal
            return response()->json([
                'success' => false,
                'message' => 'Failed to import multi units: ' . $e->getMessage(),
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public function importCapitalGoods(Request $request)
    {
        // Validate the request
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls|max:10240',
            'staff' => 'required',
            'date' => 'required|date',
            'type' => 'nullable',
            'description' => 'nullable'
        ]);

        try {
            $import = new CapitalGoodsImport(
                $request->staff,
                $request->date,
                $request->type,
                $request->description
            );

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

            // Get the results of the import
            $results = $import->getResults();

            // Check if no rows were successfully imported
            if (empty($results['successfulRows'])) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tidak ada data yang bisa diimport. Cek kembali file anda, dan coba lagi!',
                    'successfulRows' => [],
                    'failedRows' => $results['failedRows'],
                ], Response::HTTP_BAD_REQUEST);
            }

            return response()->json([
                'success' => true,
                'message' => 'Capital goods imported successfully!',
                'successfulRows' => $results['successfulRows'],
                'failedRows' => $results['failedRows'],
            ], Response::HTTP_OK);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to import capital goods: ' . $e->getMessage(),
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public function importCapital(Request $request)
    {
        // Validate the request
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls|max:10240',
        ]);

        try {
            $import = new CapitalImport();

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

            // Get the results of the import
            $results = $import->getResults();

            // Check if no rows were successfully imported
            if (empty($results['successfulRows'])) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tidak ada data yang bisa diimport. Cek kembali file anda, dan coba lagi!',
                    'successfulRows' => [],
                    'failedRows' => $results['failedRows'],
                ], Response::HTTP_BAD_REQUEST);
            }

            return response()->json([
                'success' => true,
                'message' => 'Capital goods imported successfully!',
                'data' => $results['successfulRows'],
            ], Response::HTTP_OK);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to import capital goods: ' . $e->getMessage(),
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public function importStockOpname(Request $request)
    {
        // Validate the request
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls|max:10240',
        ]);

        try {
            $import = new StockOpnameImport();

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

            // Get the results of the import
            $results = $import->getResults();

            // Check if no rows were successfully imported
            if (empty($results['successfulRows'])) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tidak ada data yang bisa diimport. Cek kembali file anda, dan coba lagi!',
                    'successfulRows' => [],
                    'failedRows' => $results['failedRows'],
                ], Response::HTTP_BAD_REQUEST);
            }

            return response()->json([
                'success' => true,
                'message' => 'Capital goods imported successfully!',
                'data' => $results['successfulRows'],
            ], Response::HTTP_OK);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to import capital goods: ' . $e->getMessage(),
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
}
