<?php
$pageTitle = 'Mon Profil';
require_once __DIR__ . '/includes/header.php';
$db = getDB();

$user = getCurrentUser();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fullName = sanitize($_POST['full_name'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $phone = sanitize($_POST['phone'] ?? '');
    $currentPassword = $_POST['current_password'] ?? '';
    $newPassword = $_POST['new_password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';

    // Update profile info
    $db->prepare("UPDATE users SET full_name=?, email=?, phone=?, updated_at=datetime('now') WHERE id=?")
        ->execute([$fullName, $email, $phone, $_SESSION['user_id']]);
    $_SESSION['user_name'] = $fullName;

    // Change password if provided
    if ($newPassword) {
        if (!password_verify($currentPassword, $user['password'])) {
            flash('error', 'Mot de passe actuel incorrect.');
            redirect('/profil.php');
        }
        if ($newPassword !== $confirmPassword) {
            flash('error', 'Les mots de passe ne correspondent pas.');
            redirect('/profil.php');
        }
        if (strlen($newPassword) < 6) {
            flash('error', 'Le mot de passe doit contenir au moins 6 caractères.');
            redirect('/profil.php');
        }
        $db->prepare("UPDATE users SET password=? WHERE id=?")
            ->execute([password_hash($newPassword, PASSWORD_DEFAULT), $_SESSION['user_id']]);
        logAction($_SESSION['user_id'], 'password_change', 'Mot de passe modifié');
    }

    logAction($_SESSION['user_id'], 'profile_update', 'Profil mis à jour');
    flash('success', 'Profil mis à jour avec succès.');
    redirect('/profil.php');
}

$roleLabels = ['admin'=>'Administrateur','responsable'=>'Responsable Tourisme/Hajj/Omra','comptable'=>'Comptable','agent'=>'Agent commercial'];
?>

<div class="row justify-content-center">
    <div class="col-lg-8">
        <div class="card table-card mb-4">
            <div class="card-header"><i class="bi bi-person-circle me-2"></i>Informations du compte</div>
            <div class="card-body p-4">
                <div class="text-center mb-4">
                    <div class="rounded-circle bg-primary bg-opacity-10 d-inline-flex align-items-center justify-content-center mb-2" style="width:80px;height:80px;">
                        <i class="bi bi-person-fill text-primary" style="font-size:2.5rem;"></i>
                    </div>
                    <h5 class="mb-1"><?= sanitize($user['full_name']) ?></h5>
                    <span class="badge bg-primary"><?= $roleLabels[$user['role']] ?? $user['role'] ?></span>
                    <p class="text-muted small mt-2">Dernière connexion: <?= $user['last_login'] ? formatDateTime($user['last_login']) : 'N/A' ?></p>
                </div>

                <form method="POST">
                    <h6 class="text-primary border-bottom pb-2 mb-3">Informations personnelles</h6>
                    <div class="row g-3 mb-4">
                        <div class="col-md-4">
                            <label class="form-label">Nom d'utilisateur</label>
                            <input type="text" class="form-control" value="<?= sanitize($user['username']) ?>" disabled>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Nom complet *</label>
                            <input type="text" name="full_name" class="form-control" value="<?= sanitize($user['full_name']) ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Rôle</label>
                            <input type="text" class="form-control" value="<?= $roleLabels[$user['role']] ?? $user['role'] ?>" disabled>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Email</label>
                            <input type="email" name="email" class="form-control" value="<?= sanitize($user['email'] ?? '') ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Téléphone</label>
                            <input type="text" name="phone" class="form-control" value="<?= sanitize($user['phone'] ?? '') ?>">
                        </div>
                    </div>

                    <h6 class="text-primary border-bottom pb-2 mb-3">Changer le mot de passe</h6>
                    <div class="row g-3 mb-4">
                        <div class="col-md-4">
                            <label class="form-label">Mot de passe actuel</label>
                            <input type="password" name="current_password" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Nouveau mot de passe</label>
                            <input type="password" name="new_password" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Confirmer</label>
                            <input type="password" name="confirm_password" class="form-control">
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>Enregistrer les modifications</button>
                </form>
            </div>
        </div>
    </div>
</div>

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