<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Producttype;
use App\Models\Product;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ProducttypeImport;

class ProducttypeController extends Controller
{
    public function getProducttype()
    {
        $data = Producttype::all();

        $response = [
            'success' => true,
            'producttype' => $data,
        ];

        return response($response, 200);
    }

    public function getProducttypeDetail(Request $request)
    {
        $data = Producttype::find($request->id);

        $response = [
            'success' => true,
            'producttype' => $data,
        ];

        return response($response, 200);
    }

    public function createProducttype(Request $request)
    {
        $request->validate([
            'name' => 'required',
        ]);

        $check = Producttype::where('name', $request->name)->first();
        if ($check) {
            $response = [
                'success' => false,
                'message'  => 'Nama sudah dipakai',
            ];
            return response($response, 400);
        }

        $data = new Producttype;
        $data->name = $request->name;
        $data->save();

        $response = [
            'success' => true,
            'producttype' => $data,
        ];

        return response($response, 200);
    }

    public function editProducttype(Request $request)
    {
        $request->validate([
            'name' => 'required',
        ]);

        $check = Producttype::where('name', $request->name)->first();
        if ($check) {
            $response = [
                'success' => false,
                'message'  => 'Nama sudah dipakai',
            ];
            return response($response, 400);
        }

        $data = Producttype::find($request->id);
        $data->name = $request->name;
        $data->save();

        $response = [
            'success' => true,
            'producttype' => $data,
        ];

        return response($response, 200);
    }

    public function deleteProducttype(Request $request)
    {

        $products = Product::where('producttype', '=', $request->id)
            ->get()
            ->map(function ($item) {
                return $item->name;
            });

        if (count($products) > 0) {
            $response = [
                'success' => false,
                'message' => "silahkan hapus produk " . join(", ", json_decode($products, true)) . " terlebih dahulu",
            ];

            return response($response, 400);
        }

        $data = Producttype::find($request->id);
        $data->delete();

        $response = [
            'success' => true,
            'product' => $products,
        ];

        return response($response, 200);
    }

    public function importProducttype(Request $request)
    {
        $items = [];
        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $ext = strtolower($file->getClientOriginalExtension());
            if (in_array($ext, ['xlsx', 'xls'])) {
                $import = new ProducttypeImport();
                Excel::import($import, $file);
                $results = $import->getResults();
                $response = [
                    'success' => true,
                    'created_count' => count($results['created']),
                    'skipped_count' => count($results['skipped']),
                    'created' => $results['created'],
                    'skipped' => $results['skipped']
                ];
                return response($response, 200);
            }
            if ($file->isValid()) {
                $handle = fopen($file->getRealPath(), 'r');
                if ($handle !== false) {
                    while (($row = fgetcsv($handle)) !== false) {
                        foreach ($row as $cell) {
                            $name = trim($cell);
                            if ($name !== '') {
                                $items[] = $name;
                            }
                        }
                    }
                    fclose($handle);
                }
            }
        }
        $inputItems = $request->input('items', []);
        if (is_array($inputItems)) {
            foreach ($inputItems as $it) {
                $name = is_array($it) ? ($it['name'] ?? '') : $it;
                $name = is_string($name) ? trim($name) : '';
                if ($name !== '') {
                    $items[] = $name;
                }
            }
        }
        $items = array_values(array_unique($items));
        if (count($items) === 0) {
            $response = [
                'success' => false,
                'message' => 'items kosong'
            ];
            return response($response, 400);
        }
        $created = [];
        $skipped = [];
        foreach ($items as $name) {
            $exists = Producttype::where('name', $name)->first();
            if ($exists) {
                $skipped[] = $name;
                continue;
            }
            $data = new Producttype;
            $data->name = $name;
            $data->save();
            $created[] = $data;
        }
        $response = [
            'success' => true,
            'created_count' => count($created),
            'skipped_count' => count($skipped),
            'created' => $created,
            'skipped' => $skipped
        ];
        return response($response, 200);
    }
}
