<?php

/**
 * Created by Amit Prashant Agrahari
 * Date: 11/26/2019
 * Time: 2:12 PM
 */

class SphinxApi {

	const HOST = '127.0.0.1';
	const PORT = '9306';
	const USER_NAME = 'sphinx';

	public $conn;

	public function __construct($ip='', $port= '') {

		$this->_getConnect($ip, $port);

	}

 	public function _getConnect($ip, $port) { 		
		
		try {
		    $this->conn = new PDO("mysql:host=".$ip.":".$port.";");
		    if( empty($ip) || empty($port) ) { 
		       $this->conn = new PDO("mysql:host=192.168.30.31:9306;");
		    }
		    // set the PDO error mode to exception
		    $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		    
		} catch(PDOException $e) {
		    echo "Connection failed: " . $e->getMessage();
		    $this->conn = false;
		}

	}

	public function _insert($indexName, $cols, $quesMark, $data) {
		if ( $this->conn === false ) {
			return false;
		}

		try {

			$statement = $this->conn->prepare("REPLACE INTO `".$indexName."` (".$cols.") VALUES (".$quesMark.")");
			$x = $statement->execute($data);
			#if( !$x ) { print_r($this->conn->errorInfo()); }
			return $x;

		} catch (Exception $e) {
			echo "Insert failed: " . $e->getMessage();
		    return false;
		}

	}

	public function _fetch($query)	{

		try {
			
			$stmt = $this->conn->query($query, PDO::FETCH_ASSOC);
			$searchData = array();
			while ($row = $stmt->fetch()) {
			    $searchData[] = $row;
			}
			return $searchData;

		} catch (Exception $e) {
			echo "Fetch failed: " . $e->getMessage();
		    return false;
		}

	}

	public function _delete($idArr) {
		if( empty($idArr) ) {
			return false;
		}

		try {

			foreach ( $idArr as $id ) {
				$id = (int) $id;
				$statement = $this->conn->prepare("DELETE FROM steelstraw WHERE id = :id ");
				$statement->bindParam(':id', $id);
				$statement->execute();
				//var_dump($statement->rowCount());die;
			}
			return true;

		} catch (Exception $e) {
			echo "Delete failed: " . $e->getMessage();
		    return false;
		}

	}
	
	public function _execute($query) {
                if( empty($query) ) {
                        return false;
                }

                try {
			$count = $this->conn->exec($query);
			return $count;	
                } catch (Exception $e) {
                        echo "Delete failed: " . $e->getMessage();
                    return false;
                }

        }

}

?>

