<?php
require_once '_master/apiHandler.php';

class pageClass extends apiHandler
{
    public function __construct() {
        parent::__construct(); 
        //$this->checkERPAccess();
    }

    /**
     * List all product tags with pagination
     */
    function index() {
        try {
            $allowed = ['page', 'limit', 'search', 'parentid'];
            $fields = [
                'page' => [
                    'rules' => 'integer|min:1',
                    'type'  => 'integer',
                    'default' => 1
                ],
                'limit' => [
                    'rules' => 'integer|min:1|max:100',
                    'type'  => 'integer',
                    'default' => 10
                ],
                'search' => [
                    'rules' => 'text',
                    'type'  => 'string'
                ],
                'parentid' => [
                    'rules' => 'integer',
                    'type'  => 'integer'
                ]
            ];
            
            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) {
                $this->respond(400, false, $this->trans['httpStatusCodes']['400'], null, $request['validation_errors']);
            }

            $page = isset($request['page']) ? (int) $request['page'] : 1;
            $perPage = isset($request['limit']) ? (int) $request['limit'] : 10;
            $offset = ($page - 1) * $perPage;
            
            $where = '1=1 ';
            $params = [];
            
            if (!empty($request['search'])) {
                $where .= ' AND (name LIKE ? OR name_en LIKE ?)';
                $searchTerm = '%' . $request['search'] . '%';
                $params = array_merge($params, [$searchTerm, $searchTerm]);
            }
            
            if (isset($request['parentid']) && $request['parentid'] !== '') {
                $where .= ' AND parentid = ?';
                $params[] = $request['parentid'];
            }
            
            // Get total count
            $total = R::count('searchfilters', $where, $params);
            
            // Get paginated results
            $tags = R::findAll('searchfilters', 
                $where . ' ORDER BY id DESC LIMIT ?, ?', 
                array_merge($params, [$offset, $perPage])
            );
            
            $result = [];
            foreach ($tags as $tag) {
                $result[] = [
                    'id' => $tag->id,
                    'name' => $tag->name,
                    'name_en' => $tag->name_en,
                    'parentid' => $tag->parentid,
                    'conditions' => $tag->conditions,
                    'color_code' => $tag->color_code,
                    'created_at' => $tag->created_at
                ];
            }
            
            $response = [
                'data' => $result,
                'pagination' => [
                    'total' => (int)$total,
                    'limit' => (int)$perPage,
                    'current_page' => (int)$page,
                    'last_page' => ceil($total / $perPage)
                ]
            ];
            
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
            
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    /**
     * Add a new product tag
     */
    function add() {
        try {
            $allowed = ['name', 'name_en', 'parentid', 'conditions', 'color_code'];
            $fields = [
                'name' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'name_en' => [
                    'rules' => 'text|max:255',
                    'type'  => 'string',
                ],
                'parentid' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'conditions' => [
                    'rules' => 'integer|min:0|max:1',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'color_code' => [
                    'rules' => 'string|max:191|regex:/^[a-zA-Z0-9#]+$/',
                    'type'  => 'raw',
                    'message' => 'Color code can only contain letters, numbers, and #'
                ]
            ];

            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) {
                $this->respond(400, false, $this->trans['httpStatusCodes']['400'], null, $request['validation_errors']);
            }

            // Check if tag name already exists with the same parent
            if (helpers::valueExistsInTable('searchfilters', 'name = ? AND parentid = ?', [$request['name'], $request['parentid']])) {
                $this->respond(409, false, $this->trans['messages']['searchfilters']['nameExists'], null, ['name' => $this->trans['messages']['searchfilters']['nameExists']]);
            }

            $tag = R::dispense('searchfilters');
            $tag->name = $request['name'];
            $tag->name_en = $request['name_en'];
            $tag->parentid = (int)$request['parentid'];
            $tag->user_id = 1; // $this->userInfo->userid
            $tag->conditions = (int)$request['conditions'];
            $tag->color_code = $request['color_code'];
            $tag->created_at = date('Y-m-d H:i:s');
            $tag->updated_at = date('Y-m-d H:i:s');
            
            $id = R::store($tag);
            
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $tag);
            
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    /**
     * Get tag details by ID
     */
    function details() {
        try {
            $allowed = ['id'];
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ]
            ];
            
            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) {
                $this->respond(400, false, $this->trans['httpStatusCodes']['400'], null, $request['validation_errors']);
            }

            $tag = R::findOne('searchfilters', 'id = ?', [$request['id']]);
            
            if (!$tag) {
                $this->respond(404, false, $this->trans['httpStatusCodes']['404'], null, ['id' => $this->trans['messages']['searchfilters']['notFound']]);
            }
            
            $response = [
                'id' => $tag->id,
                'name' => $tag->name,
                'name_en' => $tag->name_en,
                'parentid' => $tag->parentid,
                'user_id' => $tag->user_id,
                'conditions' => $tag->conditions,
                'color_code' => $tag->color_code,
                'created_at' => $tag->created_at,
                'updated_at' => $tag->updated_at
            ];
            
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
            
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    /**
     * Update an existing tag
     */
    function update() {
        try {
            $allowed = ['id', 'name', 'name_en', 'parentid', 'conditions', 'color_code'];
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'name' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'name_en' => [
                    'rules' => 'text|max:255',
                    'type'  => 'string',
                ],
                'parentid' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'conditions' => [
                    'rules' => 'integer|min:0|max:1',
                    'type'  => 'integer'
                ],
                'color_code' => [
                    'rules' => 'string|max:191|regex:/^[a-zA-Z0-9#]+$/',
                    'type'  => 'raw',
                    'message' => 'Color code can only contain letters, numbers, and #'
                ]
            ];

            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) {
                $this->respond(400, false, $this->trans['httpStatusCodes']['400'], null, $request['validation_errors']);
            }

            // Check if tag exists
            $tag = R::findOne('searchfilters', 'id = ?', [$request['id']]);
            if (!$tag) {
                $this->respond(404, false, $this->trans['httpStatusCodes']['404'], null, ['id' => $this->trans['messages']['searchfilters']['notFound']]);
            }

            // Check if another tag with the same name and parent already exists
            $existing = R::findOne('searchfilters', 'name = ? AND parentid = ? AND id != ?', 
                [$request['name'], $request['parentid'], $request['id']]);
            
            if ($existing) {
                $this->respond(409, false, $this->trans['messages']['searchfilters']['nameExists'], null, ['name' => $this->trans['messages']['searchfilters']['nameExists']]);
            }

            // Update tag
            $tag->name = $request['name'];
            $tag->name_en = isset($request['name_en']) ? $request['name_en'] : $tag->name_en;
            $tag->parentid = isset($request['parentid']) ? (int)$request['parentid'] : $tag->parentid;
            $tag->conditions = isset($request['conditions']) ? (int)$request['conditions'] : $tag->conditions;
            $tag->color_code = isset($request['color_code']) ? $request['color_code'] : $tag->color_code;
            $tag->updated_at = date('Y-m-d H:i:s');
            
            R::store($tag);
            
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $tag);
            
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    /**
     * Delete a tag
     */
    function delete() {
        try {
            $allowed = ['id'];
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ]
            ];
            
            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) {
                $this->respond(400, false, $this->trans['httpStatusCodes']['400'], null, $request['validation_errors']);
            }

            // Check if tag exists
            $tag = R::findOne('searchfilters', 'id = ?', [$request['id']]);
            if (!$tag) {
                $this->respond(404, false, $this->trans['httpStatusCodes']['404'], null, ['id' => $this->trans['messages']['searchfilters']['notFound']]);
            }

            // Check if tag has children
            $childCount = R::count('searchfilters', 'parentid = ?', [$request['id']]);
            if ($childCount > 0) {
                $this->respond(400, false, $this->trans['httpStatusCodes']['400'], null, ['id' => $this->trans['messages']['searchfilters']['hasChildren']]);
            }

            // Delete the tag
            R::trash($tag);
            
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], ['id' => $request['id']]);
            
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }
}

require_once("_master/fireApi.php");