<?php
/**
 * API file to sync user passwords with their group passwords
 * Designed to be run as a cron job
 */

// Database connection parameters - update these with your actual credentials
$db_host = 'localhost';
$db_name = 'anesoft_c89nl6wlzb9_new';
$db_user = 'anesoft_c89nl6wlzb9';
$db_pass = 'XJj9pkWI3JRa#';

// Establish database connection
try {
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Database connection failed: " . $e->getMessage();
    exit(1);
}

/**
 * Function to sync user passwords with their group passwords
 * This updates both user_pass and user_pass_clear fields
 * 
 * @return string Message indicating result of operation
 */
function sync_user_passwords($pdo) {
    try {
        // Run the password sync query
        $query = "
            UPDATE wp_users u
            JOIN wp_groups g ON u.group_id = g.id
            SET u.user_pass = g.group_pass,
                u.user_pass_clear = g.group_pass_clear
            WHERE u.group_id IS NOT NULL
        ";
        
        $stmt = $pdo->prepare($query);
        $result = $stmt->execute();
        
        if ($result) {
            $affected = $stmt->rowCount();
            return "Password synchronization complete. $affected account(s) updated.";
        } else {
            return "Error: Synchronization failed. " . implode(', ', $pdo->errorInfo());
        }
    } catch (Exception $e) {
        return "Error: " . $e->getMessage();
    }
}

// Add timestamp for logging
$timestamp = date('Y-m-d H:i:s');

// Execute the function and get the result
$result = sync_user_passwords($pdo);

// Determine the log file path (same directory as this script)
$log_file = __DIR__ . '/logs/sync_passwords_log.txt';

// Create log message
$log_message = "[$timestamp] $result" . PHP_EOL;

// Append result to log file
file_put_contents($log_file, $log_message, FILE_APPEND);

// Also output to stdout (helpful for debugging)
echo $log_message;
?>