<?php
/**
 * Enterprise HRM ERP System - Fix Admin Login
 * This script will:
 * 1. Check if admin user exists
 * 2. Reset admin password if needed
 * 3. Unlock admin account if locked
 * 4. Activate admin account if inactive
 * DELETE THIS FILE AFTER USE FOR SECURITY
 */

require_once __DIR__ . '/includes/init.php';

$username = 'admin';
$newPassword = 'Admin@123'; // Default password - change after login!
$error = null;
$success = false;
$action = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = sanitize($_POST['username'] ?? 'admin');
    $newPassword = $_POST['new_password'] ?? 'Admin@123';
    $action = $_POST['action'] ?? 'reset';
    
    try {
        $db = getDB();
        $db->beginTransaction();
        
        // Check if user exists
        $stmt = $db->prepare("SELECT user_id, username, email, user_status, locked_until, failed_login_attempts FROM users WHERE username = ? OR email = ?");
        $stmt->execute([$username, $username]);
        $user = $stmt->fetch();
        
        if (!$user) {
            // Create admin user if doesn't exist
            $passwordHash = hashPassword($newPassword);
            $stmt = $db->prepare("
                INSERT INTO users (site_id, username, email, password_hash, full_name, role_id, user_status)
                VALUES (1, ?, ?, ?, 'System Administrator', 1, 'active')
            ");
            $stmt->execute([$username, $username . '@hrm.local', $passwordHash]);
            $success = true;
            $action = 'created';
        } else {
            // Reset password and unlock account
            $passwordHash = hashPassword($newPassword);
            $stmt = $db->prepare("
                UPDATE users 
                SET password_hash = ?, 
                    user_status = 'active',
                    failed_login_attempts = 0,
                    locked_until = NULL
                WHERE user_id = ?
            ");
            $stmt->execute([$passwordHash, $user['user_id']]);
            $success = true;
            $action = 'reset';
        }
        
        $db->commit();
        
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        $error = 'Error: ' . $e->getMessage();
        error_log("Fix admin login error: " . $e->getMessage());
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fix Admin Login</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        .container {
            background: white;
            padding: 40px;
            border-radius: 12px;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
            max-width: 500px;
            width: 100%;
        }
        h1 {
            color: #333;
            margin-bottom: 10px;
        }
        .subtitle {
            color: #666;
            margin-bottom: 30px;
        }
        .alert {
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
        }
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #dc2626;
        }
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }
        input[type="text"],
        input[type="password"] {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            box-sizing: border-box;
        }
        input:focus {
            outline: none;
            border-color: #1e293b;
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }
        .btn {
            width: 100%;
            padding: 12px;
            background: #1e293b;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            margin-top: 10px;
        }
        .btn:hover {
            background: #1d4ed8;
        }
        .credentials {
            background: #f3f4f6;
            padding: 20px;
            border-radius: 6px;
            margin: 20px 0;
        }
        .cred-item {
            margin: 10px 0;
        }
        .cred-label {
            font-weight: bold;
            display: inline-block;
            width: 100px;
        }
        .warning {
            background: #fef3c7;
            color: #92400e;
            padding: 15px;
            border-radius: 6px;
            margin-top: 20px;
            border-left: 4px solid #f59e0b;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Fix Admin Login</h1>
        <p class="subtitle">Reset Admin Password & Unlock Account</p>
        
        <?php if ($error): ?>
        <div class="alert alert-error">
            <?php echo htmlspecialchars($error); ?>
        </div>
        <?php endif; ?>
        
        <?php if ($success): ?>
        <div class="alert alert-success">
            <?php if ($action === 'created'): ?>
                <strong>✓ Admin User Created Successfully!</strong><br>
                A new admin user has been created.
            <?php else: ?>
                <strong>✓ Admin Account Fixed Successfully!</strong><br>
                Password has been reset and account has been unlocked.
            <?php endif; ?>
        </div>
        
        <div class="credentials">
            <h3>Login Credentials:</h3>
            <div class="cred-item">
                <span class="cred-label">Username:</span>
                <span><?php echo htmlspecialchars($username); ?></span>
            </div>
            <div class="cred-item">
                <span class="cred-label">Password:</span>
                <span><?php echo htmlspecialchars($newPassword); ?></span>
            </div>
        </div>
        
        <div class="warning">
            <strong>⚠️ IMPORTANT:</strong><br>
            1. Please change the password after first login<br>
            2. Delete this file (fix_admin_login.php) immediately for security
        </div>
        
        <a href="<?php echo BASE_URL; ?>/login.php" class="btn">Go to Login Page</a>
        
        <?php else: ?>
        
        <form method="POST">
            <div class="form-group">
                <label for="username">Username:</label>
                <input type="text" id="username" name="username" value="<?php echo htmlspecialchars($username); ?>" required>
            </div>
            
            <div class="form-group">
                <label for="new_password">New Password:</label>
                <input type="password" id="new_password" name="new_password" value="<?php echo htmlspecialchars($newPassword); ?>" required>
            </div>
            
            <input type="hidden" name="action" value="reset">
            
            <button type="submit" class="btn">Fix Admin Login</button>
        </form>
        
        <?php endif; ?>
    </div>
</body>
</html>
