#!/usr/bin/env php
<?php
/**
 * Server Account Creation Helper
 * Creates server accounts with properly hashed passwords
 * 
 * Usage:
 * php backend/create_server_account.php
 * 
 * Then follow the prompts to:
 * 1. Enter server name
 * 2. Enter employee ID (used for login)
 * 3. Enter password
 * 4. Enter phone number
 * 
 * Or use it in your manager dashboard to create accounts
 */

if (php_sapi_name() !== 'cli' && !isset($_REQUEST['action'])) {
    die('This script is for CLI or form submission only');
}

define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'granny_restaurant');

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if ($conn->connect_error) {
    die(json_encode(['success' => false, 'message' => 'Connection failed: ' . $conn->connect_error]));
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    
    switch ($action) {
        case 'create_server':
            createServerAccount();
            break;
        case 'list_servers':
            listServers();
            break;
        case 'update_server_password':
            updateServerPassword();
            break;
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    exit;
}

// CLI mode
if (php_sapi_name() === 'cli') {
    echo "\n===== SERVER ACCOUNT MANAGER =====\n\n";
    echo "1. Create new server account\n";
    echo "2. List all servers\n";
    echo "3. Update server password\n";
    echo "4. Exit\n\n";
    
    echo "Choose option (1-4): ";
    $choice = trim(fgets(STDIN));
    
    switch ($choice) {
        case '1':
            createServerCLI();
            break;
        case '2':
            listServersCLI();
            break;
        case '3':
            updateServerPasswordCLI();
            break;
        case '4':
            echo "Goodbye!\n";
            exit;
        default:
            echo "Invalid option\n";
    }
}

// ===== Functions =====

function createServerAccount() {
    global $conn;
    
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $employee_id = isset($_POST['employee_id']) ? trim($_POST['employee_id']) : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    
    // Validation
    if (empty($name)) {
        echo json_encode(['success' => false, 'message' => 'Server name is required']);
        return;
    }
    
    if (empty($employee_id)) {
        echo json_encode(['success' => false, 'message' => 'Employee ID is required']);
        return;
    }
    
    if (empty($password) || strlen($password) < 6) {
        echo json_encode(['success' => false, 'message' => 'Password must be at least 6 characters']);
        return;
    }
    
    // Check if employee_id already exists
    $emp_check = $conn->query("SELECT id FROM servers WHERE employee_id = '" . $conn->real_escape_string($employee_id) . "'");
    if ($emp_check && $emp_check->num_rows > 0) {
        echo json_encode(['success' => false, 'message' => 'Employee ID already exists']);
        return;
    }
    
    // Hash password
    $hashed_password = password_hash($password, PASSWORD_BCRYPT);
    
    // Insert server
    $sql = "INSERT INTO servers (name, employee_id, password, phone, status, is_online)
            VALUES (
                '" . $conn->real_escape_string($name) . "',
                '" . $conn->real_escape_string($employee_id) . "',
                '" . $conn->real_escape_string($hashed_password) . "',
                " . ($phone ? "'" . $conn->real_escape_string($phone) . "'" : "NULL") . ",
                'available',
                FALSE
            )";
    
    if ($conn->query($sql) === TRUE) {
        $server_id = $conn->insert_id;
        echo json_encode([
            'success' => true,
            'message' => 'Server account created successfully',
            'server_id' => $server_id,
            'employee_id' => $employee_id
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error creating account: ' . $conn->error]);
    }
}

function listServers() {
    global $conn;
    
    $sql = "SELECT id, name, employee_id, phone, status, is_online, created_at
            FROM servers
            ORDER BY name";
    
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $servers = [];
        while ($row = $result->fetch_assoc()) {
            $servers[] = $row;
        }
        echo json_encode([
            'success' => true,
            'message' => 'Servers retrieved',
            'data' => $servers,
            'count' => count($servers)
        ]);
    } else {
        echo json_encode(['success' => true, 'message' => 'No servers found', 'data' => []]);
    }
}

function updateServerPassword() {
    global $conn;
    
    $server_id = isset($_POST['server_id']) ? intval($_POST['server_id']) : 0;
    $new_password = isset($_POST['password']) ? $_POST['password'] : '';
    
    if (!$server_id) {
        echo json_encode(['success' => false, 'message' => 'Server ID is required']);
        return;
    }
    
    if (empty($new_password) || strlen($new_password) < 6) {
        echo json_encode(['success' => false, 'message' => 'Password must be at least 6 characters']);
        return;
    }
    
    // Check if server exists
    $check = $conn->query("SELECT id FROM servers WHERE id = " . $server_id);
    if (!$check || $check->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Server not found']);
        return;
    }
    
    // Hash password
    $hashed_password = password_hash($new_password, PASSWORD_BCRYPT);
    
    // Update password
    $sql = "UPDATE servers SET password = '" . $conn->real_escape_string($hashed_password) . "'
            WHERE id = " . $server_id;
    
    if ($conn->query($sql) === TRUE) {
        echo json_encode(['success' => true, 'message' => 'Password updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating password: ' . $conn->error]);
    }
}

function createServerCLI() {
    global $conn;
    
    echo "\n--- Create New Server Account ---\n\n";
    
    echo "Enter server name: ";
    $name = trim(fgets(STDIN));
    
    echo "Enter employee ID: ";
    $employee_id = trim(fgets(STDIN));
    
    echo "Enter password (min 6 characters): ";
    $password = trim(fgets(STDIN));
    
    echo "Enter phone number (or press Enter to skip): ";
    $phone = trim(fgets(STDIN));
    
    // Validation
    if (empty($name)) {
        echo "ERROR: Server name is required\n";
        return;
    }
    
    if (empty($employee_id)) {
        echo "ERROR: Employee ID is required\n";
        return;
    }
    
    if (empty($password) || strlen($password) < 6) {
        echo "ERROR: Password must be at least 6 characters\n";
        return;
    }
    
    // Check if employee_id already exists
    $emp_check = $conn->query("SELECT id FROM servers WHERE employee_id = '" . $conn->real_escape_string($employee_id) . "'");
    if ($emp_check && $emp_check->num_rows > 0) {
        echo "ERROR: Employee ID already exists\n";
        return;
    }
    
    // Hash password
    $hashed_password = password_hash($password, PASSWORD_BCRYPT);
    
    // Insert server
    $sql = "INSERT INTO servers (name, employee_id, password, phone, status, is_online)
            VALUES (
                '" . $conn->real_escape_string($name) . "',
                '" . $conn->real_escape_string($employee_id) . "',
                '" . $conn->real_escape_string($hashed_password) . "',
                " . ($phone ? "'" . $conn->real_escape_string($phone) . "'" : "NULL") . ",
                'available',
                FALSE
            )";
    
    if ($conn->query($sql) === TRUE) {
        $server_id = $conn->insert_id;
        echo "\n✓ Server account created successfully!\n";
        echo "Server ID: " . $server_id . "\n";
        echo "Employee ID: " . $employee_id . "\n";
        echo "Name: " . $name . "\n\n";
    } else {
        echo "ERROR: " . $conn->error . "\n";
    }
}

function listServersCLI() {
    global $conn;
    
    $sql = "SELECT id, name, employee_id, phone, status, is_online
            FROM servers
            ORDER BY name";
    
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        echo "\n--- Server List ---\n\n";
        printf("%-3s %-20s %-15s %-12s %-8s\n", "ID", "Name", "Emp ID", "Status", "Online");
        echo str_repeat("-", 70) . "\n";
        
        while ($row = $result->fetch_assoc()) {
            $online = $row['is_online'] ? "Yes" : "No";
            printf("%-3s %-20s %-15s %-12s %-8s\n",
                $row['id'],
                substr($row['name'], 0, 20),
                $row['employee_id'] ?? '-',
                $row['status'],
                $online
            );
        }
        echo "\n";
    } else {
        echo "\nNo servers found.\n\n";
    }
}

function updateServerPasswordCLI() {
    global $conn;
    
    echo "\n--- Update Server Password ---\n\n";
    
    // List servers first
    listServersCLI();
    
    echo "Enter server ID: ";
    $server_id = intval(trim(fgets(STDIN)));
    
    // Check if server exists
    $check = $conn->query("SELECT name, employee_id FROM servers WHERE id = " . $server_id);
    if (!$check || $check->num_rows === 0) {
        echo "ERROR: Server not found\n";
        return;
    }
    
    $server = $check->fetch_assoc();
    echo "Server: " . $server['name'] . " (ID: " . $server['employee_id'] . ")\n";
    
    echo "Enter new password (min 6 characters): ";
    $password = trim(fgets(STDIN));
    
    if (empty($password) || strlen($password) < 6) {
        echo "ERROR: Password must be at least 6 characters\n";
        return;
    }
    
    // Hash password
    $hashed_password = password_hash($password, PASSWORD_BCRYPT);
    
    // Update password
    $sql = "UPDATE servers SET password = '" . $conn->real_escape_string($hashed_password) . "'
            WHERE id = " . $server_id;
    
    if ($conn->query($sql) === TRUE) {
        echo "\n✓ Password updated successfully!\n\n";
    } else {
        echo "ERROR: " . $conn->error . "\n";
    }
}

$conn->close();
?>
