<?php

class InstallModel
{
    // private $db;
    public function __construct()
    {
    }
    public function addDatabse($data)
    {

        file_put_contents("../app/config/db.php", serialize($data));
        $db_name =  $data['db_name'];
        $db_username =  $data['db_username'];
        $db_password =  $data['db_password'];  

       try{
            $dbh = new PDO("mysql:dbname=$db_name;host=localhost", "$db_username", "$db_password" );
            return "connection";
        }catch(PDOException $ex){
            return "database_error";
           
        }



        // return true;
    }
    public function databaseInstall()
    {
        $array = unserialize(file_get_contents("../app/config/db.php"));
        if (file_exists("../app/config/db.php") && $array !== false) {
            $db_name = $array["db_name"];
            $db_username = $array["db_username"];
            $db_password = $array["db_password"];
        } else {
            $db_name = "";
            $db_username = "";
            $db_password = "";
        }

        
        try {
             $db = new PDO("mysql:dbname=$db_name;host=localhost", "$db_username", "$db_password" );
             $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
             $tables_arr = array('users','visitors','user_logs','countries','apis');
             foreach($tables_arr as $table){
                $droptable = 'DROP TABLE IF EXISTS '.$table;
                $resultd = $db->prepare($droptable); 
                $resultd->execute();
             }
             require_once "../app/models/sql.php";
             foreach ($tables_to_install as $table_to_install) {
                $table_installation_query = $db->exec($table_to_install);
            }
        } catch(PDOException $e) {
            return $e->getMessage();//Remove or change message in production code
        }

        return true;
    }
}
