<?php

namespace App\Controllers;

use PhpOffice\PhpSpreadsheet\IOFactory;
use App\Models\ModelPractitioners;

class Practitioners extends BaseController
{
    protected $modelPractitioners;

    public function __construct()
    {
        if (!session()->get('isLoggedIn')) {
            return redirect()->to('/login');
        }

        $this->modelPractitioners = new ModelPractitioners();
        helper(['text', 'uuid_helper']); // untuk UUID

    }

    public function index()
    {
        $data = [
            'Breadcumb' => 'Pasien',
            'Practitioners'  => $this->modelPractitioners->getAllData()
        ];
        return view('practitioners/index', $data);
    }

    public function getData($id)
    {
        if ($this->request->isAJAX()) {
            $data = $this->modelPractitioners->find($id);
            echo json_encode($data ?? null);
        }
    }


    public function tambahData()
    {
        if ($this->request->isAJAX()) {
            $nik           = $this->request->getVar('nik');
            $nama          = $this->request->getVar('nama');
            $tanggal_lahir = $this->request->getVar('tanggal_lahir');
            $jenis_kelamin = $this->request->getVar('jenis_kelamin');
            $alamat        = $this->request->getVar('alamat');
            $no_hp         = $this->request->getVar('no_hp');


            // Validasi input
            $errors = [];
            if (empty($nik)) $errors[] = 'NIK';
            if (empty($nama)) $errors[] = 'Nama';
            if (empty($tanggal_lahir)) $errors[] = 'Tanggal Lahir';
            if (empty($jenis_kelamin)) $errors[] = 'Jenis Kelamin';

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

            // Cek apakah NIK sudah terdaftar
            $cekNIK = $this->modelPractitioners->where('nik', $nik)->first();
            if ($cekNIK) {
                echo json_encode([
                    'status'  => 'error',
                    'message' => 'NIK sudah terdaftar. Silakan gunakan NIK lain.'
                ]);
                return;
            }

            // Generate No.RM otomatis
            $no_rm = $this->modelPractitioners->generateNoRM($tanggal_lahir);

            // Data yang akan disimpan
            $data = [
                'id'             => generate_uuid_v4(),
                'nik'            => $nik,
                'no_rm'          => $no_rm,
                'nama'           => $nama,
                'tanggal_lahir'  => $tanggal_lahir,
                'jenis_kelamin'  => $jenis_kelamin,
                'alamat'         => $alamat,
                'no_hp'          => $no_hp,
                'aktif'          => 1,
                'created_at'     => date('Y-m-d H:i:s'),
            ];

            // Simpan ke database
            if ($this->modelPractitioners->tambahData($data)) {
                echo json_encode([
                    'status'  => 'success',
                    'message' => 'Data pasien berhasil ditambahkan'
                ]);
            } else {
                echo json_encode([
                    'status'  => 'error',
                    'message' => 'Terjadi kesalahan saat menambahkan data pasien'
                ]);
            }
        }
    }


    public function updateData()
    {
        if ($this->request->isAJAX()) {
            $id             = $this->request->getVar('id');
            $nik            = $this->request->getVar('nik');
            $nama           = $this->request->getVar('nama');
            $tanggal_lahir  = $this->request->getVar('tanggal_lahir');
            $jenis_kelamin  = $this->request->getVar('jenis_kelamin');
            $alamat         = $this->request->getVar('alamat');
            $no_hp          = $this->request->getVar('no_hp');

            $errors = [];
            if (empty($nik)) $errors[] = 'NIK';
            if (empty($nama)) $errors[] = 'Nama';
            if (empty($tanggal_lahir)) $errors[] = 'Tanggal Lahir';

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

            $data = [
                'nik'           => $nik,
                'nama'          => $nama,
                'tanggal_lahir' => $tanggal_lahir,
                'jenis_kelamin' => $jenis_kelamin,
                'alamat'        => $alamat,
                'no_hp'         => $no_hp
            ];

            if ($this->modelPractitioners->updateData($id, $data)) {
                echo json_encode(['status' => 'success', 'message' => 'Data pasien berhasil diperbarui']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Gagal memperbarui data']);
            }
        }
    }

    public function deleteData()
    {
        if ($this->request->isAJAX()) {
            $id = $this->request->getVar('id');
            $data = $this->modelPractitioners->find($id);

            if (!$data) {
                return $this->response->setJSON(['error' => 'Data pasien tidak ditemukan']);
            }

            if ($this->modelPractitioners->deleteData($id)) {
                return $this->response->setJSON(['status' => 'success', 'message' => "Pasien {$data['nama']} berhasil dihapus"]);
            } else {
                return $this->response->setJSON(['error' => 'Gagal menghapus data pasien']);
            }
        }

        return $this->response->setJSON(['error' => 'Akses tidak valid']);
    }

    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 = IOFactory::createReader(ucfirst($ext));
                $spreadsheet = $reader->load($file->getTempName());
                $data = $spreadsheet->getActiveSheet()->toArray();

                $rows = [];
                $duplicates = [];

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

                    // Format: NIK | Nama | Tanggal Lahir | Jenis Kelamin | Alamat | No HP
                    $existing = $this->modelPatient->where('nik', $row[0])->first();
                    if ($existing) {
                        $duplicates[] = $row[0];
                        continue;
                    }

                    $rows[] = [
                        'id'             => uuid_create(UUID_TYPE_RANDOM),
                        'nik'            => $row[0],
                        'nama'           => $row[1],
                        'tanggal_lahir'  => $row[2],
                        'jenis_kelamin'  => strtolower($row[3]) === 'l' ? 'male' : 'female',
                        'alamat'         => $row[4],
                        'no_hp'          => $row[5],
                        'aktif'          => 1,
                        'created_at'     => date('Y-m-d H:i:s')
                    ];
                }

                if (!empty($rows)) {
                    $this->modelPatient->insertBatch($rows);
                }

                $message = !empty($duplicates)
                    ? 'Data duplikat: ' . implode(', ', $duplicates)
                    : 'Data pasien berhasil diimport.';

                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 ditemukan atau rusak.']);
    }

    public function changeStatus()
    {
        if ($this->request->isAJAX()) {
            $id     = $this->request->getVar('id');
            $status = $this->request->getVar('aktif');

            if (!$id || !in_array($status, ['0', '1'])) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Data tidak valid'
                ]);
            }

            $update = $this->modelPractitioners->update($id, ['aktif' => $status]);

            if ($update) {
                $text = $status == '1' ? 'diaktifkan' : 'dinonaktifkan';
                return $this->response->setJSON([
                    'status'  => 'success',
                    'message' => "Status pasien berhasil $text."
                ]);
            } else {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Gagal mengubah status.'
                ]);
            }
        }
    }
}
