<?php

//Hak Cipta dilindungi Undang-undang. Hak Cipta : Khamdi Rahmani, Reg. Kemenkum HAM No : 000121327. Dilarang merubah isi File tanpa ijin tertulis dari pemegang Hak Cipta. 

class installDB extends database
{

    public function install()
    {

        $db = database::getInstance();
        $_host = $this->_host;
        $_dbname = $this->_dbname;
        $_username = $this->_username;
        $_password = $this->_password;

        $pdo = new PDO('mysql:host=' . $_host . ';dbname=' . $_dbname, $_username, $_password, array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ));

        if (isset($_POST['installDB'])) {

            $nama_file = $_FILES['datafile']['name'];
            // $ukuran = $_FILES['datafile']['size'];

            //periksa jika data yang dimasukan belum lengkap
            if ($nama_file == "") {
                echo "File belum ditentukan";
                echo "<script>confirm('File Database tidak ditemukan !')</script>";
            } else {
                //definisikan variabel file dan alamat file
                $uploaddir = 'asset/backup/restore/';

                $alamatfile = $uploaddir . $nama_file;

                if (move_uploaded_file($_FILES['datafile']['tmp_name'], $alamatfile)) {
                    /**
                     * Import SQL File
                     *
                     * @param $pdo
                     * @param $sqlFile
                     * @param null $tablePrefix
                     * @param null $InFilePath
                     * @return bool
                     */
                    $filePath = 'asset/backup/restore/' . $nama_file;
                    //$filePath = '../backup/' . $nama_file;
                    // Import the SQL file
                    $res = $this->restore_exec($pdo, $filePath);
                    if ($res === false) {
                        die('ERROR');
                    }
                } else {
                    //jika gagal
                    echo "Proses upload gagal, kode error = " . $_FILES['location']['error'];
                    //    echo "";
                }
                // $direct = new toast();
                //echo $direct->redirect('toast', 'restore', 'utility/backup/index');
                //header("location:./");
                echo "<script>  
                        document.location.href='./lisensi/';
                     </script>";
            }
        } else {
            unset($_POST['restore']);
        };
    }



    private function restore_exec($pdo, $sqlFile, $tablePrefix = null, $InFilePath = null)
    {
        try {

            // Enable LOAD LOCAL INFILE
            $pdo->setAttribute(\PDO::MYSQL_ATTR_LOCAL_INFILE, true);

            $errorDetect = false;

            // Temporary variable, used to store current query
            $tmpLine = '';

            // Read in entire file
            $lines = file($sqlFile);

            // Loop through each line
            foreach ($lines as $line) {
                // Skip it if it's a comment
                if (substr($line, 0, 2) == '--' || trim($line) == '') {
                    continue;
                }

                // Read & replace prefix
                $line = str_replace(['<<prefix>>', '<<InFilePath>>'], [$tablePrefix, $InFilePath], $line);

                // Add this line to the current segment
                $tmpLine .= $line;

                // If it has a semicolon at the end, it's the end of the query
                if (substr(trim($line), -1, 1) == ';') {
                    try {
                        // Perform the Query
                        $pdo->exec($tmpLine);
                    } catch (\PDOException $e) {
                        echo "<br><pre>Error performing Query: '<strong>" . $tmpLine . "</strong>': " . $e->getMessage() . "</pre>\n";
                        $errorDetect = true;
                    }

                    // Reset temp variable to empty
                    $tmpLine = '';
                }
            }

            // Check if error is detected
            if ($errorDetect) {
                return false;
            }
        } catch (\Exception $e) {
            echo "<br><pre>Exception => " . $e->getMessage() . "</pre>\n";
            return false;
        }

        return true;
    }
}
