<?php
namespace FAAPI;
set_time_limit(0);
ini_set('memory_limit', '50024M');
error_reporting(E_ALL | E_STRICT);
$path_to_root = "../..";
include_once $path_to_root . "/modules/property/includes/db/property_db.php";
include_once $path_to_root . "/modules/property/propertytypes.php";

class Property {

    //Get Items
    public function get($rest) {
        $req = $rest->request();
        $page = $req->get("page");

        if ($page == null) {
            $this->users_all();
        } else {
            // If page = 1 the value will be 0, if page = 2 the value will be 1, ...
            $from = --$page * RESULTS_PER_PAGE;
            $this->propertys_all($from);
        }
    }

    public function getById($rest, $id) {
        $info = get_property($id);
        api_success_response(json_encode($info));
    }

    private function propertys_all($from = null) {
        if ($from == null)
            $from = 0;

        $sql = "SELECT * FROM " . TB_PREF . "property WHERE status=".STATUS_ACTIVE." LIMIT " . $from . ", " . RESULTS_PER_PAGE;

        $query = db_query($sql, "error");

        $info = array();

        while ($data = db_fetch_assoc($query, "error")) {
            $info[] = $data;
        }

        api_success_response(json_encode($info));
    }

    // Add Item
    public function post($rest) {
        $req = $rest->request();
        $info = $req->post();
        $new = TRUE;
        $selected_id = -1;
        if(!empty($info['id'])){
            $new = FALSE;
            $selected_id = $info['id'];
        }

        // Validate Required Fields
        if (empty($info['rent_amount']) || $info['rent_amount'] == 0) {
            api_field_error(200, 'Rent amount is required','rent_amount');
        }
        
        if (empty($info['door_no'])) {
            api_error(200, 'Door number is required','door_no');
        }
        if (empty($info['floor'])) {
            api_error(200, 'Floor is required','floor');
        }
        
        if (!is_numeric($info['bedrooms'])) {
            api_error(200, 'Number of bedrooms is required','bedrooms');
        }
        
        if (!is_numeric($info['bathrooms'])) {
            api_error(200, 'Number of bathrooms is required','bathrooms');
        }
        
        if (empty($info['latitude']) || empty($info['longitude'])) {
            api_error(200, 'Location is required','latitude');
        }
        
        if (empty($info['agentid'])) {
            api_error(200, 'Againt ID is not selected is required','agentid');
        }
        

        $id = null;
        if ($selected_id != -1) {
            update_property($selected_id,1,$info['door_no'], "", "", $info['latitude'], $info['longitude'], $info['location'], "", "", "", $info['agentid'], $info['category'], $info['type'], $info['rent_amount'], $info['floor'], $info['bedrooms'], $info['bathrooms'], $info['balcony'], 0, 0, 0, 0, $info['amenities'],$info['furnishings'],$info['size'],$info['goodwill'],$info['stock_value'],$info['period_in_business'],$info['profit']);
        } else {
            add_property(1,$info['door_no'], "", "", $info['latitude'], $info['longitude'], $info['location'], "", "", "", $info['agentid'], $info['category'], $info['type'], $info['rent_amount'], $info['floor'], $info['bedrooms'], $info['bathrooms'], $info['balcony'], 0, 0, 0, 0,$info['amenities'],$info['furnishings'],$info['size'],$info['goodwill'],$info['stock_value'],$info['period_in_business'],$info['profit']);
            $selected_id = db_insert_id();
        }

        $cust = get_property($selected_id);
        if ($cust['id']) {
            api_success_response(json_encode($cust));
        } else {
            api_error(500, 'Could Not Save to Database');
        }
    }
    
    // Add Item
    public function addImage($rest) {
        global $path_to_root;
        $req = $rest->request();
        $info = $req->post();
        //api_error(200, "wewe");
        //die(); 
        $fileExtensions = ['jpeg','jpg','png'];
        $fileName = $_FILES['files']['name'];
        $fileSize = $_FILES['files']['size'];
        $fileTmpName  = $_FILES['files']['tmp_name'];
        $fileType = $_FILES['files']['type'];
        $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);

        // Validate Required Fields
        if (empty($_GET['property_id'])) {
            api_field_error(200, 'property_id is required','property_id');
        }
        
        if (empty($_GET['image_for'])) {
            api_field_error(200, 'image_for is required','image_for');
        }
        
        if (empty($_GET['filename'])) {
            api_field_error(200, 'filename is required','filename');
        }
        
        if (! in_array($fileExtension,$fileExtensions)) {
            api_field_error(200, "This file extension is not allowed. Please upload a JPEG or PNG file","");
        }

        if ($fileSize > 5000000) {
            api_field_error(200, "This file is more than 2MB. Sorry, it has to be less than or equal to 5MB","");
        }
        
        $didUpload = move_uploaded_file($fileTmpName, $path_to_root . "/modules/property/images/property/".  basename($fileName) );
        add_property_image($_GET['property_id'], $fileName, $_GET['image_for']);
        $selected_id = db_insert_id();
        $upload_output = ob_get_contents();
        ob_end_clean();
        
        //api_success_response(Array("Upload Output"=>$upload_output));
        if ($selected_id > 0 && $didUpload) {
            api_success_response(json_encode(Array("Upload Output"=>$upload_output)));
        } else {
            api_error(200, 'Could Not Upload Image');
        }
    }
    
    public function deleteImage($rest,$property_id,$image_for) {
        $req = $rest->request();
        $info = $req->post();
        
        if (empty($property_id)) {
            api_field_error(200, 'property_id is required','property_id');
        }
        
        if (empty($image_for)) {
            api_field_error(200, 'image_for is required','image_for');
        }

        
        if(delete_property_image($property_id,$image_for)){
            api_success_response();
        } else {
            api_error(200, "Image Deletion failed");
        }
        
    }
    
    public function property_images($property_id) {
        $sql = "SELECT * FROM " . TB_PREF . "property_images WHERE status=".STATUS_ACTIVE." and property_id=".  db_escape($property_id) ;

        $query = db_query($sql, "error getting property images");
        $info['images'] = array();
        while ($data = db_fetch_assoc($query, "error")) {
            $info['images'][] = $data;
        }
        api_success_response(json_encode($info));
    }

}
