<?php
require_once '_master/apiHandler.php';
//To Be Continued fatma
//dailyentryfun , affect plugins will be redbeans , add tree element with add()
//require_once '../dailyentryfun.php';

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

    /**
     * List all stores with pagination
     */
    function index() {
        try {
            $allowed = ['page', 'limit', 'search', 'branchId'];
            $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'
                ],
                'branchId' => [
                    'rules' => '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']);
            }

            $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 (storeName LIKE ? OR nameEn LIKE ? OR phone LIKE ? OR email LIKE ?)';
                $searchTerm = '%' . $request['search'] . '%';
                $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm, $searchTerm]);
            }
            
            if (!empty($request['branchId'])) {
                $where .= ' AND branchId = ?';
                $params[] = $request['branchId'];
            }
            
            // Get total count
            $total = R::count('store', $where, $params);
            
            // Get paginated results
            $stores = R::findAll('store', 
                $where . ' ORDER BY storeId DESC LIMIT ?, ?', 
                array_merge($params, [$offset, $perPage])
            );
            
            $result = [];
            foreach ($stores as $store) {
                $result[] = [
                    'storeId' => $store->storeId,
                    'storeName' => $store->storeName,
                    'nameEn' => $store->nameEn,
                    'branchId' => $store->branchId,
                    'phone' => $store->phone,
                    'email' => $store->email,
                    'storeDate' => $store->storeDate,
                    'createdAt' => $store->createdAt,
                    'updatedAt' => $store->updatedAt
                ];
            }
            
            $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 store
     */
    function add() {
        try {
            $allowed = ['storeName', 'nameEn', 'branchId', 'addressAr', 'addressEn', 'phone', 'email', 'storeDate', 'storeDescription'];
            $fields = [
                'storeName' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'nameEn' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'branchId' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'addressAr' => [
                    'rules' => 'required|text',
                    'type'  => 'string',
                ],
                'addressEn' => [
                    'rules' => 'required|text',
                    'type'  => 'string',
                ],
                'phone' => [
                    'rules' => 'required|text|max:20',
                    'type'  => 'string',
                ],
                'email' => [
                    'rules' => 'required|text|max:100',//email
                    'type'  => 'string',
                ],
                'storeDate' => [
                    'rules' => 'required|date',
                    'type'  => 'string',
                ],
                'storeDescription' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
            ];

            $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 store name already exists for this branch
            if (helpers::valueExistsInTable('store', 'storeName = ? AND branchId = ?', [$request['storeName'], $request['branchId']])) {
                $this->respond(409, false, $this->trans['messages']['store']['nameExists'], null, ['storeName' => $this->trans['messages']['store']['nameExists']]);
            }

            $store = R::dispense('store');
            $store->storeName = $request['storeName'];
            $store->nameEn = $request['nameEn'];
            $store->branchId = $request['branchId'];
            $store->addressAr = $request['addressAr'];
            $store->addressEn = $request['addressEn'];
            $store->phone = $request['phone'];
            $store->email = $request['email'];
            $store->storeDate = $request['storeDate'];
            $store->storeDescription = $request['storeDescription'];
            $store->conditions = 0;
            $store->userId = 1; // $this->userInfo->userid
            $store->treeId = 0;
            $store->treeIdBetween = 0;
            $store->webApiId = 0;
            $store->createdAt = date('Y-m-d H:i:s');
            $store->updatedAt = date('Y-m-d H:i:s');
            
            $id = R::store($store);
            $store->storeId = $id;

            // $treeId = addTreeElement($request['storeName'], 49, 3, 0, 1, '', 0, 0);
            // $treeIdBetween = addTreeElement($request['storeName'] . " وسيط", 49, 3, 0, 1, '', 0, 0);
            // $store->treeId = $treeId;
            // $store->treeIdBetween = $treeIdBetween;
            // R::exec("UPDATE store SET treeId = ?, treeIdBetween = ? WHERE storeId = ?", [$treeId, $treeIdBetween, $id]);
            
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $store);
            
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    /**
     * Get store 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']);
            }

            $store = R::findOne('store', 'storeId = ?', [$request['id']]);
            
            if (!$store) {
                $this->respond(404, false, $this->trans['httpStatusCodes']['404'], null, ['id' => $this->trans['messages']['store']['notFound']]);
            }
            
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $store);
            
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    /**
     * Update an existing store
     */
    function update() {
        try {
            $allowed = ['storeId', 'storeName', 'nameEn', 'branchId', 'addressAr', 'addressEn', 'phone', 'email', 'storeDate', 'storeDescription', 'conditions', 'treeId', 'treeIdBetween', 'webApiId'];
            $fields = [
                'storeId' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'storeName' => [
                    'rules' => 'text|min:1|max:255',
                    'type'  => 'string',
                ],
                'nameEn' => [
                    'rules' => 'text|min:1|max:255',
                    'type'  => 'string',
                ],
                'branchId' => [
                    'rules' => 'integer|min:1',
                    'type'  => 'integer',
                ],
                'addressAr' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'addressEn' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'phone' => [
                    'rules' => 'text|max:20',
                    'type'  => 'string',
                ],
                'email' => [
                    'rules' => 'text|max:100',//email
                    'type'  => 'string',
                ],
                'storeDate' => [
                    'rules' => 'date',
                    'type'  => 'string',
                ],
                'storeDescription' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'conditions' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'treeId' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'treeIdBetween' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'webApiId' => [
                    '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']);
            }

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

            // Check if store name already exists for this branch (if name or branch is being updated)
            $checkName = isset($request['storeName']) ? $request['storeName'] : $store->storeName;
            $checkBranchId = isset($request['branchId']) ? $request['branchId'] : $store->branchId;
            
            $existing = R::findOne('store', 'storeName = ? AND branchId = ? AND storeId != ?', 
                [$checkName, $checkBranchId, $store->storeId]);
                
            if ($existing) {
                $this->respond(409, false, $this->trans['messages']['store']['nameExists'], null, ['storeName' => $this->trans['messages']['store']['nameExists']]);
            }

            // Update fields if they are provided in the request
            $updatableFields = ['storeName', 'nameEn', 'branchId', 'addressAr', 'addressEn', 
                               'phone', 'email', 'storeDate', 'storeDescription', 'conditions', 
                               'treeId', 'treeIdBetween', 'webApiId'];
            
            foreach ($updatableFields as $field) {
                if (isset($request[$field])) {
                    $store->$field = $request[$field];
                }
            }
            
            $store->updatedAt = date('Y-m-d H:i:s');
            
            R::store($store);
            
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $store);
            
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    /**
     * Delete a store (soft delete)
     */
    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']);
            }

            $store = R::findOne('store', 'storeId = ?', [$request['id']]);
            
            if (!$store) {
                $this->respond(404, false, $this->trans['httpStatusCodes']['404'], null, ['id' => $this->trans['messages']['store']['notFound']]);
            }
            
            // Perform soft delete (assuming there's a 'deleted' column)
            // If you need to actually delete the record, use R::trash($store);
            // $store->deleted = 1;
            // $store->deletedAt = date('Y-m-d H:i:s');
            // R::store($store);
            
            // Or hard delete
            R::trash($store);
            
            $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");
