<?php

namespace Modules\Lpj\Services;

use Modules\Lpj\Models\DaftarPustaka;

class DaftarPustakaService
{
    public function storeDaftarPustaka(array $data, $file)
    {
        if ($file) {
            $data['attachment'] = $this->handleUpload($file);
        }
        return DaftarPustaka::create($data);
    }

    public function updateDaftarPustaka($data, $file, $id)
    {
        // Ambil data inputan yang diperlukan saja

        $daftarPustaka = DaftarPustaka::findOrFail($id);

        // Jika ada file baru yang diupload
        if ($file) {
            // (Opsional) Hapus file lama
            if ($daftarPustaka->attachment && file_exists(public_path($daftarPustaka->attachment))) {
                unlink(public_path($daftarPustaka->attachment));
            }

            // Upload file baru
            $data['attachment'] = $this->handleUpload($file);
        }

        // Update data
        $daftarPustaka->update($data);

        return $daftarPustaka;
    }


    public function deleteDaftarPustaka($id)
    {
        return DaftarPustaka::where('id', $id)->delete();
    }

    public function getDaftarPustakaById($id)
    {
        return DaftarPustaka::where('id', $id)->first();
    }

    // get all with pagination
    public function getAllDaftarPustaka($request)
    {
        $query = DaftarPustaka::query();

        // Filter pencarian
        if (!empty($request->get('search'))) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->orWhere('judul', 'LIKE', "%$search%");
            });
        }

        // Filter kategori
        if (!empty($request->get('category'))) {
            $category = explode(',', $request->input('category'));
            $query->whereIn('category_id', $category);
        }

        // Default pagination
        $page = (int) $request->get('page', 1);
        $size = (int) $request->get('size', 10);

        return $query->paginate($size, ['*'], 'page', $page);
    }


    private function handleUpload($file)
    {
        $today = now();
        $folderPath = 'daftar_pustaka/' . $today->format('Y/m/d');

        $fileName = $file->getClientOriginalName();
        $filePath = $file->storeAs($folderPath, $fileName, 'public');

        return $filePath;
    }


}
