<?php
/**
 * User Profile - Edit name, change password
 * PHP User Registration - https://rskworld.in
 * Developer: Molla Samser | RSK World
 * Contact: help@rskworld.in | +91 93305 39277
 * Year: 2026
 */

require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/includes/functions.php';
requireLogin();

$user = getCurrentUser();
if ($user === null) {
    session_destroy();
    header('Location: login.php');
    exit;
}

$errors = [];
$success = getFlash('success');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pdo = getDbConnection();

    if (isset($_POST['action']) && $_POST['action'] === 'update_name') {
        $name = sanitize($_POST['name'] ?? '');
        if (strlen($name) < 2) {
            $errors[] = 'Name must be at least 2 characters.';
        } else {
            $stmt = $pdo->prepare('UPDATE users SET name = ? WHERE id = ?');
            $stmt->execute([$name, $user['id']]);
            $_SESSION['user_name'] = $name;
            $user['name'] = $name;
            $success = 'Name updated.';
        }
    }

    if (isset($_POST['action']) && $_POST['action'] === 'change_password') {
        $current = $_POST['current_password'] ?? '';
        $new = $_POST['new_password'] ?? '';
        $confirm = $_POST['new_password_confirm'] ?? '';
        $stmt = $pdo->prepare('SELECT password FROM users WHERE id = ?');
        $stmt->execute([$user['id']]);
        $row = $stmt->fetch();
        if (!password_verify($current, $row['password'])) {
            $errors[] = 'Current password is incorrect.';
        } elseif (strlen($new) < 8) {
            $errors[] = 'New password must be at least 8 characters.';
        } elseif ($new !== $confirm) {
            $errors[] = 'New passwords do not match.';
        } else {
            $stmt = $pdo->prepare('UPDATE users SET password = ? WHERE id = ?');
            $stmt->execute([password_hash($new, PASSWORD_DEFAULT), $user['id']]);
            $success = 'Password changed.';
        }
    }

    if (isset($_POST['action']) && $_POST['action'] === 'upload_avatar' && !empty($_FILES['avatar']['tmp_name'])) {
        $file = $_FILES['avatar'];
        $maxSize = 2 * 1024 * 1024; // 2MB
        $allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        if ($file['size'] > $maxSize) {
            $errors[] = 'Image must be under 2 MB.';
        } elseif (!in_array($file['type'] ?? '', $allowed, true)) {
            $errors[] = 'Please upload a JPG, PNG, GIF or WebP image.';
        } else {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $file['tmp_name']);
            finfo_close($finfo);
            if (!in_array($mime, $allowed, true)) {
                $errors[] = 'Invalid image type.';
            } else {
                $extMap = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp'];
                $ext = $extMap[$mime] ?? 'jpg';
                $dir = __DIR__ . '/uploads/avatars';
                if (!is_dir($dir)) {
                    @mkdir($dir, 0755, true);
                }
                $filename = (int) $user['id'] . '.' . $ext;
                $path = $dir . '/' . $filename;
                if (move_uploaded_file($file['tmp_name'], $path)) {
                    try {
                        $pdo->prepare('UPDATE users SET avatar_path = ? WHERE id = ?')->execute(['uploads/avatars/' . $filename, $user['id']]);
                    } catch (PDOException $e) {
                        if ($e->getCode() === '42S22') {
                            try {
                                $pdo->exec('ALTER TABLE users ADD COLUMN avatar_path VARCHAR(255) NULL');
                                $pdo->prepare('UPDATE users SET avatar_path = ? WHERE id = ?')->execute(['uploads/avatars/' . $filename, $user['id']]);
                            } catch (PDOException $e2) {
                                $errors[] = 'Could not save avatar. Run sql/migrate-add-new-features.sql';
                                @unlink($path);
                            }
                        } else {
                            @unlink($path);
                            $errors[] = 'Could not save avatar.';
                        }
                    }
                    if (empty($errors)) {
                        $user['avatar_path'] = 'uploads/avatars/' . $filename;
                        $success = 'Profile picture updated.';
                    }
                } else {
                    $errors[] = 'Upload failed.';
                }
            }
        }
    }

    if (isset($_POST['action']) && $_POST['action'] === 'remove_avatar') {
        $oldPath = $user['avatar_path'] ?? null;
        if ($oldPath && is_string($oldPath)) {
            $full = __DIR__ . '/' . $oldPath;
            if (is_file($full)) @unlink($full);
        }
        try {
            $pdo->prepare('UPDATE users SET avatar_path = NULL WHERE id = ?')->execute([$user['id']]);
            $user['avatar_path'] = null;
            $success = 'Profile picture removed.';
        } catch (PDOException $e) {
            if ($e->getCode() === '42S22') { /* no column */ } else { $errors[] = 'Could not remove avatar.'; }
        }
    }
}

$pageTitle = 'Profile';
require_once __DIR__ . '/includes/header.php';
?>

<div class="auth-card profile-card">
    <h1><i class="fas fa-user"></i> Profile</h1>
    <p class="subtitle">PHP User Registration — <a href="https://rskworld.in" target="_blank">rskworld.in</a></p>

    <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if (!empty($errors)): ?>
        <div class="alert alert-error">
            <?php foreach ($errors as $e): ?>
                <div><?= htmlspecialchars($e) ?></div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <section class="profile-section">
        <h2>Profile picture</h2>
        <?php
        $avatarPath = $user['avatar_path'] ?? null;
        if ($avatarPath && is_string($avatarPath) && $avatarPath !== ''):
            $avatarSrc = (strpos($avatarPath, '/') === 0 || strpos($avatarPath, 'http') === 0) ? $avatarPath : $avatarPath;
        ?>
        <p><img src="<?= htmlspecialchars($avatarSrc) ?>" alt="Avatar" class="avatar avatar-lg" width="80" height="80"></p>
        <form method="post" action="" style="display:inline;">
            <input type="hidden" name="action" value="remove_avatar">
            <button type="submit" class="btn btn-secondary btn-sm">Remove picture</button>
        </form>
        <?php endif; ?>
        <form method="post" action="" enctype="multipart/form-data" class="auth-form">
            <input type="hidden" name="action" value="upload_avatar">
            <div class="form-group">
                <label for="avatar">Upload new picture (JPG, PNG, GIF or WebP, max 2 MB)</label>
                <input type="file" id="avatar" name="avatar" accept="image/jpeg,image/png,image/gif,image/webp">
            </div>
            <button type="submit" class="btn btn-primary">Upload</button>
        </form>
    </section>

    <section class="profile-section">
        <h2>Update name</h2>
        <form method="post" action="" class="auth-form">
            <input type="hidden" name="action" value="update_name">
            <div class="form-group">
                <label for="name">Full Name</label>
                <input type="text" id="name" name="name" value="<?= htmlspecialchars($user['name'] ?? '') ?>" required minlength="2">
            </div>
            <button type="submit" class="btn btn-primary">Save Name</button>
        </form>
    </section>

    <section class="profile-section">
        <h2>Change password</h2>
        <form method="post" action="" class="auth-form">
            <input type="hidden" name="action" value="change_password">
            <div class="form-group">
                <label for="current_password">Current Password</label>
                <input type="password" id="current_password" name="current_password" required>
            </div>
            <div class="form-group">
                <label for="new_password">New Password</label>
                <input type="password" id="new_password" name="new_password" required minlength="8">
                <span id="new-password-strength" class="password-strength" aria-live="polite"></span>
            </div>
            <div class="form-group">
                <label for="new_password_confirm">Confirm New Password</label>
                <input type="password" id="new_password_confirm" name="new_password_confirm" required minlength="8">
            </div>
            <button type="submit" class="btn btn-primary">Change Password</button>
        </form>
    </section>
    <script>
    (function() {
        var el = document.getElementById('new_password');
        var out = document.getElementById('new-password-strength');
        if (!el || !out) return;
        function strength(p) {
            if (!p || p.length < 6) return { label: 'Too short', cls: 'strength-weak' };
            if (p.length < 8) return { label: 'Weak', cls: 'strength-weak' };
            var hasNum = /\d/.test(p), hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(p), hasUpper = /[A-Z]/.test(p);
            if (p.length >= 12 && hasNum && (hasSpecial || hasUpper)) return { label: 'Strong', cls: 'strength-strong' };
            if (p.length >= 8 && (hasNum || hasSpecial || hasUpper)) return { label: 'Medium', cls: 'strength-medium' };
            return { label: 'Weak', cls: 'strength-weak' };
        }
        el.addEventListener('input', function() {
            var s = strength(this.value);
            out.textContent = this.value ? s.label : '';
            out.className = 'password-strength ' + (this.value ? s.cls : '');
        });
    })();
    </script>
    <p class="auth-footer">
        <a href="dashboard.php">Back to Dashboard</a>
        &nbsp;|&nbsp; <a href="delete-account.php" class="text-danger">Delete account</a>
    </p>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
