<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ServerModel;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\API\ResponseTrait;


class Server extends BaseController
{
    var $model, $validation;
    use ResponseTrait;
    function __construct()
    {
        $this->model = new ServerModel();
        $this->validation = \Config\Services::validation();
        helper("cookie");
        helper("global_fungsi_helper");
    }
    public function getIndex()
{
    $servers = $this->model->orderBy('next_maintenance', 'ASC')
                          ->findAll();

    return view('admin/server/index', ['servers' => $servers]);
}
    function getAdd()
    {
        $data['title'] = "Tambah Server";
        $data['detail'] = [];
        $data['action'] = "add";
        $data['alert'] = "";
        $data['tombol'] = "+ Tambah Data Server";
        echo view('admin/server/form', $data);
    }
    public function postData()
    {
        $action = $this->request->getVar('action');

        // Basic validation rules that apply to both add and update
        $rules = [
            'server_name' => [
                'rules' => 'required',
                'errors' => [
                    'required' => 'Nama Server harus diisi'
                ]
            ],
            'cpu_core' => [
                'rules' => 'required|numeric',
                'errors' => [
                    'required' => 'Core CPU harus diisi',
                    'numeric' => 'Core CPU harus berupa angka'
                ]
            ],
            'ram' => [
                'rules' => 'required|numeric',
                'errors' => [
                    'required' => 'RAM harus diisi',
                    'numeric' => 'RAM harus berupa angka'
                ]
            ],
            'storage' => [
                'rules' => 'required|numeric',
                'errors' => [
                    'required' => 'Storage harus diisi',
                    'numeric' => 'Storage harus berupa angka'
                ]
            ],
            'operating_system' => [
                'rules' => 'required',
                'errors' => [
                    'required' => 'Sistem Operasi harus diisi'
                ]
            ],
            'server_date' => [
                'rules' => 'required|valid_date',
                'errors' => [
                    'required' => 'Tanggal aktif harus diisi',
                    'valid_date' => 'Tanggal tidak valid'
                ]
            ],
            'last_evaluated' => [
                'rules' => 'required|valid_date',
                'errors' => [
                    'required' => 'Tanggal evaluasi harus diisi',
                    'valid_date' => 'Tanggal tidak valid'
                ]
            ],
            'next_maintenance' => [
                'rules' => 'required|valid_date',
                'errors' => [
                    'required' => 'Jadwal pemeliharaan harus diisi',
                    'valid_date' => 'Tanggal tidak valid'
                ]
            ]
        ];

        if (!$this->validate($rules)) {
            $errors = $this->validator->getErrors();
            return $this->respond(['errors' => $errors], 400);
        }

        // Process the data based on action (add/update)
        switch ($action) {
            case "add":
                // Additional rules for add action if needed
                $rulesAdd = [
                    'server_name' => [
                        'rules' => 'required|is_unique[server.server_name]',
                        'errors' => [
                            'is_unique' => 'Nama Server sudah digunakan'
                        ]
                    ]
                ];

                if (!$this->validate($rulesAdd)) {
                    $errorsAdd = $this->validator->getErrors();
                    return $this->respond(['errors' => $errorsAdd], 400);
                }

                // Prepare data for insertion
                $requestData = [
                    'server_name' => $this->request->getVar('server_name'),
                    'kepemilikan_dropdown' => $this->request->getVar('kepemilikan_dropdown'),
                    'cpu_core' => $this->request->getVar('cpu_core'),
                    'ram' => $this->request->getVar('ram'),
                    'storage' => $this->request->getVar('storage'),
                    'status' => $this->request->getVar('status'),
                    'operating_system' => $this->request->getVar('operating_system'),
                    'server_date' => $this->request->getVar('server_date'),
                    'last_evaluated' => $this->request->getVar('last_evaluated'),
                    'next_maintenance' => $this->request->getVar('next_maintenance')
                ];

                // Handle conditional fields for ownership
                if ($this->request->getVar('kepemilikan_dropdown') === 'lainnya') {
                    $requestData['kepemilikan_lainnya'] = $this->request->getVar('kepemilikan_lainnya');
                    $requestData['serah_terima'] = $this->request->getVar('serah_terima');
                    $requestData['penanggung_jawab'] = $this->request->getVar('penanggung_jawab');
                } else {
                    $requestData['kepemilikan_lainnya'] = null;
                    $requestData['serah_terima'] = null;
                    $requestData['penanggung_jawab'] = null;
                }

                // Insert the data
                $this->model->insert($requestData);

                return $this->respond([
                    'status' => 'success',
                    'message' => 'Server berhasil ditambahkan'
                ], 200);

            case "update":
                // Get the existing server data
                $detail = $this->model->find($this->request->getVar('id'));

                if (!$detail) {
                    return $this->respond([
                        'status' => 'error',
                        'message' => 'Server tidak ditemukan'
                    ], 404);
                }

                // Additional rules for update if needed (e.g., unique server_name excluding current record)
                $rulesUpdate = [
                    'server_name' => [
                        'rules' => "required|is_unique[server.server_name,id,{$detail['id']}]",
                        'errors' => [
                            'is_unique' => 'Nama Server sudah digunakan'
                        ]
                    ]
                ];

                if (!$this->validate($rulesUpdate)) {
                    $errorsUpdate = $this->validator->getErrors();
                    return $this->respond(['errors' => $errorsUpdate], 400);
                }

                // Prepare data for update
                $requestData = [
                    'server_name' => $this->request->getVar('server_name'),
                    'kepemilikan_dropdown' => $this->request->getVar('kepemilikan_dropdown'),
                    'cpu_core' => $this->request->getVar('cpu_core'),
                    'ram' => $this->request->getVar('ram'),
                    'storage' => $this->request->getVar('storage'),
                    'status' => $this->request->getVar('status'),
                    'operating_system' => $this->request->getVar('operating_system'),
                    'server_date' => $this->request->getVar('server_date'),
                    'last_evaluated' => $this->request->getVar('last_evaluated'),
                    'next_maintenance' => $this->request->getVar('next_maintenance')
                ];

                // Handle conditional fields for ownership
                if ($this->request->getVar('kepemilikan_dropdown') === 'lainnya') {
                    $requestData['kepemilikan_lainnya'] = $this->request->getVar('kepemilikan_lainnya');
                    $requestData['serah_terima'] = $this->request->getVar('serah_terima');
                    $requestData['penanggung_jawab'] = $this->request->getVar('penanggung_jawab');
                } else {
                    $requestData['kepemilikan_lainnya'] = null;
                    $requestData['serah_terima'] = null;
                    $requestData['penanggung_jawab'] = null;
                }

                // Update the data
                $this->model->update($detail['id'], $requestData);

                return $this->respond([
                    'status' => 'success',
                    'message' => 'Server berhasil diperbarui'
                ], 200);
        }
    }
}
