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

class pageClass extends apiHandler
{
    public function __construct() {
        parent::__construct(); 
        $this->checkERPAccess();
    }
    
    
        function index() {
        try{
            $this->getrequest->page  = isset($this->getrequest->page) ? (int) $this->getrequest->page : 1;
            $this->getrequest->limit    =isset($this->getrequest->limit) ? (int) $this->getrequest->limit : 10;
            $this->getrequest->id  = isset($this->getrequest->id) ? (int) $this->getrequest->id : 0;
            $this->getrequest->status  = isset($this->getrequest->status) ? $this->getrequest->status : 0;
            $this->getrequest->searchName = isset($this->getrequest->searchName) ? trim($this->getrequest->searchName) : '';


            $allowed = ['page', 'limit','id','status','searchName'];
            $fields = [
                'page' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'limit' => [
                    'rules' => 'required|integer|min:1|max:100',
                    'type'  => 'integer',
                ],
                'id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'status' => [
                    'rules' => 'integer',
                    'type'  => 'integer'
                ]
            ];

            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) $this->respond(401,false,$this->trans['httpStatusCodes']['401'], null,$request['validation_errors']);
            $src = $this->hosturl.'/upload/companyproduces/';
            if($this->lang == 'ar'){
                $select = 'companyname as name , description_ar as description';
            }else{
                $select = 'name_en as name , description_en as description';
            }
            if ($request['id'] > 0) {
                $response = R::getRow("SELECT id, $select, CONCAT('$src', logo) as image  FROM companyproduces WHERE id = ?",[$request['id']]);
                $this->respond(200,true,$this->trans['httpStatusCodes']['200'], null, [],$response);
            }
            
            
            $searchQuery = "";
            if ($request['searchName']) {
                $ids = R::getCol('SELECT id FROM companyproduces WHERE (companyname LIKE ? OR name_en LIKE ?)', ['%' . $request['searchName'] . '%', '%' . $request['searchName'] . '%']);
                $idList = implode(",", $ids);
                $searchQuery .= " AND id in (0$idList)";
            }


            // حساب الإزاحة (Offset)
            $offset = ($request['page'] > 0 ? $request['page'] - 1 : 0) * $request['limit'];

            // استخدام معاملات آمنة بدل دمج النصوص في SQL
            $sql = "SELECT id, $select, CONCAT('$src', logo) as image FROM companyproduces WHERE del= 0 and isActive= 0 LIMIT ? OFFSET ?";
  
            $results   = R::getAll($sql, array($request['limit'], $offset));

            // إجمالي السجلات
            $totalRecords = R::getCell('SELECT COUNT(*) FROM companyproduces WHERE del=0 and isActive=0');

            // إخراج البيانات
            if ($request['id'] > 0) {
                $response = $results;
            }else{
                $response = array(
                    "company_produces"  => $results,
                    "pagination" => [
                      "current_page"=> (int) $request['page'],
                      "total_pages"=> ceil($totalRecords / $request['limit']),           
                      "total_items"=> (int) $totalRecords,
                      "per_page"=> $request['limit']
                    ]
                );
            }
            $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 company produce
     */
    function add() {
        try {
            $allowed = ['companyname', 'name_en', 'description_ar', 'description_en', 'status', 'logo'];
            $fields = [
                'companyname' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'name_en' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'description_ar' => [
                    'rules' => 'text|max:300',
                    'type'  => 'string',
                ],
                'description_en' => [
                    'rules' => 'text|max:300',
                    'type'  => 'string',
                ],
                'status' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'logo' => [
                    'rules' => 'text|max:255',
                    '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 company name already exists
            if (helpers::valueExistsInTable('companyproduces', 'companyname = ?', [$request['companyname']])) {
                $this->respond(409, false, $this->trans['messages']['companyproduces']['nameExists'], null, ['companyname' => $this->trans['messages']['companyproduces']['nameExists']]);
            }

            $handle = new upload($_FILES['logo']);
            $request['logo'] =uploadImages2($handle, '../../upload/companyproduces');

            $rdispense = R::dispense('companyproduces');
            $rdispense->companyname = $request['companyname'];
            $rdispense->name_en = $request['name_en'];
            $rdispense->description_ar = $request['description_ar'];
            $rdispense->description_en = $request['description_en'];
            $rdispense->status = (int)$request['status'];
            $rdispense->logo = $request['logo'];
            $rdispense->addtoday = date('Y-m-d H:i:s');
            $rdispense->adduserid = 1;//$this->userInfo->userid
            $rdispense->created_at = $rdispense->updatetoday= date('Y-m-d H:i:s');
            $rdispense->del = 0;
            $rdispense->deltoday = '';
            $rdispense->deluserid = 0;
            $rdispense->updateuserid = 1;
            
            $id = R::store($rdispense);
            
            $this->respond(200,true,$this->trans['httpStatusCodes']['200'], null, [],$rdispense);
            
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

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

            $company = R::findOne('companyproduces', 'id = ? AND del = 0', [$request['id']]);
            
            if (!$company) {
                $this->respond(404, false, $this->trans['httpStatusCodes']['404'], null, ['id' => $this->trans['messages']['companyproduces']['notFound']]);
            }
            
            $response = [
                'id' => $company->id,
                'companyname' => $company->companyname,
                'name_en' => $company->name_en,
                'description_ar' => $company->description_ar,
                'description_en' => $company->description_en,
                'status' => $company->status,
                'logo' => '../upload/companyproduces/'.$company->logo,
                'created_at' => $company->created_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 company produce
     */
    function update() {
        try {
            $allowed = ['id', 'companyname', 'name_en', 'description_ar', 'description_en', 'status', 'logo'];
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'companyname' => [
                    'rules' => 'text|min:1|max:255',
                    'type'  => 'string',
                ],
                'name_en' => [
                    'rules' => 'text|min:1|max:255',
                    'type'  => 'string',
                ],
                'description_ar' => [
                    'rules' => 'text|max:300',
                    'type'  => 'string',
                ],
                'description_en' => [
                    'rules' => 'text|max:300',
                    'type'  => 'string',
                ],
                'status' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'logo' => [
                    'rules' => 'text|max:255',
                    '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 company exists
            $company = R::findOne('companyproduces', 'id = ? AND del = 0', [$request['id']]);
            if (!$company) {
                $this->respond(404, false, $this->trans['httpStatusCodes']['404'], null, ['id' => $this->trans['messages']['companyproduces']['notFound']]);
            }

            // Check if company name already exists for another record
            if (!empty($request['companyname']) && 
                helpers::valueExistsInTable('companyproduces', 'companyname = ? AND id != ?', [$request['companyname'], $request['id']])) {
                $this->respond(409, false, $this->trans['messages']['companyproduces']['nameExists'], null, ['companyname' => $this->trans['messages']['companyproduces']['nameExists']]);
            }

            $handle = new upload($_FILES['logo']);
            //$request['logo'] =uploadImages2($handle, '../../upload/companyproduces');
            $_POST['oldlogo'] = $company->logo;
            $request['logo'] = updateImagesWithoutresiz($handle, "oldlogo", '../../upload/companyproduces');
            //echo('Upload error: ' . $handle->error);
            if(strlen($request['logo']) > 10 && file_exists('../../upload/companyproduces/'.$company->logo)){
                unlink('../../upload/companyproduces/'.$company->logo);
            }
            

            // Update fields if provided
            if (!empty($request['companyname'])) $company->companyname = $request['companyname'];
            if (!empty($request['name_en'])) $company->name_en = $request['name_en'];
            if (isset($request['description_ar'])) $company->description_ar = $request['description_ar'];
            if (isset($request['description_en'])) $company->description_en = $request['description_en'];
            if (isset($request['status'])) $company->status = $request['status'];
            if (isset($request['logo'])) $company->logo = $request['logo'];
            
            $company->updatetoday = date('Y-m-d H:i:s');
            $company->updateuserid = 1;//$this->userInfo->userid;
            
            R::store($company);
            
            $response = [
                'id' => $company->id,
                'companyname' => $company->companyname,
                'name_en' => $company->name_en,
                'status' => $company->status
            ];
            
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
            
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    /**
     * Delete company produce (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']);
            }

            $company = R::findOne('companyproduces', 'id = ? AND del = 0', [$request['id']]);
            
            if (!$company) {
                $this->respond(404, false, $this->trans['httpStatusCodes']['404'], null, ['id' => $this->trans['messages']['companyproduces']['notFound']]);
            }
            
            // Soft delete
            $company->del = 1;
            $company->deltoday = date('Y-m-d H:i:s');
            $company->deluserid = 1;//$this->userInfo->userid
            
            R::store($company);
            
            $this->respond(200, true, $this->trans['httpStatusCodes']['200']);
            
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    
}

require_once("_master/fireApi.php");
