<?php

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

    $filename = 'config.php';

    if (is_writable($filename)) {

        $sample = file_get_contents($filename);
        $sample = preg_replace('/\$db_server(\s*)=(\s*)[\'"](.*)[\'"]/',"\$db_server   = '".$_POST['db_servername']."'",$sample);
        $sample = preg_replace('/\$db_username(\s*)=(\s*)[\'"](.*)[\'"]/',"\$db_username = '".$_POST['db_username']."'",$sample);
        $sample = preg_replace('/\$db_password(\s*)=(\s*)[\'"](.*)[\'"]/',"\$db_password = '".$_POST['db_password']."'",$sample);
        $sample = preg_replace('/\$db_name(\s*)=(\s*)[\'"](.*)[\'"]/',"\$db_name     = '".$_POST['db_name']."'",$sample);

        $h = fopen($filename, 'w');
        fwrite($h, $sample);
        fclose($h);

        $db_connect = @mysql_connect($_POST['db_servername'], $_POST['db_username'], $_POST['db_password']);

        if($db_connect){

            $arr_ok_msgs[1] = "<li>MySQL connected</li>";

            if(isset($_POST['create_db']) and $_POST['create_db']==1){

                if (mysql_query("CREATE DATABASE ".$_POST['db_name']." CHARACTER SET utf8 COLLATE utf8_general_ci;",$db_connect))
                    $arr_ok_msgs[2] = "<li>Database created<li>";
                else
                    $arr_error_msgs[2] = "<li class=\"not-found\">Database not created <span>(".mysql_error().")</span></li>";

            }

            if(isset($_POST['create_table']) and $_POST['create_table']==1 or isset($_POST['fill_data']) and $_POST['fill_data']==1)
                $mysql_dump = file_get_contents('assets/imdbtop250.sql');

            if(isset($_POST['create_table']) and $_POST['create_table']==1){

                mysql_select_db($_POST['db_name']);

                preg_match_all('/CREATE TABLE `(.*?)`(.*?);/s',$mysql_dump,$matches);

                if(count($matches)>0){

                    $arr_ok_msgs[3]='';
                    $arr_error_msgs[3]='';

                    $i=0;
                    foreach($matches[0] as $sql){

                        if(mysql_query($sql,$db_connect))
                            $arr_ok_msgs[3] .= "<li>Table created - ".$matches[1][$i]."</li>";
                        else
                            $arr_error_msgs[3] .= "<li class=\"not-found\">Table not created - ".$matches[1][$i]." <span>(".mysql_error().")</span></li>";

                        $i++;

                    }

                }

            }

            if(isset($_POST['fill_data']) and $_POST['fill_data']==1){

                    mysql_select_db($_POST['db_name']);

                    preg_match_all('/insert (.*?);/s',$mysql_dump,$matches);
                    if(count($matches)>0){

                        $arr_ok_msgs[4]='';
                        $arr_error_msgs[4]='';

                        foreach($matches[0] as $sql){

                            if(mysql_query($sql,$db_connect))
                                $arr_ok_msgs[4] = "<li>Data inserted</li>";
                            else
                                $arr_error_msgs[4] = "<li class=\"not-found\">Data not inserted <span>(".mysql_error().")</span></li>";

                        }

                    }

            }

        }else{
            $arr_error_msgs[1] = "<li class=\"not-found\">MySQL not connected <span>(".mysql_error().")</span></li>";
        }

    } else {
        $arr_error_msgs[0] = "<li class=\"not-found\">The file $filename can't be changed.</li>";
    }

}

function testMySQL(){
    global $db_server, $db_username, $db_password, $db_name;

    $arr_error = array();

    $db_connect = @mysql_connect($db_server, $db_username, $db_password);

    if($db_connect){

        if(mysql_select_db($db_name)){

            //mysql_set_charset('utf8');

            $result = mysql_query('SELECT count(*) FROM imdbtop250',$db_connect);

            if($result){

                if(mysql_result($result, 0)>0)
                    return true;
                else
                    return 1;

            }else{
                return 2;
            }

        }else{
            return 3;
        }

    }else{
        return 4;
    }

    return true;

}

$mysql_test = testMySQL();

if($mysql_test!==true){

    $handle = fopen("config.php", "r");
    if ($handle) {
        while (!feof($handle) and (!isset($db_server) or !isset($db_username) or !isset($db_password) or !isset($db_name))) {

            $buffer = fgets($handle, 4096);

            // find for the $db_server value
            preg_match('/\$db_server(\s*)=(\s*)[\'"](.*)[\'"]/',$buffer,$matches);
            if(count($matches)>0)
                $db_server = $matches[3];

            // find for the $db_username value
            preg_match('/\$db_username(\s*)=(\s*)[\'"](.*)[\'"]/',$buffer,$matches);
            if(count($matches)>0)
                $db_username = $matches[3];

            // find for the $db_password value
            preg_match('/\$db_password(\s*)=(\s*)[\'"](.*)[\'"]/',$buffer,$matches);
            if(count($matches)>0)
                $db_password = $matches[3];

            // find for the $db_name value
            preg_match('/\$db_name(\s*)=(\s*)[\'"](.*)[\'"]/',$buffer,$matches);
            if(count($matches)>0)
                $db_name = $matches[3];
        }
        fclose($handle);
    }


    if(isset($arr_ok_msgs) or isset($arr_error_msgs)){

?>

<div id="msg">
    <ul>
        <?php
        for($i=1; $i<=4; $i++){
            if(isset($arr_ok_msgs[$i]))
                echo $arr_ok_msgs[$i];
            if(isset($arr_error_msgs[$i]))
                echo $arr_error_msgs[$i];
        }
        ?>
    </ul>
</div>

<?php } ?>

<p>This page needs:</p>
<ul id="needs">
    <li<?php if($mysql_test>3) echo ' class="not-found"'; ?>>a MySQL connection</li>
    <li<?php if($mysql_test>2) echo ' class="not-found"'; ?>>a Database</li>
    <li<?php if($mysql_test>1) echo ' class="not-found"'; ?>>the example tables</li>
    <li<?php if($mysql_test>0) echo ' class="not-found"'; ?>>the example data</li>
</ul>

<h2>Solution</h2>
<ul id="solution">
    <li><input type="radio" name="solution" value="automatic" onclick="document.getElementById('manual-installation').style.display = 'none'; document.getElementById('automatic-installation').style.display = 'block';" />Automatic Configuration</li>
    <li><input type="radio" name="solution" value="manual" onclick="document.getElementById('automatic-installation').style.display = 'none'; document.getElementById('manual-installation').style.display = 'block';" />Manual Configuration</li>
</ul>

<form id="automatic-installation" method="post" style="display: none;">

    <div style="width: 290px; padding-top: 214px; float: right;">

        <h3>Options</h3>
        <ul>
            <li><input type="checkbox" name="create_db" value="1" checked="checked" /> create Database if not exists</li>
            <li><input type="checkbox" name="create_table" value="1" checked="checked" /> create all necessary tables if not exists</li>
            <li><input type="checkbox" name="fill_data" value="1" checked="checked" /> fill the tables with example data</li>
        </ul>

    </div>

    <h2>Automatic Configuration</h2>
    <p>Please fill your MySQL settings</p>

    <label>Server</label>
    <input type="text" name="db_servername" value="<?php echo $db_server; ?>" />

    <label>Username</label>
    <input type="text" name="db_username" value="<?php echo $db_username; ?>" />

    <label>Password</label>
    <input type="text" name="db_password" value="<?php echo $db_password; ?>" />

    <label>DB Name</label>
    <input type="text" name="db_name" value="<?php echo $db_name; ?>" />


    <input type="submit" value="UPDATE" />

</form>

<div id="manual-installation" style="display: none;">
    <h2>Manual Configuration</h2>
    <ol>
        <li>create a database in your MySQL server
            <ul>
                <li>you can use phpMyAdmin or other MySQL managers</li>
                <li>the SQL query should be something like:<br /><code style="margin-left: 20px;">CREATE DATABASE creativedreams CHARACTER SET utf8 COLLATE utf8_general_ci;</code></li>
            </ul>
        </li>
        <li>import the sql dump <code>assets/imdbtop250.sql</code>
            <ul>
                <li>you can use phpMyAdmin or other MySQL managers</li>
            </ul>
        </li>
        <li>open config.php and edit all MySQL settings</li>
    </ol>
</div>

<?php

exit;

}

?>