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

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

    /**
     * List all branches with pagination
     */


    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 : 1000;
            $this->getrequest->id  = isset($this->getrequest->id) ? (int) $this->getrequest->id : 0;
            $this->getrequest->searchName = isset($this->getrequest->searchName) ? trim($this->getrequest->searchName) : '';
            $allowed = ['searchName','page', 'limit','id'];
            $fields = [
                'searchName' => [
                    'rules' => 'text|min:1|max:100',
                    'type'  => 'string',
                ],
                'page' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'limit' => [
                    'rules' => 'required|integer|min:1|max:100',
                    'type'  => 'integer',
                ],
                'id' => [
                    '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.'/views/default/images/branch_image/';
            if($this->lang == 'ar'){
                $select = 'branchName as name, branchAddress as address';
            }else{
                $select = 'nameEn as name, addressEn as address';
            }


            if ($request['id'] > 0) {
                $response = R::getRow("SELECT branchId as id, $select, CONCAT('$src', logo) as image, phone, mobile, branchNo as branch_no, email, branchDate as branch_date  FROM `branch` WHERE branchId = ?",[$request['id']]);
                $this->respond(200,true,$this->trans['httpStatusCodes']['200'], null, [],$response);
            }

            $searchQuery = "";
            if ($request['searchName']) {
                $ids = R::getCol('SELECT branchId FROM branch WHERE status = 0 AND (branchName LIKE ? OR nameEn LIKE ?)', ['%' . $request['searchName'] . '%', '%' . $request['searchName'] . '%']);
                $idList = implode(",", $ids);
                $searchQuery .= " AND branchId in (0$idList)";
            }



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

            // استخدام معاملات آمنة بدل دمج النصوص في SQL
            $sql = "SELECT branchId as id, $select, CONCAT('$src', logo) as image, phone, mobile, branchNo as branch_no, email, branchDate as branch_date FROM `branch` WHERE status = 0  $searchQuery LIMIT ? OFFSET ?";
         
  
            $results   = R::getAll($sql, array($request['limit'], $offset));

            // إجمالي السجلات
            $totalRecords = R::getCell("SELECT COUNT(*) FROM `branch` WHERE status = 0 $searchQuery ");


            // إخراج البيانات
            if ($request['id'] > 0) {
                $response = $results;
            }else{
                $response = array(
                    "branches"  => $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 branch
     */
    function add() {

        try {
            $allowed = ['name', 'name_en', 'address', 'address_en', 'branch_date', 
                       'phone', 'mobile', 'email', 'branch_no', 'comment', 'logo', 'branch_tax_no', 'status'];
            
            $fields = [
                'name' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'name_en' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'address' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'address_en' => [
                    'rules' => 'required|text',
                    'type'  => 'string',
                ],
                'branch_date' => [
                    'rules' => 'required|date',
                    'type'  => 'string',
                ],
                'phone' => [
                    'rules' => 'required|text|max:50',
                    'type'  => 'string',
                ],
                'mobile' => [
                    'rules' => 'required|text|max:50',
                    'type'  => 'string',
                ],
                'email' => [
                    'rules' => 'required|text|max:100',//email
                    'type'  => 'string',
                ],
                'branch_no' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'comment' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'logo' => [
                    'rules' => 'text|max:255',
                    'type'  => 'string',
                ],
                'branch_tax_no' => [
                    'rules' => 'text|max:255',
                    'type'  => 'string',
                ],
                'status' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 1
                ]
            ];

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

            if (helpers::valueExistsInTable('branch', 'branchName = ? or nameEn = ?', [$request['name'], $request['name_en']])) {
               $this->respond(409,false,$this->trans['messages']['branches']['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            }
            $image_name = $request['logo'];
            $src = $this->hosturl.'/views/default/images/branch_image/';
            if (strpos($image_name, 'dump') !== false) {
                //mine
                $url_array = explode('/', $image_name);
                $count_url_array = count($url_array);
                if (file_exists('../../upload/dump/' . $url_array[$count_url_array - 1])) {
                    rename("../../upload/dump/" . $url_array[$count_url_array - 1], "../../views/default/images/branch_image/" . $url_array[$count_url_array - 1]);
                }
                $image_name = $url_array[$count_url_array - 1];
            }

            $branch = R::dispense('branch');
            $branch->branchName = $request['name'];
            $branch->nameEn = $request['name_en'];
            $branch->branchAddress = $request['address'];
            $branch->addressEn = $request['address_en'];
            $branch->branchDate = $request['branch_date'];
            $branch->phone = $request['phone'];
            $branch->mobile = $request['mobile'];
            $branch->email = $request['email'];
            $branch->branchNo = $request['branch_no'];
            $branch->message = $request['comment'];
            $branch->logo = $image_name;
            $branch->branchTaxNo = $request['branch_tax_no'];
            $branch->status = (int)$request['status'];
            $branch->createdAt = date('Y-m-d H:i:s');
            $branch->updatedAt = date('Y-m-d H:i:s');
            $id = R::store($branch);
            $branch->image = $src . $image_name;
            
            $fresponse = helpers::beanToStdClass($branch,['phone','mobile','email','image'], [],['branchId' => 'id','branchName' => 'name','nameEn' => 'name_en','branchAddress' => 'address',
                'addressEn' => 'address_en','branchDate' => 'branch_date','branchNo' => 'branch_no']);
                
            $this->respond(200, true, $this->trans['messages']['branches']['200'], null, [],$fresponse);
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    function edit() {
        try{

            $allowed = ['id'];
             $fields = [
                'id' => [
                    'rules' => 'required|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']);
            
            if (helpers::valueNotExistsInTable('branch', 'branchId = ?',[$request['id']])) {
              $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['id' => $this->trans['messages']['branches']['branchIdNotExists']]);
            }
            
            $src = $this->hosturl.'/views/default/images/branch_image/';
            $select = 'branchName as name, branchAddress as address, nameEn as name_en, addressEn as address_en';

            $response = R::getRow("SELECT branchId as id, $select, CONCAT('$src', logo) as image, phone, mobile, branchNo as branch_no, email, branchDate as branch_date  FROM `branch` WHERE branchId = ?",[$request['id']]);
            $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 branch
     */
    function update() {
        try {
            
            $allowed = ['id','name', 'name_en', 'address', 'address_en', 'branch_date', 
                       'phone', 'mobile', 'email', 'branch_no', 'comment', 'logo', 'branch_tax_no', 'status'];

            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'name' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'name_en' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'address' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'address_en' => [
                    'rules' => 'required|text',
                    'type'  => 'string',
                ],
                'branch_date' => [
                    'rules' => 'required|date',
                    'type'  => 'string',
                ],
                'phone' => [
                    'rules' => 'required|text|max:50',
                    'type'  => 'string',
                ],
                'mobile' => [
                    'rules' => 'required|text|max:50',
                    'type'  => 'string',
                ],
                'email' => [
                    'rules' => 'required|text|max:100',//email
                    'type'  => 'string',
                ],
                'branch_no' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'comment' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'logo' => [
                    'rules' => 'text|max:255',
                    'type'  => 'string',
                ],
                'branch_tax_no' => [
                    'rules' => 'text|max:255',
                    'type'  => 'string',
                ],
                'status' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 1
                ]
            ];
            
            
        

            $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 branch exists
            $branch = R::findOne('branch', 'branchId = ?', [$request['id']]);
            if (!$branch) {
                $this->respond(404, false, 'Branch not found', null, ['id' => 'Branch not found']);
            }

            // Check if branch name already exists for another branch
            $existing = R::findOne('branch', 'branchName = ? AND branchId != ?', [$request['branchName'], $request['id']]);
            if ($existing) {
                $this->respond(409, false, 'Branch name already exists', null, ['branchName' => 'Branch name already exists']);
            }

            $image_name = $request['logo'];
            $src = $this->hosturl.'/views/default/images/branch_image/';
            if (strpos($image_name, 'dump') !== false) {
                //mine
                $url_array = explode('/', $image_name);
                $count_url_array = count($url_array);
                if (file_exists('../../upload/dump/' . $url_array[$count_url_array - 1])) {
                    rename("../../upload/dump/" . $url_array[$count_url_array - 1], "../../views/default/images/branch_image/" . $url_array[$count_url_array - 1]);
                }
                $image_name = $url_array[$count_url_array - 1];
            }

            
            
            $rupdate = R::load('branch',$request['id']);
            $rupdate->branchName = $request['name'];
            $rupdate->nameEn = $request['name_en'];
            $rupdate->branchAddress = $request['address'];
            $rupdate->addressEn = $request['address_en'];
            $rupdate->branchDate = $request['branch_date'];
            $rupdate->phone = $request['phone'];
            $rupdate->mobile = $request['mobile'];
            $rupdate->email = $request['email'];
            $rupdate->branchNo = $request['branch_no'];
            $rupdate->message = $request['comment'];
            $rupdate->logo = empty($image_name) ? $rupdate->logo : $image_name;
            $rupdate->branchTaxNo = $request['branch_tax_no'];
            $rupdate->status = (int)$request['status'];
            $rupdate->updatedAt = date('Y-m-d H:i:s');
            R::store($rupdate);
            $rupdate->image = $src . $rupdate->logo;
            $fresponse = helpers::beanToStdClass($rupdate,['phone','mobile','email','image'], [],['branchId' => 'id','branchName' => 'name','nameEn' => 'name_en','branchAddress' => 'address',
                'addressEn' => 'address_en','branchDate' => 'branch_date','branchNo' => 'branch_no']);
            $this->respond(200,true,$this->trans['messages']['branches']['update'], null, [],$fresponse);
            
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    /**
     * Delete a branch
     */
    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']);

            if (helpers::valueNotExistsInTable('branch', 'branchId = ?', [$request['id']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['id' => $this->trans['messages']['branches']['branchIdNotExists']]);
            }

            $rupdate = R::load('branch', $request['id']);
            $id = R::trash($rupdate);
            $this->respond(200,true,$this->trans['messages']['branches']['softDelete'], null, [],[]);
        }catch (Exception $exception){
            $this->respond(500,false,$this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }
}

require_once("_master/fireApi.php");