<?php
/**
 * User Profile Page
 * Research Survey Management System
 */

define('PAGE_TITLE', 'My Profile');
require_once __DIR__ . '/../includes/functions.php';
requireAuth();

$pdo = getDBConnection();
$user = getCurrentUser();

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fullName = sanitize($_POST['full_name'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $currentPassword = $_POST['current_password'] ?? '';
    $newPassword = $_POST['new_password'] ?? '';
    
    if ($fullName && $email) {
        if (!empty($newPassword)) {
            $stmt = $pdo->prepare("SELECT password_hash FROM users WHERE user_id = :id");
            $stmt->execute(['id' => $_SESSION['user_id']]);
            $hash = $stmt->fetchColumn();
            
            if (!password_verify($currentPassword, $hash)) {
                $error = 'Current password is incorrect.';
            } elseif (strlen($newPassword) < 6) {
                $error = 'New password must be at least 6 characters.';
            } else {
                $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE users SET full_name = :name, email = :email, password_hash = :hash WHERE user_id = :id");
                $stmt->execute(['name' => $fullName, 'email' => $email, 'hash' => $newHash, 'id' => $_SESSION['user_id']]);
                $success = 'Profile and password updated successfully!';
            }
        } else {
            $stmt = $pdo->prepare("UPDATE users SET full_name = :name, email = :email WHERE user_id = :id");
            $stmt->execute(['name' => $fullName, 'email' => $email, 'id' => $_SESSION['user_id']]);
            $success = 'Profile updated successfully!';
        }
        
        $_SESSION['user_name'] = $fullName;
        logAudit('update', 'user', $_SESSION['user_id']);
    }
}

require_once __DIR__ . '/../includes/header.php';
?>

<div class="dashboard-header">
    <div>
        <h1><i class="fas fa-user me-2 text-primary"></i>My Profile</h1>
        <p>Manage your account settings</p>
    </div>
</div>

<div class="row g-3">
    <div class="col-md-4">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <div class="rounded-circle bg-primary text-white d-inline-flex align-items-center justify-content-center mb-3"
                     style="width:80px;height:80px;font-size:2rem;">
                    <?php echo strtoupper(substr($user['full_name'] ?? 'U', 0, 1)); ?>
                </div>
                <h5 class="card-title"><?php echo htmlspecialchars($user['full_name']); ?></h5>
                <p class="text-muted mb-0"><?php echo htmlspecialchars($user['role']); ?></p>
                <p class="text-muted small"><?php echo htmlspecialchars($user['department'] ?? ''); ?></p>
            </div>
        </div>
    </div>
    <div class="col-md-8">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-edit me-2 text-primary"></i>Edit Profile</h5>
            </div>
            <div class="card-body">
                <?php if ($error): ?>
                <div class="alert alert-danger"><?php echo $error; ?></div>
                <?php endif; ?>
                <?php if ($success): ?>
                <div class="alert alert-success"><?php echo $success; ?></div>
                <?php endif; ?>
                <form method="POST">
                    <div class="mb-3">
                        <label class="form-label">Full Name</label>
                        <input type="text" class="form-control" name="full_name" value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                    </div>
                    <hr>
                    <h6 class="fw-bold mb-3">Change Password</h6>
                    <div class="mb-3">
                        <label class="form-label">Current Password</label>
                        <input type="password" class="form-control" name="current_password">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">New Password</label>
                        <input type="password" class="form-control" name="new_password" minlength="6">
                        <small class="text-muted">Leave blank to keep current password</small>
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-1"></i> Update Profile
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

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