<?php

namespace App\Controllers\View;

use App\Controllers\BaseController;
use App\Models\AttendanceCommentTemplateModel;

class AttendanceCommentTemplateController extends BaseController
{
    protected $templateModel;

    public function __construct()
    {
        $this->templateModel = new AttendanceCommentTemplateModel();
    }

    // Method to load configuration management page
    public function index()
    {
        helper('url');
        return view('attendance_templates/index', [
            'templateEndpoint' => site_url('api/attendance-templates'),
        ]);
    }

    

    public function save()
    {
        $id = $this->request->getPost('id');
        $data = [
            'min_score'     => $this->request->getPost('min_score'),
            'max_score'     => $this->request->getPost('max_score'),
            'template_text' => $this->request->getPost('template_text'),
            'is_active'     => $this->request->getPost('is_active') === 'on' ? 1 : 0,
        ];

        if ($id) {
            $this->templateModel->update($id, $data);
        } else {
            $this->templateModel->insert($data);
        }

        return $this->response->setJSON(['status' => 'success']);
    }

    public function delete()
    {
        $id = $this->request->getPost('id');
        if ($id) {
            $this->templateModel->delete($id);
            return $this->response->setJSON(['status' => 'success']);
        }
        return $this->response->setJSON(['status' => 'error', 'message' => 'ID not provided']);
    }

    public function listData()
    {
        $rows = $this->templateModel
            ->orderBy('min_score', 'ASC')
            ->findAll();

        $templates = array_map(static function ($row) {
            if (!is_array($row)) {
                return [];
            }
            return [
                'id'            => (int) ($row['id'] ?? 0),
                'min_score'     => (int) ($row['min_score'] ?? 0),
                'max_score'     => (int) ($row['max_score'] ?? 0),
                'template_text' => (string) ($row['template_text'] ?? ''),
                'is_active'     => (bool) ($row['is_active'] ?? false),
            ];
        }, $rows ?? []);

        return $this->response->setJSON(['templates' => $templates]);
    }
}
