<?php
/**
 * Portail — Mon profil (élève / parent)
 */
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';

checkRole(['student', 'parent']);

$userId = (int)$_SESSION['user_id'];
$error  = '';

// ── Sauvegarde mot de passe / photo ────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();

    // Photo upload
    if (!empty($_FILES['photo']['name'])) {
        $allowedExts = ['jpg','jpeg','png','gif','webp'];
        $ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedExts)) {
            $error = 'Format de photo non autorisé (jpeg, png, gif, webp).';
        } elseif ($_FILES['photo']['size'] > 2 * 1024 * 1024) {
            $error = 'La photo ne doit pas dépasser 2 Mo.';
        } else {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $_FILES['photo']['tmp_name']);
            finfo_close($finfo);
            if (!in_array($mime, ['image/jpeg','image/png','image/gif','image/webp'])) {
                $error = 'Le fichier n\'est pas une image valide.';
            } else {
                $old = $pdo->prepare("SELECT photo FROM users WHERE id=?");
                $old->execute([$userId]); $oldPhoto = $old->fetchColumn();
                if ($oldPhoto && file_exists(__DIR__ . '/../uploads/users/' . $oldPhoto)) {
                    unlink(__DIR__ . '/../uploads/users/' . $oldPhoto);
                }
                $photo = uniqid('user_') . '.' . $ext;
                move_uploaded_file($_FILES['photo']['tmp_name'], __DIR__ . '/../uploads/users/' . $photo);
                $pdo->prepare("UPDATE users SET photo=? WHERE id=?")->execute([$photo, $userId]);
                $_SESSION['user_photo'] = $photo;
                flashMessage('success', 'Photo de profil mise à jour.');
                header('Location: profile.php'); exit;
            }
        }
    }

    // Suppression photo
    if (!empty($_POST['remove_photo'])) {
        $old = $pdo->prepare("SELECT photo FROM users WHERE id=?");
        $old->execute([$userId]); $oldPhoto = $old->fetchColumn();
        if ($oldPhoto && file_exists(__DIR__ . '/../uploads/users/' . $oldPhoto)) {
            unlink(__DIR__ . '/../uploads/users/' . $oldPhoto);
        }
        $pdo->prepare("UPDATE users SET photo=NULL WHERE id=?")->execute([$userId]);
        $_SESSION['user_photo'] = null;
        flashMessage('success', 'Photo supprimée.');
        header('Location: profile.php'); exit;
    }

    $currentPwd = $_POST['current_password'] ?? '';
    $newPwd     = $_POST['new_password']     ?? '';
    $confirmPwd = $_POST['confirm_password'] ?? '';

    $stmt = $pdo->prepare("SELECT password FROM users WHERE id=?");
    $stmt->execute([$userId]);
    $row = $stmt->fetch();

    if (!$row || !password_verify($currentPwd, $row['password'])) {
        $error = 'Mot de passe actuel incorrect.';
    } elseif (strlen($newPwd) < 12) {
        $error = 'Le nouveau mot de passe doit comporter au moins 12 caractères.';
    } elseif (!preg_match('/[A-Z]/', $newPwd)) {
        $error = 'Le nouveau mot de passe doit contenir au moins une majuscule.';
    } elseif (!preg_match('/[0-9]/', $newPwd)) {
        $error = 'Le nouveau mot de passe doit contenir au moins un chiffre.';
    } elseif ($newPwd !== $confirmPwd) {
        $error = 'Les deux mots de passe ne correspondent pas.';
    } else {
        $hash = password_hash($newPwd, PASSWORD_BCRYPT, ['cost' => BCRYPT_COST]);
        $pdo->prepare("UPDATE users SET password=?, plain_password=null WHERE id=?")->execute([$hash, $userId]);
        $role = $_SESSION['user_role'];
        $name = $_SESSION['user_name'];
        $phone = getUserPhone($pdo, $userId, $role);
        if ($phone) {
            sendWhatsApp($phone, "Bonjour $name, votre mot de passe Nukunu Mofiala a été modifié. Nouveau mot de passe : $newPwd");
        }
        flashMessage('success', 'Mot de passe mis à jour avec succès.');
        header('Location: profile.php'); exit;
    }
}

// ── Données utilisateur ───────────────────────────────────────────────────────
$stmt = $pdo->prepare("SELECT u.*, s.name AS school_name FROM users u LEFT JOIN schools s ON u.school_id=s.id WHERE u.id=?");
$stmt->execute([$userId]);
$user = $stmt->fetch();

// Données élève liées
$studentData = null;
if ($_SESSION['user_role'] === 'student') {
    $stmt = $pdo->prepare("SELECT s.*, c.name AS class_name, sc.name AS school_name
        FROM students s
        LEFT JOIN classes c ON s.class_id=c.id
        LEFT JOIN schools sc ON s.school_id=sc.id
        WHERE s.user_id=?");
    $stmt->execute([$userId]);
    $studentData = $stmt->fetch();
}

// Enfants liés (parent)
$children = [];
if ($_SESSION['user_role'] === 'parent') {
    $stmt = $pdo->prepare("
        SELECT s.*, c.name AS class_name, sc.name AS school_name
        FROM parent_students ps
        JOIN students s ON ps.student_id=s.id
        LEFT JOIN classes c ON s.class_id=c.id
        LEFT JOIN schools sc ON s.school_id=sc.id
        WHERE ps.user_id=?
        ORDER BY s.last_name, s.first_name
    ");
    $stmt->execute([$userId]);
    $children = $stmt->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mon profil - Nukunu Mofiala</title>
    <link rel="stylesheet" href="<?= BASE_URL ?>assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
<div class="dashboard">
    <?php include '../includes/portal_sidebar.php'; ?>
    <div class="main-content">
        <div class="header-bar">
            <h1><i class="fas fa-user-circle"></i> Mon profil</h1>
        </div>
        <?= showFlash() ?>
        <?php if ($error): ?><div class="error-message"><?= e($error) ?></div><?php endif; ?>

        <div class="dashboard-grid-2">

            <!-- Informations du compte -->
            <div class="card">
                <div class="card-header">
                    <span class="card-title"><i class="fas fa-id-card"></i> Informations du compte</span>
                </div>
                <div style="display:flex;align-items:center;gap:1rem;margin-bottom:1.5rem;">
                    <?= userPhotoImg($user['photo'] ?? null, $user['name'], 'large') ?>
                    <div>
                        <div style="font-size:1.1rem;font-weight:700;color:#2d3748;"><?= e($user['name']) ?></div>
                        <div style="color:#718096;"><?= e($user['email']) ?></div>
                        <span class="badge <?= getRoleBadgeClass($user['role']) ?>" style="margin-top:.3rem;">
                            <?= getRoleLabel($user['role']) ?>
                        </span>
                    </div>
                </div>
                <form method="POST" enctype="multipart/form-data" style="margin-bottom:1rem;">
                    <?= csrfField() ?>
                    <div style="display:flex;align-items:center;gap:.75rem;flex-wrap:wrap;">
                        <input type="file" name="photo" accept="image/jpeg,image/png,image/gif,image/webp" style="flex:1;min-width:140px;">
                        <button type="submit" class="btn-action btn-edit" style="font-size:.85rem;"><i class="fas fa-upload"></i> Changer photo</button>
                        <?php if (!empty($user['photo'])): ?>
                        <button type="submit" name="remove_photo" value="1" class="btn-action btn-delete" style="font-size:.85rem;" onclick="return confirm('Supprimer la photo ?')"><i class="fas fa-trash"></i> Supprimer</button>
                        <?php endif; ?>
                    </div>
                    <small style="color:#718096;">Max 2 Mo — JPEG, PNG, GIF, WebP</small>
                </form>
                <table style="width:100%;border-collapse:collapse;">
                    <tr><td style="padding:.5rem;color:#718096;font-weight:500;">École</td><td><?= e($user['school_name'] ?? 'N/A') ?></td></tr>
                    <tr><td style="padding:.5rem;color:#718096;font-weight:500;">Compte créé le</td><td><?= formatDate($user['created_at']) ?></td></tr>
                    <tr><td style="padding:.5rem;color:#718096;font-weight:500;">Statut</td>
                        <td><?= $user['active'] ? '<span style="color:#22543d;font-weight:600;">✅ Actif</span>' : '<span style="color:#c53030;">❌ Inactif</span>' ?></td>
                    </tr>
                </table>
            </div>

            <!-- Changer le mot de passe -->
            <div class="card">
                <div class="card-header">
                    <span class="card-title"><i class="fas fa-lock"></i> Changer le mot de passe</span>
                </div>
                <form method="POST">
                    <?= csrfField() ?>
                    <div class="form-group">
                        <label>Mot de passe actuel <span style="color:red">*</span></label>
                        <input type="password" name="current_password" required>
                    </div>
                    <div class="form-group">
                        <label>Nouveau mot de passe <span style="color:red">*</span></label>
                        <input type="password" name="new_password" required minlength="12" placeholder="Min. 12 caractères">
                    </div>
                    <div class="form-group">
                        <label>Confirmer le mot de passe <span style="color:red">*</span></label>
                        <input type="password" name="confirm_password" required minlength="8">
                    </div>
                    <button type="submit" class="btn-submit"><i class="fas fa-save"></i> Mettre à jour</button>
                </form>
            </div>
        </div>

        <?php if ($studentData): ?>
        <!-- Profil élève -->
        <div class="card" style="margin-top:1.5rem;">
            <div class="card-header">
                <span class="card-title"><i class="fas fa-user-graduate"></i> Mes informations scolaires</span>
            </div>
            <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:1rem;">
                <div><span style="color:#718096;font-size:.85rem;">Prénom</span><div style="font-weight:600;"><?= e($studentData['first_name']) ?></div></div>
                <div><span style="color:#718096;font-size:.85rem;">Nom</span><div style="font-weight:600;"><?= e($studentData['last_name']) ?></div></div>
                <div><span style="color:#718096;font-size:.85rem;">Classe</span><div style="font-weight:600;"><?= e($studentData['class_name'] ?? '-') ?></div></div>
                <div><span style="color:#718096;font-size:.85rem;">École</span><div style="font-weight:600;"><?= e($studentData['school_name'] ?? '-') ?></div></div>
                <div><span style="color:#718096;font-size:.85rem;">Date de naissance</span><div style="font-weight:600;"><?= formatDate($studentData['birth_date']) ?></div></div>
                <div><span style="color:#718096;font-size:.85rem;">Genre</span><div style="font-weight:600;"><?= e($studentData['gender'] ?? '-') ?></div></div>
            </div>
        </div>
        <?php endif; ?>

        <?php if (!empty($children)): ?>
        <!-- Enfants (parent) -->
        <div class="card" style="margin-top:1.5rem;">
            <div class="card-header">
                <span class="card-title"><i class="fas fa-child"></i> Mes enfants</span>
                <a href="<?= BASE_URL ?>portal/children.php" class="btn-action btn-view">Voir détails</a>
            </div>
            <div style="display:flex;gap:1rem;flex-wrap:wrap;">
            <?php foreach ($children as $ch): ?>
            <div style="background:#f7fafc;border-radius:10px;padding:1rem;min-width:180px;border:1px solid #e2e8f0;">
                <div class="sidebar-user-avatar" style="width:40px;height:40px;font-size:1.1rem;margin-bottom:.5rem;">
                    <?= strtoupper(mb_substr($ch['first_name'], 0, 1)) ?>
                </div>
                <div style="font-weight:700;color:#2d3748;"><?= e($ch['last_name'].' '.$ch['first_name']) ?></div>
                <div style="color:#718096;font-size:.85rem;"><?= e($ch['class_name'] ?? '-') ?></div>
                <div style="color:#a0aec0;font-size:.8rem;"><?= e($ch['school_name'] ?? '-') ?></div>
            </div>
            <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

    </div>
</div>
</body>
</html>
