<?php

namespace App\Controllers;

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

use App\Models\ModelBookings;
use App\Models\ModelCustomer;
use App\Models\ModelEmployees;
use App\Models\ModelService;

class Bookings extends BaseController
{
    protected $modelBookings;
    protected $modelCustomer;
    protected $modelEmployees;
    protected $modelService;

    public function __construct()
    {
        // Cek apakah pengguna sudah login
        if (!session()->get('isLoggedIn')) {
            return redirect()->to('/login'); // Arahkan ke halaman login jika belum login
        }
        $this->modelBookings = new ModelBookings();
        $this->modelCustomer = new ModelCustomer();
        $this->modelEmployees = new ModelEmployees();
        $this->modelService = new ModelService();

        // untuk helper format rupiah
        helper('currency_helper');
    }

    public function index()
    {
        $dataBookings = $this->modelBookings->getAllData();
        $dataCustomer = $this->modelCustomer->getAllData();
        $dataEmployess = $this->modelEmployees->getAllData();
        $dataService = $this->modelService->getAllData();
        $dataBreadcumb = 'Bookings';

        $data = [
            'Breadcumb' => $dataBreadcumb,
            'customer' => $dataCustomer,
            'employees' => $dataEmployess,
            'service' => $dataService,
            'bookings' => $dataBookings,
        ];

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

    public function getData($id_Bookings)
    {
        if ($this->request->isAJAX()) {
            $data = $this->modelBookings->find($id_Bookings); // 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()) {

            $id_customer            = $this->request->getVar('id_customer');
            $id_employee              = $this->request->getVar('id_employee');
            $id_service               = $this->request->getVar('id_service');
            $status               = $this->request->getVar('status');
            $booking_time               = $this->request->getVar('booking_time');

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

            if (empty($id_customer)) {
                $errors[] = 'Nama Customer';
            }
            if (empty($id_employee)) {
                $errors[] = 'id_employee';
            }
            if (empty($id_service)) {
                $errors[] = 'id_service';
            }
            if (empty($booking_time)) {
                $errors[] = 'booking_time';
            }
            if (empty($status)) {
                $errors[] = 'status';
            }

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

            // Siapkan data untuk disimpan
            $data = [
                'id_customer'       => $id_customer,
                'id_employee'         => $id_employee,
                'id_service'          => $id_service,
                'booking_time'          => $booking_time,
                'status'          => $status,
            ];

            // Memanggil method tambahData() dari model untuk insert data
            if ($this->modelBookings->tambahData($data)) {
                $msg = ['status' => 'success', 'message' => 'Data Bookings 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()) {
            $id_bookings = $this->request->getVar('id_bookings');
            $id_customer            = $this->request->getVar('id_customer');
            $id_employee              = $this->request->getVar('id_employee');
            $id_service               = $this->request->getVar('id_service');
            $status               = $this->request->getVar('status');
            $booking_time               = $this->request->getVar('booking_time');



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


            if (empty($id_customer)) {
                $errors[] = 'Nama Customer';
            }
            if (empty($id_employee)) {
                $errors[] = 'id_employee';
            }
            if (empty($id_service)) {
                $errors[] = 'id_service';
            }
            if (empty($booking_time)) {
                $errors[] = 'booking_time';
            }
            if (empty($status)) {
                $errors[] = 'status';
            }

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


            $data = [
                'id_customer'       => $id_customer,
                'id_employee'         => $id_employee,
                'id_service'          => $id_service,
                'booking_time'          => $booking_time,
                'status'          => $status,
            ];

            // Memanggil method updateData() dari model untuk insert data
            if ($this->modelBookings->updateData($id_bookings, $data)) {
                $msg = ['status' => 'success', 'message' => 'Data Bookings 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_bookings = $this->request->getVar('id_bookings');

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

            // Inisialisasi model


            // Cari data berdasarkan ID
            $BookingsData = $this->modelBookings->find($id_bookings);
            if (!$BookingsData) {
                return $this->response->setJSON(
                    [
                        'error' => "Data Bookings dengan ID $id_bookings tidak ditemukan"
                    ]
                );
            }

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

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

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



    public function changeStatus()
    {
        $id_bookings = $this->request->getPost('id_bookings');
        $status = $this->request->getPost('status');


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

    public function getBookingsBySiswa($id_siswa)
    {
        $Bookings = $this->modelBookings
            ->where('id_siswa', $id_siswa)
            ->where('is_active', 1)
            ->first();

        if ($Bookings) {
            echo json_encode($Bookings);
        } 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
                $BookingsModel = new ModelBookings();
                $rows = [];
                $duplicates = [];
                $errors = [];

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

                    // Pengecekan duplikasi berdasarkan NIK
                    $existing = $BookingsModel->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)) {
                    $BookingsModel->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.']);
    }
}
