<?php
// init_admin.php

// Database configuration
require_once 'bd/myData.php';

// Verify if script is running from command line
if (php_sapi_name() !== 'cli') {
    die('This script can only be run from the command line.');
}

// Function to check if any users exist
function checkExistingUsers() {
    try {
        $query = "SELECT COUNT(*) as count FROM users";
        $result = metodGet($query);
        $count = $result->fetch(PDO::FETCH_ASSOC)['count'];
        return $count > 0;
    } catch (Exception $e) {
        die("Error checking existing users: " . $e->getMessage() . "\n");
    }
}

// Function to validate password strength
function validatePassword($password) {
    // At least 8 characters, 1 uppercase, 1 lowercase, 1 number, 1 special character
    $uppercase = preg_match('@[A-Z]@', $password);
    $lowercase = preg_match('@[a-z]@', $password);
    $number    = preg_match('@[0-9]@', $password);
    $special   = preg_match('@[^\w]@', $password);

    return strlen($password) >= 8 && $uppercase && $lowercase && $number && $special;
}

// Function to create admin user
function createAdminUser($username, $password) {
    try {
        $query = "INSERT INTO users (
            username, 
            password, 
            role, 
            active, 
            profile,
            user_cre,
            first_login,
            date_cre
        ) VALUES (
            :username,
            :password,
            'admin',
            1,
            'Administrator',
            'system',
            0,
            CURRENT_TIMESTAMP
        )";

        $params = array(
            ':username' => $username,
            ':password' => password_hash($password, PASSWORD_BCRYPT)
        );

        connect();
        global $pdo;
        $statement = $pdo->prepare($query);
        $result = $statement->execute($params);

        if ($result) {
            // Log the creation in movement history
            logMovement('system', 'INSERT', 'users');
            echo "Admin user created successfully!\n";
            return true;
        }
        return false;
    } catch (Exception $e) {
        die("Error creating admin user: " . $e->getMessage() . "\n");
    }
}

// Main execution
echo "Admin User Initialization Script\n";
echo "==============================\n\n";

// Check if users already exist
if (checkExistingUsers()) {
    die("Users already exist in the database. This script is only for initial setup.\n");
}

// Get username
echo "Enter admin username: ";
$username = trim(fgets(STDIN));

if (strlen($username) < 4) {
    die("Username must be at least 4 characters long.\n");
}

// Get password
echo "Enter admin password (min 8 chars, must include uppercase, lowercase, number, and special char): ";
$password = trim(fgets(STDIN));

if (!validatePassword($password)) {
    die("Password does not meet security requirements.\n");
}

// Confirm password
echo "Confirm password: ";
$confirm_password = trim(fgets(STDIN));

if ($password !== $confirm_password) {
    die("Passwords do not match.\n");
}

// Create the admin user
if (createAdminUser($username, $password)) {
    echo "\nInitial setup complete! You can now log in with these credentials.\n";
} else {
    echo "\nFailed to create admin user. Please check the error logs.\n";
}