<?php
// Redirect to original installer
header('Location: install.php');
exit;
?>
<style>
.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid blue;
  border-bottom: 16px solid blue;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
<link rel="shortcut icon" href="../../theme/images/favicon.ico">
<?php
//error_reporting(0);

// Define lock file path
define('INSTALLER_LOCK_FILE', __DIR__ . '/../../install.lock');

// Check if installation is locked
if (file_exists(INSTALLER_LOCK_FILE)) {
    die('<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Installation Locked - NCS Billing System</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .lock-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            max-width: 600px;
            width: 100%;
            padding: 40px;
            text-align: center;
        }
        .lock-icon {
            font-size: 60px;
            color: #e74c3c;
            margin-bottom: 20px;
        }
        .warning-box {
            background: #fff3cd;
            border: 2px solid #ffc107;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
            text-align: left;
        }
        .info-box {
            background: #d1ecf1;
            border: 2px solid #0c5460;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
        }
        .file-path {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            font-family: monospace;
            font-size: 0.9rem;
            color: #2c3e50;
            margin: 10px 0;
            word-break: break-all;
        }
    </style>
</head>
<body>
    <div class="lock-container">
        <div class="lock-icon">
            <i class="fa fa-lock"></i>
        </div>
        <h1>Installation Already Completed</h1>
        <p>Your NCS Billing System has already been installed.</p>
        
        <div class="warning-box">
            <h4><i class="fa fa-exclamation-triangle"></i> Important</h4>
            <ul>
                <li>Do not delete the lock file unless you intend to re-install</li>
                <li>Re-installation will <strong>overwrite your database</strong></li>
                <li>Always backup before re-installing</li>
            </ul>
        </div>

        <div class="info-box">
            <strong>To re-install:</strong> Delete the lock file at:<br>
            <div class="file-path">' . realpath(INSTALLER_LOCK_FILE) . '</div>
        </div>
        
        <p><strong>Support:</strong> <a href="mailto:admin@nanzige.com">admin@nanzige.com</a></p>
    </div>
</body>
</html>');
}

include '../../application/helpers/custom_helper.php';
include '../../application/helpers/appinfo_helper.php';


$db_config_path = '../../application/config/database.php';
$codeigniter_index_page = '../../index.php';



if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST) {
    
	require_once('taskCoreClass.php');
	require_once('includes/databaseLibrary.php');

	$core = new Core();
	$database = new Database();

	if($core->checkEmpty($_POST) == true)
	{

       // $database->create_database($_POST);
        if($database->check_database_exist_or_not($_POST) == false)
        {
            $message = $core->show_message('error',"Failed ! Database `".$_POST['database']."` Does Not Exist! Please Create Manually in Your server!");
        } 

		else if($database->create_database($_POST) == false)
		{
			$message = $core->show_message('error',"The database could not be created, make sure your the host, username, password, database name is correct.");
		} 

		else if ($database->create_tables($_POST) == false)
		{
			$message = $core->show_message('error',"Invalid Purchase Code!!");
		} 
        
		else if ($core->checkFile() == false)
		{
			$message = $core->show_message('error',"File application/config/database.php is Empty");
		}
        
		else if ($core->write_config($_POST) == false)
		{
			$message = $core->show_message('error',"The database configuration file could not be written, please chmod application/config/database.php file to 777");
		}

		if(!isset($message)) {
            // Create lock file to prevent re-installation
            $lockContent = "Installation completed on: " . date('Y-m-d H:i:s') . "\n";
            $lockContent .= "Database: " . $_POST['database'] . "\n";
            $lockContent .= "Site URL: " . $_POST['url'] . "\n";
            $lockContent .= "\n";
            $lockContent .= "WARNING: Do not delete this file unless you want to re-install the application.\n";
            $lockContent .= "Re-installation will overwrite your existing database and cause data loss!\n";
            
            if (@file_put_contents(INSTALLER_LOCK_FILE, $lockContent) === false) {
                // Log error but don't stop installation
                error_log('Failed to create installer lock file at: ' . INSTALLER_LOCK_FILE);
            }
            
            $urlWb = $core->getAllData($_POST['url']);
            ?>
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Installation Complete - NCS Billing System</title>
                <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
                <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
                <style>
                    body { 
                        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                        min-height: 100vh; 
                        display: flex; 
                        align-items: center; 
                        justify-content: center;
                    }
                    .success-card { 
                        background: white; 
                        border-radius: 20px; 
                        box-shadow: 0 20px 40px rgba(0,0,0,0.1); 
                        padding: 40px; 
                        text-align: center;
                        max-width: 500px;
                        width: 100%;
                    }
                    .success-icon { 
                        font-size: 80px; 
                        color: #28a745; 
                        margin-bottom: 20px; 
                    }
                    .btn-success-custom { 
                        background: linear-gradient(135deg, #28a745 0%, #20c997 100%); 
                        border: none; 
                        border-radius: 25px; 
                        padding: 12px 30px; 
                        font-size: 16px;
                        color: white;
                        box-shadow: 0 5px 15px rgba(40, 167, 69, 0.3);
                        transition: all 0.3s ease;
                        margin-top: 20px;
                    }
                    .btn-success-custom:hover { 
                        transform: translateY(-2px); 
                        box-shadow: 0 8px 25px rgba(40, 167, 69, 0.4);
                        color: white;
                        text-decoration: none;
                    }
                    .login-info {
                        background: #f8f9fa;
                        border-radius: 10px;
                        padding: 20px;
                        margin: 20px 0;
                        border-left: 4px solid #28a745;
                    }
                </style>
            </head>
            <body>
                <div class="success-card">
                    <div class="success-icon">
                        <i class="fa fa-check-circle"></i>
                    </div>
                    <h2 style="color: #28a745; margin-bottom: 20px;">Installation Complete!</h2>
                    <p style="color: #666; font-size: 16px; margin-bottom: 30px;">
                        NCS Billing System has been successfully installed and configured.
                    </p>
                    
                    <div class="login-info">
                        <h5 style="color: #333; margin-bottom: 15px; text-align: left;">
                            <i class="fa fa-user"></i> Default Login Credentials
                        </h5>
                        <div style="text-align: left;">
                            <p style="margin-bottom: 8px; font-size: 14px;">
                                <strong style="color: #333;">Username:</strong> 
                                <span style="background: #e9ecef; padding: 2px 8px; border-radius: 4px; font-family: monospace;">admin@example.com</span>
                            </p>
                            <p style="margin-bottom: 0; font-size: 14px;">
                                <strong style="color: #333;">Password:</strong> 
                                <span style="background: #e9ecef; padding: 2px 8px; border-radius: 4px; font-family: monospace;">123456</span>
                            </p>
                        </div>
                    </div>
                    
                    <div style="background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 10px; padding: 15px; margin: 20px 0;">
                        <h6 style="color: #856404; margin-bottom: 10px; text-align: left;">
                            <i class="fa fa-info-circle"></i> Important Notes:
                        </h6>
                        <ul style="color: #856404; font-size: 13px; margin-bottom: 0; text-align: left; padding-left: 20px;">
                            <li>Please change the default password after your first login</li>
                            <li>Keep your login credentials secure</li>
                            <li>For support, contact: admin@nanzige.com</li>
                        </ul>
                    </div>
                    
                    <div class="text-center" style="margin-top: 30px;">
                        <a href="<?= $urlWb; ?>/login" class="btn btn-success-custom" style="font-size: 18px; padding: 15px 40px;" onclick="showLoading()">
                            <i class="fa fa-sign-in"></i> Go to Login Page
                        </a>
                        <p style="color: #666; font-size: 12px; margin-top: 15px;">
                            Click the button above to access your NCS Billing System
                        </p>
                        <p style="color: #999; font-size: 11px; margin-top: 10px;">
                            URL: <?= $urlWb; ?>/login
                        </p>
                    </div>
                    
                    <script>
                    function showInstallationProgress() {
                        // Show progress screen immediately
                        document.body.innerHTML = '<div style="text-align: center; padding: 50px; font-family: Arial, sans-serif; background: #f5f5f5; min-height: 100vh; display: flex; align-items: center; justify-content: center;"><div style="background: white; padding: 40px; border-radius: 10px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); max-width: 500px; width: 100%;"><h3 style="color: #2c3e50; margin-bottom: 20px;">Installing NCS Billing System</h3><div style="border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 50px; height: 50px; animation: spin 2s linear infinite; margin: 20px auto;"></div><div id="progress-text" style="margin: 20px 0; font-size: 16px; color: #555;">Initializing installation...</div><div style="background: #ecf0f1; border-radius: 10px; height: 20px; margin: 20px 0; overflow: hidden;"><div id="progress-bar" style="background: linear-gradient(90deg, #3498db, #2ecc71); height: 100%; width: 0%; transition: width 0.5s ease; border-radius: 10px;"></div></div><p style="color: #7f8c8d; font-size: 14px; margin: 0;">Please do not close this window during installation.</p></div></div><style>@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }</style>';
                        
                        // Start progress simulation
                        simulateInstallationProgress();
                        
                        // After showing progress, submit the form
                        setTimeout(function() {
                            // Create a hidden form and submit it
                            const form = document.createElement('form');
                            form.method = 'POST';
                            form.action = '<?php echo $_SERVER['PHP_SELF']; ?>';
                            
                            // Get form data from the original form
                            const originalForm = document.getElementById('install_form');
                            const formData = new FormData(originalForm);
                            
                            // Add form fields
                            for (let [key, value] of formData.entries()) {
                                const input = document.createElement('input');
                                input.type = 'hidden';
                                input.name = key;
                                input.value = value;
                                form.appendChild(input);
                            }
                            
                            // Submit the form
                            document.body.appendChild(form);
                            form.submit();
                        }, 2000);
                    }
                    
                    function simulateInstallationProgress() {
                        const steps = [
                            { text: "Validating database connection...", progress: 10 },
                            { text: "Creating database tables...", progress: 30 },
                            { text: "Inserting initial data...", progress: 50 },
                            { text: "Setting up user accounts...", progress: 70 },
                            { text: "Configuring system settings...", progress: 85 },
                            { text: "Finalizing installation...", progress: 95 },
                            { text: "Installation complete!", progress: 100 }
                        ];
                        
                        let currentStep = 0;
                        
                        function updateProgress() {
                            if (currentStep < steps.length) {
                                const progressElement = document.getElementById('progress-text');
                                const barElement = document.getElementById('progress-bar');
                                
                                if (progressElement && barElement) {
                                    progressElement.textContent = steps[currentStep].text;
                                    barElement.style.width = steps[currentStep].progress + '%';
                                }
                                currentStep++;
                                setTimeout(updateProgress, 1000); // 1 second delay between steps
                            }
                        }
                        
                        // Start progress after a short delay
                        setTimeout(updateProgress, 500);
                    }
                    
                    function showLoading() {
                        document.body.innerHTML = '<div style="text-align: center; padding: 50px; font-family: Arial, sans-serif;"><h3>Preparing System...</h3><div style="border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 40px; height: 40px; animation: spin 2s linear infinite; margin: 20px auto;"></div><p>Please wait while we prepare your system.</p><p><small>This may take a few moments...</small></p></div><style>@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }</style>';
                        
                        // Add delay before redirect
                        setTimeout(function() {
                            window.location.href = '<?= $urlWb; ?>/login';
                        }, 3000);
                    }
                    </script>
                </div>
            </body>
            </html>
            <?php 
            exit();
		}
	}
	else {
		$message = $core->show_message('error','The host, username, password, database name, and URL are required.');
	}
}
?>
<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>NCS Billing System - Installation</title>
		<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cosmo/bootstrap.min.css" rel="stylesheet">
	</head>
	<body>
    <div class="container">
        <div class="col-md-8 col-md-offset-2">
            <h1 class="text-center"><i class="fa fa-cogs"></i> NCS Billing System Installer</h1>
            <p class="text-muted text-center">Application Version <?=app_version();?></p>
            <hr>
            <?php 
            if(is_writable($db_config_path) && is_writable($codeigniter_index_page))
            {
            ?>
                <?php if(isset($message)) {
                echo '
                <div class="alert alert-warning alert-dismissible" role="alert">
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                ' . $message . '
                </div>';
                }?>
                
                <div class="alert alert-success">
                           If you facing any issue in Installation, Please Contact Support. <br>
                    Email: admin@nanzige.com
                        </p>
                    </div>

                <form id="install_form" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="showInstallationProgress(); return false;">
                    <?php 
                        $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                        $url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                        
                        $url = str_replace('setup/install/', '', $url);
                        $url = str_replace('index.php', '', $url);
                    ?>
                    <input type="hidden" id="url" class="form-control" name="url" placeholder="http://example.com/" value="<?=$url;?>" />
                    
                    <div class="row">
                        <!-- Left Column: Database Configuration -->
                        <div class="col-md-12">
                            <div class="panel panel-primary" style="margin-bottom: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                                <div class="panel-heading" style="padding: 15px 20px;">
                                    <h4 class="panel-title" style="margin: 0; font-size: 16px;">
                                        <i class="fa fa-database"></i> Database Configuration
                                    </h4>
                                </div>
                                <div class="panel-body" style="padding: 25px;">
                                    <p class="help-block" style="margin-bottom: 20px;">Please provide your database connection details to install the NCS Billing System.</p>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group" style="margin-bottom: 20px;">
                                                <label for="hostname" style="font-weight: 600; margin-bottom: 8px;">Database Host<span class='text-danger'>*</span></label>
                                                <input type="text" id="hostname" placeholder="localhost" class="form-control" name="hostname" value='localhost' style="padding: 12px; border-radius: 6px;"/>
                                                <p class="help-block text-danger" style="display: none;" id="hostname_msg"></p> 
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group" style="margin-bottom: 20px;">
                                                <label for="username" style="font-weight: 600; margin-bottom: 8px;">Database Username<span class='text-danger'>*</span></label>
                                                <input type="text" id="username" placeholder="Database Username" class="form-control" name="username" value='' style="padding: 12px; border-radius: 6px;"/>
                                                <p class="help-block text-danger" style="display: none;" id="username_msg"></p> 
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group" style="margin-bottom: 20px;">
                                                <label for="password" style="font-weight: 600; margin-bottom: 8px;">Database Password</label>
                                                <input type="password" id="password" placeholder="Database Password" class="form-control" name="password" value='' style="padding: 12px; border-radius: 6px;"/>
                                                <p class="help-block text-danger" style="display: none;" id="password_msg"></p> 
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group" style="margin-bottom: 20px;">
                                                <label for="database" style="font-weight: 600; margin-bottom: 8px;">Database Name<span class='text-danger'>*</span></label>
                                                <input type="text" id="database" placeholder="Database Name" class="form-control" name="database" value='' style="padding: 12px; border-radius: 6px;"/>
                                                <p class="help-block text-danger" style="display: none;" id="database_msg" ></p> 
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group" style="margin-bottom: 20px;">
                                        <label for="url" style="font-weight: 600; margin-bottom: 8px;">Site URL<span class='text-danger'>*</span></label>
                                        <input type="text" id="url" placeholder="http://localhost/ncsbillingbook" class="form-control" name="url" value='' style="padding: 12px; border-radius: 6px;"/>
                                        <p class="help-block" style="margin-top: 8px;">Enter the URL where you want to install the application (e.g., http://localhost/ncsbillingbook)</p>
                                        <p class="help-block text-danger" style="display: none;" id="url_msg"></p> 
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Install Button - Full Width -->
                    <div class="row" style="margin-top: 30px;">
                        <div class="col-md-12">
                            <div class="form-group">
                                <button type="button" class="btn btn-success btn-lg btn-block" id="send" style="padding: 15px; font-size: 16px; border-radius: 8px;">
                                    <i class="fa fa-download"></i> Install NCS Billing System
                                </button>
                                <p class="help-block text-center" style="margin-top: 15px;">
                                    <small>This will install the NCS Billing System with your database configuration</small>
                                </p>
                            </div>
                        </div>
                    </div>
                </form>
        
                <?php 
                } 
                else {
                ?>
                <p class="alert alert-danger">
                    Please make the application/config/database.php file writable.<br>
                    <strong>Example</strong>:<br />
                    <code>chmod 777 application/config/database.php</code>
                    </p>
                <?php 
                } 
                ?>
            </div>
            
            <footer>
                <div class="col-md-12" style="text-align:center;margin-bottom:20px">
                    <hr>
                </div>
            </footer>
      </div>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <script type="text/javascript">
        /*Email validation code*/
        function validateEmail(sEmail) {
            var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,9}|[0-9]{1,3})(\]?)$/;
            if (filter.test(sEmail)) {
                return true;
            }
            else {
                return false;
            }
        }

          // Re-enable install button when page loads (in case user came back from error page)
          $(document).ready(function() {
              $("#send").prop('disabled', false).html('<i class="fa fa-download"></i> Install NCS Billing System');
          });

          $("#send").click(function(event) {
            
              event.preventDefault();
              var flag=true;

                function check_field(id)
                {

                  if(!$("#"+id).val().trim() ) //Also check Others????
                    {

                        $('#'+id+'_msg').fadeIn(200).show().html('Required Field').addClass('required');
                       // $('#'+id).css({'background-color' : '#E8E2E9'});
                        flag=false;
                    }
                    else
                    {
                         $('#'+id+'_msg').fadeOut(200).hide();
                         //$('#'+id).css({'background-color' : '#FFFFFF'});    //White color
                    }
                }


               //Validate Input box or selection box should not be blank or empty
                check_field("hostname");
                check_field("username");
                check_field("database");
                check_field("url");

                if(flag==false){
                    return false;
                }

                
                $("#send").val("Please wait...").attr('disabled',true);
                $("#install_form").submit();
                return;
          });
      </script>
	</body>
</html>
