<?php

namespace App\Controllers;

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

class Patients extends BaseController
{
    protected $modelPatient;

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

        $this->modelPatient = new ModelPatient();
        helper(['text']); // untuk UUID
    }

    public function index()
    {
        $data = [
            'Breadcumb' => 'Patients',
            'patients'  => $this->modelPatient->getAllData()
        ];
        return view('patients/index', $data);
    }

    public function getData($id)
    {
        if ($this->request->isAJAX()) {
            $data = $this->modelPatient->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');

            $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 = [
                'id'             => uuid_create(UUID_TYPE_RANDOM),
                'nik'            => $nik,
                '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')
            ];

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

    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->modelPatient->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->modelPatient->find($id);

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

            if ($this->modelPatient->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.']);
    }
}
