<?php
namespace App\Models;
use PDO;
class BaseModel{
    public $db;
    public function __construct(){
        $this->db = DatabaseConnection::getConnection();
    }
    // Thanks to Salil bhai for this;

    // Get the ID of the last row inserted
    public function insertId()
    {
        return $this->db->lastInsertId();
    }

    public function getCount($tablename){
        try {
            $sql = "SELECT * from $tablename";
            $stmt = $this->db->prepare($sql);
            if ($stmt->execute()) {
                // Return the selected data as an assoc array
                return $stmt->rowCount();
            } else {
                return false;
            }
        }
        catch (\Exception $e){
            return false;
        }
    }
    public function getOffset($pageNumber,$limit){
        return (($pageNumber - 1) * $limit);
    }
    public function select($sql, $data = array(), $fetchType = PDO::FETCH_ASSOC)
    {
        try {

            // Prepare the SQL statement
            $stmt = $this->db->prepare($sql);
            // Execute the statement
            if ($stmt->execute($data)) {
                // Return the selected data as an assoc array
                return $stmt->fetchAll($fetchType);
            } else {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    // Perform an INSERT query
    public function insert($sql, $data = array())
    {
        try {
            // Prepare the SQL statement
            $stmt = $this->db->prepare($sql);
            // Execute the statement
            if ($stmt->execute($data)) {
                // Return the number of rows affected
                return $stmt->rowCount();
            } else {
//                echo '<pre>';print_r($stmt);
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    public function update($sql, $data = array())
    {
        try {

            // Prepare the SQL statement
            $stmt = $this->db->prepare($sql);
            // Execute the statement
            if ($stmt->execute($data)) {
                return true;
            } else {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    public function delete($sql, $data = array())
    {
        try {
            // Prepare the SQL statement
            $stmt = $this->db->prepare($sql);
            // Execute the statement
            if ($stmt->execute($data)) {
                return true;
            } else {
                return false;
            }
        } catch (\Exception $e) {
            print_r($e);
            return false;
        }
    }
}