<?php
/**
 * Admin Password Reset - Command Line Script
 * 
 * Usage: php reset_admin_password_cli.php [username] [new_password]
 * 
 * If no arguments provided, it will reset the first admin user's password to 'admin123'
 */

require_once 'config.php';

// Get command line arguments
$username = $argv[1] ?? null;
$newPassword = $argv[2] ?? null;

// If no username provided, get the first admin user
if (!$username) {
    $result = $conn->query("SELECT username FROM admin_users WHERE status = 'active' ORDER BY id LIMIT 1");
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $username = $row['username'];
        echo "No username provided. Using first active admin: {$username}\n";
    } else {
        die("Error: No admin users found in database.\n");
    }
}

// If no password provided, use default
if (!$newPassword) {
    $newPassword = 'admin123';
    echo "No password provided. Using default password: {$newPassword}\n";
}

// Validate password length
if (strlen($newPassword) < 6) {
    die("Error: Password must be at least 6 characters long.\n");
}

// Check if admin user exists
$checkStmt = $conn->prepare("SELECT id, username, role, status FROM admin_users WHERE username = ?");
$checkStmt->bind_param("s", $username);
$checkStmt->execute();
$result = $checkStmt->get_result();

if ($result->num_rows === 0) {
    die("Error: Admin user '{$username}' not found.\n");
}

$admin = $result->fetch_assoc();
$checkStmt->close();

echo "\n";
echo "========================================\n";
echo "  ADMIN PASSWORD RESET\n";
echo "========================================\n";
echo "Username: {$admin['username']}\n";
echo "Role: {$admin['role']}\n";
echo "Status: {$admin['status']}\n";
echo "----------------------------------------\n";

// Hash the new password
$passwordHash = password_hash($newPassword, PASSWORD_DEFAULT);

// Update the password
$updateStmt = $conn->prepare("UPDATE admin_users SET password_hash = ?, updated_at = NOW() WHERE username = ?");
$updateStmt->bind_param("ss", $passwordHash, $username);

if ($updateStmt->execute()) {
    echo "✓ Password reset successfully!\n";
    echo "----------------------------------------\n";
    echo "NEW LOGIN CREDENTIALS:\n";
    echo "----------------------------------------\n";
    echo "Username: {$username}\n";
    echo "Password: {$newPassword}\n";
    echo "----------------------------------------\n";
    echo "\n";
    echo "⚠️  IMPORTANT: Please change this password after logging in!\n";
    echo "\n";
} else {
    die("Error: Failed to reset password - " . $updateStmt->error . "\n");
}

$updateStmt->close();
$conn->close();

?>

