<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../includes/functions.php';

requireLogin();

$success = '';
$error = '';
$current_user = getCurrentUser();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    // Validate required fields
    if (!$username || !$email || !$current_password) {
        $error = 'Please fill in all required fields.';
    } else {
        $pdo = getDB();
        
        // Verify current password
        if (!password_verify($current_password, $current_user['password'])) {
            $error = 'Current password is incorrect.';
        } else {
            // Check if username or email already exists (excluding current user)
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE (username = ? OR email = ?) AND id != ?");
            $stmt->execute([$username, $email, $current_user['id']]);
            
            if ($stmt->fetchColumn() > 0) {
                $error = 'Username or email already exists.';
            } else {
                // Update user information
                if ($new_password) {
                    // Validate new password
                    if (strlen($new_password) < 6) {
                        $error = 'New password must be at least 6 characters long.';
                    } elseif ($new_password !== $confirm_password) {
                        $error = 'New passwords do not match.';
                    } else {
                        // Update with new password
                        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                        $stmt = $pdo->prepare("UPDATE users SET username = ?, email = ?, password = ? WHERE id = ?");
                        
                        if ($stmt->execute([$username, $email, $hashed_password, $current_user['id']])) {
                            $_SESSION['username'] = $username;
                            $success = 'Account updated successfully! Password has been changed.';
                            $current_user['username'] = $username;
                            $current_user['email'] = $email;
                        } else {
                            $error = 'Error updating account.';
                        }
                    }
                } else {
                    // Update without changing password
                    $stmt = $pdo->prepare("UPDATE users SET username = ?, email = ? WHERE id = ?");
                    
                    if ($stmt->execute([$username, $email, $current_user['id']])) {
                        $_SESSION['username'] = $username;
                        $success = 'Account updated successfully!';
                        $current_user['username'] = $username;
                        $current_user['email'] = $email;
                    } else {
                        $error = 'Error updating account.';
                    }
                }
            }
        }
    }
}

$page_title = 'Account Settings';
include 'includes/admin_header.php';
?>

<?php if ($error): ?>
    <div class="alert alert-error">
        <?php echo htmlspecialchars($error); ?>
    </div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="alert alert-success">
        <?php echo htmlspecialchars($success); ?>
    </div>
<?php endif; ?>

<div class="account-settings">
    <div class="settings-card">
        <div class="settings-header">
            <h2><i class="fas fa-user-cog"></i> Account Settings</h2>
            <p>Update your account information and change your password</p>
        </div>

        <form method="POST" class="account-form">
            <div class="form-section">
                <h3>Basic Information</h3>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="username">Username *</label>
                        <input type="text" id="username" name="username" required 
                               value="<?php echo htmlspecialchars($current_user['username']); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="email">Email Address *</label>
                        <input type="email" id="email" name="email" required 
                               value="<?php echo htmlspecialchars($current_user['email']); ?>">
                    </div>
                </div>
            </div>

            <div class="form-section">
                <h3>Password Change</h3>
                <p class="form-help">Leave password fields empty if you don't want to change your password</p>
                
                <div class="form-group">
                    <label for="current_password">Current Password *</label>
                    <input type="password" id="current_password" name="current_password" required>
                    <small>Required to save any changes</small>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="new_password">New Password</label>
                        <input type="password" id="new_password" name="new_password" minlength="6">
                        <small>Minimum 6 characters</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="confirm_password">Confirm New Password</label>
                        <input type="password" id="confirm_password" name="confirm_password">
                    </div>
                </div>
            </div>

            <div class="form-actions">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> Save Changes
                </button>
                <a href="dashboard.php" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>

    <div class="account-info">
        <div class="info-card">
            <h3><i class="fas fa-info-circle"></i> Account Information</h3>
            <div class="info-item">
                <label>User ID:</label>
                <span><?php echo $current_user['id']; ?></span>
            </div>
            <div class="info-item">
                <label>Role:</label>
                <span class="role-badge"><?php echo ucfirst($current_user['role']); ?></span>
            </div>
            <div class="info-item">
                <label>Account Created:</label>
                <span><?php echo formatDate($current_user['created_at']); ?></span>
            </div>
        </div>

        <div class="security-tips">
            <h4><i class="fas fa-shield-alt"></i> Security Tips</h4>
            <ul>
                <li>Use a strong password with at least 8 characters</li>
                <li>Include uppercase, lowercase, numbers, and symbols</li>
                <li>Don't reuse passwords from other accounts</li>
                <li>Change your password regularly</li>
            </ul>
        </div>
    </div>
</div>

<?php include 'includes/admin_footer.php'; ?>