<?php
/**
 * Reset Admin Password
 * Run this script once to reset the admin password
 * DELETE AFTER USE!
 */

require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/config/database.php';

echo "<h1>Reset Admin Password</h1>";

try {
    $pdo = get_db_connection();
    
    // New password
    $new_password = 'Admin@123';
    $hash = password_hash($new_password, PASSWORD_DEFAULT, ['cost' => 12]);
    
    echo "New hash: <code>$hash</code><br><br>";
    
    // Update admin user
    $stmt = $pdo->prepare("UPDATE users SET password_hash = ? WHERE username = ? OR email = ?");
    $result = $stmt->execute([$hash, 'admin', 'admin']);
    
    if ($stmt->rowCount() > 0) {
        echo "<p style='color: green'>✓ Admin password reset successfully to 'Admin@123'</p>";
    } else {
        echo "<p style='color: orange'>No admin user found. Creating one...</p>";
        
        // Create admin user if not exists
        $stmt = $pdo->prepare("INSERT INTO users (username, email, password_hash, first_name, last_name, role_id, is_active) 
                               VALUES (?, ?, ?, ?, ?, ?, ?)");
        $result = $stmt->execute(['admin', 'admin@ruhondo.com', $hash, 'System', 'Administrator', 1, 1]);
        
        if ($result) {
            echo "<p style='color: green'>✓ Admin user created with password 'Admin@123'</p>";
        } else {
            echo "<p style='color: red'>✗ Failed to create admin user</p>";
        }
    }
    
    // Also update other test users
    $test_users = ['superadmin', 'fdagent1', 'cashier1'];
    foreach ($test_users as $username) {
        $stmt = $pdo->prepare("UPDATE users SET password_hash = ? WHERE username = ?");
        $stmt->execute([$hash, $username]);
        if ($stmt->rowCount() > 0) {
            echo "<p style='color: green'>✓ Password reset for '$username'</p>";
        }
    }
    
} catch (Exception $e) {
    echo "<p style='color: red'>Error: " . $e->getMessage() . "</p>";
}

echo "<hr>";
echo "<p><a href='login.php'>Go to Login Page</a></p>";
echo "<p><strong>IMPORTANT: Delete this file after use!</strong></p>";