<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Installation - Buku Tamu</title>
    
    <!-- Fonts & CSS -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="css/modern.css">
    
    <style>
        .install-step {
            animation: fadeIn 0.5s ease-in-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body class="d-flex align-items-center min-vh-100">

    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-6 col-lg-5">
                <div class="glass-card text-center install-step">
                    <div class="mb-4">
                        <i class="bi bi-rocket-takeoff-fill text-gradient" style="font-size: 3rem;"></i>
                        <h2 class="mt-2 fw-bold">Installation</h2>
                        <p class="text-muted">Setup your Guestbook Application</p>
                    </div>

                    <?php
                    if (!file_exists('config.php')) {
                        if (isset($_POST['dbname']) && isset($_POST['dbuser'])) {
                            
                            $dbhost = $_POST['dbhost'];
                            $dbname = $_POST['dbname'];
                            $dbuser = $_POST['dbuser'];
                            $dbpassword = $_POST['dbpassword'];
                            
                            $content = '<?php 
$dbhost = "'.$dbhost.'"; 
$dbname = "'.$dbname.'"; 
$dbuser	  = "'.$dbuser.'";
$dbpassword = "'.$dbpassword.'";
?>';
                            
                            $handle = fopen("config.php", "w+");
                            if (fwrite($handle, $content) === FALSE) {
                                unlink("config.php");
                                echo '<div class="alert alert-danger mb-3">Failed to create config file. Check permissions.</div>';
                            } else {
                                // Try connection
                                include('config.php');
                                $con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
                                
                                if (mysqli_connect_errno()) {
                                    unlink("config.php");
                                    echo '<div class="alert alert-danger mb-3">
                                            <strong>Connection Failed!</strong><br>
                                            Check your database credentials.<br>
                                            Error: '.mysqli_connect_error().'
                                          </div>
                                          <a href="install.php" class="btn btn-primary w-100">Try Again</a>';
                                } else {
                                    // Connection Success - Create Tables
                                    // Users Table
                                    $stable = "CREATE TABLE IF NOT EXISTS users_id (id int(11) NOT NULL auto_increment, username varchar(100) NOT NULL,password varchar(225) NULL,email varchar(225) NOT NULL UNIQUE,phone varchar(225) NULL,role varchar(10) NOT NULL,register_date DATETIME DEFAULT CURRENT_TIMESTAMP,whatsapp LONGTEXT,timer varchar(50) NULL,video varchar(225) NULL,image varchar(225) NULL,cover varchar(5) NULL,logo varchar(225) NULL,bg varchar(5) NULL,font varchar(100) NULL,size_welcome varchar(10) NULL,size_tamu varchar(10) NULL,color varchar(100) NULL,text varchar(225) NULL,apikey varchar(225) NULL,apikeyone varchar(225) NULL,starsender varchar(5) NULL,apiurlonesender varchar(225) NULL,iframe varchar(225) NULL, timezone varchar(50) NULL, PRIMARY KEY(id) )";
                                    $con->query($stable);
                                    
                                    // Insert Admin
                                    $sql = "SELECT * FROM users_id";  
                                    $result = mysqli_query($con,$sql);  
                                    if(mysqli_num_rows($result) == 0) {
                                        $enter = "INSERT INTO users_id (username,password,email,phone,role,register_date,whatsapp,timer,video,image,cover,logo,bg,font,size_welcome,size_tamu,color,text,apikey,apikeyone,apiurlonesender,starsender,iframe,timezone) VALUES('admin','21232f297a57a5a743894a0e4a801fc3','emailadmin@gmail.com','000000','admin',NOW(),'Terima kasih yang sebesar-besarnya untuk [nama] telah berhadir di hari berbahagia kami pada hari [tgl] jam [jam]\nTerima kasih atas Doa restu terbaik yang anda berikan pada kami dan keluarga.','5000','https://www.youtube.com/watch?v=XWKfMPkXyG0','','1','images/icon.png','1','Poppins','18','39','#5c00cc','Selamat Datang','','','','','https://bukutamu.net','Asia/Jakarta')";
                                        $con->query($enter);
                                    }

                                    // Other Tables
                                    $con->query("CREATE TABLE IF NOT EXISTS comment_id (no_id bigint(11) UNSIGNED NOT NULL auto_increment, nama varchar(225)NOT NULL,tgl varchar(25) DEFAULT NULL,jam varchar(25) DEFAULT NULL,tamu varchar(25) NULL,whatsapp varchar(100) NULL, PRIMARY KEY(no_id) )");
                                    
                                    $con->query("CREATE TABLE IF NOT EXISTS event_id (id bigint(11) UNSIGNED NOT NULL auto_increment, acara varchar(225) NULL,jam varchar(225) NULL,tanggal varchar(225) NULL, PRIMARY KEY(id) )");
                                    $res_event = mysqli_query($con, "SELECT * FROM event_id");
                                    if(mysqli_num_rows($res_event) == 0) {
                                        $con->query("INSERT INTO event_id (acara,jam,tanggal) VALUES('Buku Tamu','10:20 WIB','20 Mei 2023')");
                                    }

                                    $con->query("CREATE TABLE IF NOT EXISTS smtp (id bigint(11) UNSIGNED NOT NULL auto_increment, host varchar(225) DEFAULT NULL,port varchar(225) DEFAULT NULL,encryption varchar(225) DEFAULT NULL,username varchar(225) DEFAULT NULL,password varchar(225) DEFAULT NULL,emailweb varchar(225) DEFAULT NULL,nameweb varchar(225) DEFAULT NULL, PRIMARY KEY(id) )");
                                    $res_smtp = mysqli_query($con, "SELECT * FROM smtp");
                                    if(mysqli_num_rows($res_smtp) == 0) {
                                        $con->query("INSERT INTO smtp (host,port,encryption,username,password,emailweb,nameweb) VALUES('','','','','','','')");
                                    }

                                    $con->query("CREATE TABLE IF NOT EXISTS categories (id bigint(11) UNSIGNED NOT NULL auto_increment, category_name varchar(225)NOT NULL, PRIMARY KEY(id) )");

                                    echo '<div class="alert alert-success mt-3">
                                            <h4 class="alert-heading fw-bold">Success!</h4>
                                            <p>Installation completed successfully.</p>
                                            <p class="mb-0">Username: <b>admin</b><br>Password: <b>admin</b></p>
                                          </div>
                                          <a href="login" class="btn btn-primary w-100 mt-2">Go to Login</a>';
                                }
                            }
                        } else {
                            // Display Form
                        ?>
                            <form action="" method="post">
                                <div class="form-floating mb-3 text-start">
                                    <input type="text" class="form-control" name="dbhost" id="dbhost" placeholder="localhost" value="localhost" required>
                                    <label for="dbhost">Database Host</label>
                                </div>
                                <div class="form-floating mb-3 text-start">
                                    <input type="text" class="form-control" name="dbname" id="dbname" placeholder="Database Name" required>
                                    <label for="dbname">Database Name</label>
                                </div>
                                <div class="form-floating mb-3 text-start">
                                    <input type="text" class="form-control" name="dbuser" id="dbuser" placeholder="Database User" required>
                                    <label for="dbuser">Database User</label>
                                </div>
                                <div class="form-floating mb-4 text-start">
                                    <input type="password" class="form-control" name="dbpassword" id="dbpassword" placeholder="Database Password">
                                    <label for="dbpassword">Database Password</label>
                                </div>
                                <button type="submit" class="btn btn-primary w-100 py-3">Next Step <i class="bi bi-arrow-right"></i></button>
                            </form>
                        <?php
                        }
                    } else {
                        // Already Installed
                        echo '<div class="alert alert-info">
                                <i class="bi bi-info-circle-fill"></i> Application is already installed!
                              </div>
                              <a href="login" class="btn btn-primary w-100">Go to Login</a>';
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>

</body>
</html>