<?php

class OrderProjects{
    public function getOrderProjectsHeaders($type = 'array'){
        $headersHelper =  new HeadersHelper();
        $data = [];

        $headers = [
            'op.id' => 'idProject',
            'op.name' => 'projectName',
            'op.isAvailable' => 'isAvailable'
        ];

        $data['headers'] = $headersHelper->getHeader($headers, $type);

        return $data;
    }

    public function getOrderProjects($available = 1){
        global $database;
        $data = [];
        $headersSql = $this->getOrderProjectsHeaders('sql')['headers'];
        $whereSql = intval($available) === 1 ? " AND op.isAvailable=1" : "";

        $sql = "SELECT
                    $headersSql
                FROM ".TABLES['order_projects']." op
                WHERE 1=1 $whereSql
                ORDER BY op.name ASC";
        $data['data'] = $database->fetchResultArray($sql);

        return $data;
    }

    private function validateProjectData($projectData){
        global $database;
        $data = [];

        $checkMessage = $database->isEmpty('projectName', $projectData->projectName);
        if($checkMessage){
            $data['messages'][] = $checkMessage;
        }

        $checkMessage = $database->invalidLength('projectName', $projectData->projectName, 100);
        if($checkMessage){
            $data['messages'][] = $checkMessage;
        }

        return $data;
    }

    public function editOrderProject($projectData){
        global $database;
        $data = [];
        $projectData = json_decode($projectData);

        if(empty($projectData)){
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'INVALID_DATA'
            ];

            return $data;
        }

        $checkMessages = $this->validateProjectData($projectData);
        if(!empty($checkMessages)){
            return $checkMessages;
        }

        $sql = "UPDATE ".TABLES['order_projects']."
                SET name='".$database->escapeValue($projectData->projectName)."',
                    isAvailable=".$database->escapeValue($projectData->isAvailable)."
                WHERE id=".$database->escapeValue($projectData->idProject);
        $query = $database->query($sql);

        if($database->affectedRows() < 1){
            $data['messages'][] = [
                'code' => 'warning',
                'message' => 'NO_CHANGES'
            ];

        }else{
            $data['messages'][] = [
                'code' => 'success',
                'message' => 'PROJECT_UPDATED'
            ];
        }

        return $data;
    }
}
