<?php
session_start();
require_once '../../includes/config.php';

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    echo json_encode(['response' => 3, 'errormsg' => 'Unauthorized access']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $key = $_POST['_key'] ?? '';
    $submitted = $_POST['submitted'] ?? '';
    $ovh_ip = $_POST['ovh_ip'] ?? '';
    $ovh_username = $_POST['ovh_username'] ?? '';
    $ovh_password = $_POST['ovh_password'] ?? '';
    
    // Validate input
    if (empty($ovh_ip) || empty($ovh_password)) {
        echo json_encode(['response' => 2, 'msg' => 'IP Address and Password are required']);
        exit;
    }
    
    // Validate IP format
    if (!filter_var($ovh_ip, FILTER_VALIDATE_IP)) {
        echo json_encode(['response' => 2, 'msg' => 'Invalid IP Address format']);
        exit;
    }
    
    // Validate password strength
    if (strlen($ovh_password) < 8) {
        echo json_encode(['response' => 2, 'msg' => 'Password must be at least 8 characters long']);
        exit;
    }
    
    // TODO: Implement OVH API integration here
    // This would typically involve:
    // 1. Connecting to OVH API
    // 2. Authenticating with OVH credentials
    // 3. Updating the root password for the specified server
    // 4. Verifying the password change was successful
    
    // For now, log the action with correct table structure
    $db->sql_query("INSERT INTO activity_logs (user_id, date, action, ipaddress, device_os, device_client) VALUES 
                    ('{$_SESSION['user_id']}', NOW(), 
                     'OVH_ROOT_PASSWORD_CHANGE', 
                     '".$_SERVER['REMOTE_ADDR']."', 
                     'Web Panel', 
                     'Browser')");
    
    echo json_encode(['response' => 1, 'msg' => 'OVH Root password change request submitted successfully']);
    exit;
}

echo json_encode(['response' => 3, 'errormsg' => 'Invalid request']);
