query('q', '')); $query = Distributor::query()->orderByDesc('id'); if ($q !== '') { $query->where(function ($qq) use ($q) { $qq->where('nama', 'like', "%{$q}%") ->orWhere('alamat', 'like', "%{$q}%") ->orWhere('telepon', 'like', "%{$q}%"); }); } return response()->json([ 'data' => $query->get([ 'id', 'nama', 'alamat', 'telepon', 'created_at', 'updated_at', ]), ]); } public function store(Request $request): JsonResponse { $data = $request->validate([ 'nama' => ['required', 'string', 'max:150'], 'alamat' => ['nullable', 'string', 'max:255'], 'telepon' => ['nullable', 'string', 'max:50'], ]); $row = Distributor::create([ 'nama' => $data['nama'], 'alamat' => $data['alamat'] ?? null, 'telepon' => $data['telepon'] ?? null, ]); return response()->json(['data' => $row], 201); } public function update(Request $request, Distributor $distributor): JsonResponse { $data = $request->validate([ 'nama' => ['required', 'string', 'max:150'], 'alamat' => ['nullable', 'string', 'max:255'], 'telepon' => ['nullable', 'string', 'max:50'], ]); $distributor->update([ 'nama' => $data['nama'], 'alamat' => $data['alamat'] ?? null, 'telepon' => $data['telepon'] ?? null, ]); return response()->json(['data' => $distributor->fresh()]); } public function destroy(Distributor $distributor): JsonResponse { $distributor->delete(); return response()->json(['message' => 'Distributor dihapus.']); } public function import(Request $request): JsonResponse { $data = $request->validate([ 'file' => ['required', 'file', 'mimes:xlsx,xls,csv,txt', 'max:5120'], ]); $file = $data['file']; $ext = strtolower($file->getClientOriginalExtension()); if (in_array($ext, ['xlsx', 'xls'], true)) { if (!class_exists(\PhpOffice\PhpSpreadsheet\IOFactory::class)) { return response()->json([ 'message' => 'Import XLSX membutuhkan paket phpoffice/phpspreadsheet.', ], 422); } $rows = $this->readXlsx($file->getRealPath()); } else { $rows = $this->readCsv($file->getRealPath()); } if (count($rows) === 0) { return response()->json(['message' => 'File kosong atau format tidak valid.'], 422); } $inserted = 0; $skipped = 0; DB::transaction(function () use ($rows, &$inserted, &$skipped) { foreach ($rows as $row) { $nama = trim((string) ($row['nama'] ?? '')); if ($nama === '') { $skipped++; continue; } Distributor::create([ 'nama' => $nama, 'alamat' => isset($row['alamat']) && $row['alamat'] !== '' ? $row['alamat'] : null, 'telepon' => isset($row['telepon']) && $row['telepon'] !== '' ? $row['telepon'] : null, ]); $inserted++; } }); return response()->json([ 'message' => "Import selesai. Berhasil: {$inserted}, Dilewati: {$skipped}.", 'data' => [ 'inserted' => $inserted, 'skipped' => $skipped, ], ]); } public function template(): \Symfony\Component\HttpFoundation\StreamedResponse { $headers = [ 'Content-Type' => 'text/csv', 'Content-Disposition' => 'attachment; filename="template_distributor.csv"', ]; $callback = function () { $handle = fopen('php://output', 'w'); fputcsv($handle, ['nama', 'alamat', 'telepon']); fputcsv($handle, ['PT Contoh Distributor', 'Jl. Contoh No. 1', '08123456789']); fclose($handle); }; return response()->stream($callback, 200, $headers); } private function readCsv(string $path): array { $rows = []; $handle = fopen($path, 'r'); if (!$handle) { return $rows; } $header = null; while (($data = fgetcsv($handle, 0, ',')) !== false) { if ($data === [null] || $data === false) { continue; } if ($header === null) { $header = $this->normalizeHeader($data); if ($this->isHeaderRow($header)) { continue; } $rows[] = $this->mapRowByIndex($data); continue; } $rows[] = $this->mapRowByHeader($data, $header); } fclose($handle); return $rows; } private function readXlsx(string $path): array { $rows = []; $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path); $sheet = $spreadsheet->getActiveSheet(); $data = $sheet->toArray(null, true, true, true); if (count($data) === 0) { return $rows; } $first = array_shift($data); $header = $this->normalizeHeader(array_values($first ?? [])); $hasHeader = $this->isHeaderRow($header); if (!$hasHeader && $first) { $rows[] = $this->mapRowByIndex(array_values($first)); } foreach ($data as $row) { $values = array_values($row); $rows[] = $hasHeader ? $this->mapRowByHeader($values, $header) : $this->mapRowByIndex($values); } return $rows; } private function normalizeHeader(array $row): array { return array_map(function ($v) { $v = strtolower(trim((string) $v)); return preg_replace('/\s+/', '_', $v); }, $row); } private function isHeaderRow(array $header): bool { $fields = ['nama', 'alamat', 'telepon']; foreach ($fields as $f) { if (in_array($f, $header, true)) { return true; } } return false; } private function mapRowByHeader(array $row, array $header): array { $map = array_flip($header); return [ 'nama' => trim((string) ($row[$map['nama']] ?? '')), 'alamat' => trim((string) ($row[$map['alamat']] ?? '')), 'telepon' => trim((string) ($row[$map['telepon']] ?? '')), ]; } private function mapRowByIndex(array $row): array { return [ 'nama' => trim((string) ($row[0] ?? '')), 'alamat' => trim((string) ($row[1] ?? '')), 'telepon' => trim((string) ($row[2] ?? '')), ]; } }