<?php

namespace App\Controllers;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

use App\Models\ModelService;
use App\Models\ModelSiswa;

class Services extends BaseController
{
    protected $modelService;
    protected $modelSiswa;

    public function __construct()
    {
        // Cek apakah pengguna sudah login
        if (!session()->get('isLoggedIn')) {
            return redirect()->to('/login'); // Arahkan ke halaman login jika belum login
        }
        $this->modelService = new ModelService();
        // untuk helper format rupiah
        helper('currency_helper');
    }

    public function index()
    {
        $dataServices = $this->modelService->getAllData();
        $dataBreadcumb = 'Services';

        $data = [
            'Breadcumb' => $dataBreadcumb,
            'service' => $dataServices
        ];

        return view('service/index', $data);
    }

    public function getData($id_service)
    {
        if ($this->request->isAJAX()) {
            $data = $this->modelService->find($id_service); // Ambil data berdasarkan ID

            if ($data) {
                echo json_encode($data); // Kirim data ke frontend
            } else {
                echo json_encode(null);
            }
        }
    }

    public function tambahData()
    {
        if ($this->request->isAJAX()) {

            // Ambil data dari request POST
            $priceInput                  = $this->request->getVar('price');
            // Hapus "Rp" dan titik pemisah ribuan
            $priceBersih = str_replace(['Rp', '.', ' '], '', $priceInput);
            // Pastikan priceBersih adalah angka
            $priceDecimal = is_numeric($priceBersih) ? (float)$priceBersih : 0;

            $name            = $this->request->getVar('name');
            $description              = $this->request->getVar('description');
            $duration_minutes               = $this->request->getVar('duration_minutes');

            // Validasi data (mengecek field kosong satu per satu)
            $errors = [];

            if (empty($name)) {
                $errors[] = 'Nama';
            }
            if (empty($description)) {
                $errors[] = 'description';
            }
            if (empty($priceInput)) {
                $errors[] = 'Price';
            }
            if (empty($duration_minutes)) {
                $errors[] = 'duration_minutes';
            }

            if (!empty($errors)) {
                $msg = [
                    'status' => 'error',
                    'message' => 'Field berikut harus diisi: ' . implode(', ', $errors)
                ];
                echo json_encode($msg);
                return;
            }

            // Siapkan data untuk disimpan
            $data = [
                'name'       => $name,
                'description'         => $description,
                'duration_minutes'          => $duration_minutes,
                'price'          => $priceDecimal,
            ];

            // Memanggil method tambahData() dari model untuk insert data
            if ($this->modelService->tambahData($data)) {
                $msg = ['status' => 'success', 'message' => 'Data Services berhasil ditambahkan'];
                echo json_encode($msg);
            } else {
                $msg = ['status' => 'error', 'message' => 'Terjadi kesalahan saat menambahkan data'];
                echo json_encode($msg);
            }
        }
    }

    public function updateData()
    {
        if ($this->request->isAJAX()) {
            // Ambil data dari request POST
            $priceInput                  = $this->request->getVar('price');
            // Hapus "Rp" dan titik pemisah ribuan
            $priceBersih = str_replace(['Rp', '.', ' '], '', $priceInput);
            // Pastikan priceBersih adalah angka
            $priceDecimal = is_numeric($priceBersih) ? (float)$priceBersih : 0;

            $id_service = $this->request->getVar('id_service');
            $name            = $this->request->getVar('name');
            $description              = $this->request->getVar('description');
            $duration_minutes               = $this->request->getVar('duration_minutes');



            // Validasi data (mengecek field kosong satu per satu)
            $errors = [];

            if (empty($name)) {
                $errors[] = 'Nama';
            }
            if (empty($description)) {
                $errors[] = 'description';
            }
            if (empty($priceInput)) {
                $errors[] = 'Price';
            }
            if (empty($duration_minutes)) {
                $errors[] = 'duration_minutes';
            }

            if (!empty($errors)) {
                $msg = [
                    'status' => 'error',
                    'message' => 'Field berikut harus diisi: ' . implode(', ', $errors)
                ];
                echo json_encode($msg);
                return;
            }


            $data = [
                'name'       => $name,
                'description'         => $description,
                'duration_minutes'          => $duration_minutes,
                'price'          => $priceDecimal,
            ];

            // Memanggil method updateData() dari model untuk insert data
            if ($this->modelService->updateData($id_service, $data)) {
                $msg = ['status' => 'success', 'message' => 'Data Services berhasil di update'];
            } else {
                $msg = ['error' => 'Terjadi kesalahan saat menambahkan data'];
            }

            echo json_encode($msg);
        }
    }

    public function deleteData()
    {
        if ($this->request->isAJAX()) {
            // Ambil data dari request
            $id_service = $this->request->getVar('id_service');

            // Validasi apakah ID ada
            if (!$id_service) {
                return $this->response->setJSON(['error' => 'Terjadi kesalahan saat Hapus data']);
            }

            // Inisialisasi model


            // Cari data berdasarkan ID
            $serviceData = $this->modelService->find($id_service);
            if (!$serviceData) {
                return $this->response->setJSON(
                    [
                        'error' => "Data service dengan ID $id_service tidak ditemukan"
                    ]
                );
            }

            // Ambil nama untuk pesan sukses
            $nama = $ServiceData['name'] ?? 'Tidak Diketahui';

            // Proses penghapusan data
            if ($this->modelService->delete($id_service)) {
                return $this->response->setJSON(['status' => 'success', 'message' => "Data Services $nama  berhasil dihapus"]);
            } else {
                return $this->response->setJSON([
                    'error' => "Terjadi kesalahan saat menghapus data Services"
                ]);
            }
        }

        // Jika bukan permintaan AJAX, tampilkan error
        return $this->response->setJSON([
            'error' => "Akses tidak valid"
        ]);
    }



    public function changeStatus()
    {
        $id_Services = $this->request->getPost('id_Services');
        $is_active = $this->request->getPost('is_active');


        if ($this->modelServices->update($id_Services, ['is_active' => $is_active])) {
            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Status Services berhasil diubah.'
            ]);
        } else {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Gagal mengubah status Produk.'
            ]);
        }
    }

    public function getServicesBySiswa($id_siswa)
    {
        $Services = $this->modelServices
            ->where('id_siswa', $id_siswa)
            ->where('is_active', 1)
            ->first();

        if ($Services) {
            echo json_encode($Services);
        } else {
            echo json_encode(null);
        }
    }

    public function importData()
    {
        $file = $this->request->getFile('fileImport');

        if ($file->isValid() && !$file->hasMoved()) {
            $ext = $file->getClientExtension();
            $validExtensions = ['xls', 'xlsx', 'csv'];

            if (in_array($ext, $validExtensions)) {
                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader(ucfirst($ext));
                $spreadsheet = $reader->load($file->getTempName());
                $data = $spreadsheet->getActiveSheet()->toArray();

                // Validasi dan simpan data
                $ServicesModel = new ModelServices();
                $rows = [];
                $duplicates = [];
                $errors = [];

                foreach ($data as $index => $row) {
                    if ($index === 0) continue; // Lewati header

                    // Pengecekan duplikasi berdasarkan NIK
                    $existing = $ServicesModel->where('nik', $row[1])->first();
                    if ($existing) {
                        $duplicates[] = $row[1]; // Simpan NIK yang duplikat
                        continue; // Skip data ini
                    }

                    $rows[] = [
                        'nama' => $row[0],
                        'nik' => $row[1],
                        'tanggal_lahir' => $row[2],
                        'jenis_kelamin' => $row[3],
                        'alamat' => $row[4],
                        'nama_ibu' => $row[5],
                        'nama_ayah' => $row[6],
                        'status_imunisasi' => $row[7],
                        'berat_badan' => $row[8],
                        'tinggi_badan' => $row[9],
                    ];
                }

                if (!empty($rows)) {
                    $ServicesModel->insertBatch($rows);
                    $message = 'Data berhasil diimport.';
                }

                // Jika ada duplikasi, tambahkan pesan
                if (!empty($duplicates)) {
                    $message = 'Data dengan NIK berikut sudah ada: ' . implode(', ', $duplicates) . '. ';
                }

                // Jika tidak ada data untuk diimport
                if (empty($rows) && empty($duplicates)) {
                    $message = 'Tidak ada data yang diimport.';
                }

                // Mengembalikan response
                if ($message) {
                    return $this->response->setJSON(['status' => 'success', 'message' => $message]);
                }
            }

            return $this->response->setJSON(['status' => 'error', 'message' => 'Format file tidak valid.']);
        }

        return $this->response->setJSON(['status' => 'error', 'message' => 'File tidak valid.']);
    }
}
