<?php
/**
 * Mon profil — Directeurs / Enseignants
 */
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';
header('Content-Type: text/html; charset=utf-8');

checkRole(['super_admin', 'school_admin', 'teacher', 'accountant']);

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

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

    $name       = trim($_POST['name']       ?? '');
    $email      = trim($_POST['email']      ?? '');
    $gender     = $_POST['gender']          ?? '';
    $birth_date = $_POST['birth_date']      ?? '';
    $currentPwd = $_POST['current_password']?? '';
    $newPwd     = $_POST['new_password']    ?? '';
    $confirmPwd = $_POST['confirm_password']?? '';

    if (empty($name))  $error = 'Le nom est requis.';
    if (empty($email)) $error = 'L\'email est requis.';
    if (!in_array($gender, ['M','F','Autre'], true)) $gender = null;

    if (!$error) {
        // Vérifier email unique
        $chk = $pdo->prepare("SELECT id FROM users WHERE email=? AND id!=?");
        $chk->execute([$email, $userId]);
        if ($chk->fetch()) $error = 'Cet email est déjà utilisé.';
    }

    // Photo upload
    if (!$error && !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 mise à jour.');
                header('Location: profile.php'); exit;
            }
        }
    }

    // Suppression photo
    if (!$error && !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;
    }

    if (!$error) {
        // Mettre à jour l'utilisateur
        $pdo->prepare("UPDATE users SET name=?, email=?, gender=?, birth_date=? WHERE id=?")
            ->execute([$name, $email, $gender, $birth_date ?: null, $userId]);
        $_SESSION['user_name'] = $name;

        // Synchroniser la table métier
        if ($myRole === 'school_admin') {
            $pdo->prepare("UPDATE directors SET first_name=?, last_name=?, email=?, gender=? WHERE user_id=?")
                ->execute([$name, '', $email, $gender === 'M' ? 'M' : ($gender === 'F' ? 'F' : null), $userId]);
        } elseif ($myRole === 'teacher') {
            $pdo->prepare("UPDATE teachers SET first_name=?, last_name=?, email=?, gender=?, birth_date=? WHERE user_id=?")
                ->execute([$name, '', $email, $gender === 'M' ? 'M' : ($gender === 'F' ? 'F' : null), $birth_date ?: null, $userId]);
        }

        // Changer mot de passe si demandé
        if (!empty($currentPwd) || !empty($newPwd)) {
            $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=?, name=?, email=?, gender=?, birth_date=? WHERE id=?")
                    ->execute([$hash, null, $name, $email, $gender, $birth_date ?: null, $userId]);
                $phone = getUserPhone($pdo, $userId, $myRole);
                if ($phone) {
                    sendWhatsApp($phone, "Bonjour $name, votre mot de passe Nukunu Mofiala a été modifié. Nouveau mot de passe : $newPwd");
                }
                flashMessage('success', 'Profil et mot de passe mis à jour.');
                header('Location: profile.php'); exit;
            }
        }

        if (!$error) {
            flashMessage('success', 'Profil mis à jour.');
            header('Location: profile.php'); exit;
        }
    }
}

// ── Données ──────────────────────────────────────────────────────────────────
$stmt = $pdo->prepare("SELECT u.*, s.name AS school_name, s.logo AS school_logo
    FROM users u LEFT JOIN schools s ON u.school_id=s.id WHERE u.id=?");
$stmt->execute([$userId]);
$user = $stmt->fetch();
if (!$user) { flashMessage('error', 'Utilisateur introuvable.'); header('Location: dashboard.php'); exit; }

// Données métier liées
$meta = null;
if ($myRole === 'school_admin') {
    $stmt = $pdo->prepare("SELECT * FROM directors WHERE user_id=?");
    $stmt->execute([$userId]);
    $meta = $stmt->fetch();
} elseif ($myRole === 'teacher') {
    $stmt = $pdo->prepare("SELECT * FROM teachers WHERE user_id=?");
    $stmt->execute([$userId]);
    $meta = $stmt->fetch();
}
?><!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="../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/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-user-circle"></i> Mon profil'; include '../includes/topbar.php'; ?>
        <?= showFlash() ?>
        <?php if ($error): ?><div class="error-message"><?= e($error) ?></div><?php endif; ?>

        <form method="POST" enctype="multipart/form-data" class="card" style="max-width:720px;">
            <?= csrfField() ?>
            <div class="card-header"><span class="card-title"><i class="fas fa-id-card"></i> Mes informations</span></div>
            <div style="display:flex;align-items:center;gap:1rem;margin:1rem 0 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>

            <div style="display:flex;align-items:center;gap:.75rem;flex-wrap:wrap;margin-bottom:1rem;">
                <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;display:block;margin-bottom:1rem;">Max 2 Mo — JPEG, PNG, GIF, WebP</small>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
                <div class="form-group">
                    <label>Nom complet <span style="color:red">*</span></label>
                    <input type="text" name="name" required value="<?= e($user['name']) ?>">
                </div>
                <div class="form-group">
                    <label>Email <span style="color:red">*</span></label>
                    <input type="email" name="email" required value="<?= e($user['email']) ?>">
                </div>
                <div class="form-group">
                    <label>Date de naissance</label>
                    <input type="date" name="birth_date" value="<?= e($user['birth_date'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Genre</label>
                    <div style="display:flex;gap:1rem;padding-top:.3rem;">
                        <label><input type="radio" name="gender" value="M" <?= $user['gender'] === 'M' ? 'checked' : '' ?>> Masculin</label>
                        <label><input type="radio" name="gender" value="F" <?= $user['gender'] === 'F' ? 'checked' : '' ?>> Féminin</label>
                        <label><input type="radio" name="gender" value="Autre" <?= $user['gender'] === 'Autre' ? 'checked' : '' ?>> Autre</label>
                    </div>
                </div>
            </div>

            <?php if ($meta): ?>
            <hr style="margin:1.5rem 0;border:none;border-top:1px solid #e2e8f0;">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
                <?php if (!empty($meta['diploma'])): ?>
                <div><span style="color:#718096;font-size:.85rem;">Diplôme</span><div style="font-weight:600;"><?= e($meta['diploma']) ?></div></div>
                <?php endif; ?>
                <?php if (!empty($meta['phone'])): ?>
                <div><span style="color:#718096;font-size:.85rem;">Téléphone</span><div style="font-weight:600;"><?= e($meta['phone']) ?></div></div>
                <?php endif; ?>
                <?php if (!empty($meta['subject'])): ?>
                <div><span style="color:#718096;font-size:.85rem;">Matière</span><div style="font-weight:600;"><?= e($meta['subject']) ?></div></div>
                <?php endif; ?>
                <?php if (!empty($meta['start_date'])): ?>
                <div><span style="color:#718096;font-size:.85rem;">Prise de fonction</span><div style="font-weight:600;"><?= formatDate($meta['start_date']) ?></div></div>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <hr style="margin:1.5rem 0;border:none;border-top:1px solid #e2e8f0;">
            <h4 style="margin-bottom:1rem;"><i class="fas fa-lock"></i> Changer le mot de passe</h4>
            <p style="color:#718096;font-size:.85rem;margin-bottom:1rem;">Laissez vide pour conserver le mot de passe actuel.</p>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:1rem;">
                <div class="form-group">
                    <label>Mot de passe actuel</label>
                    <input type="password" name="current_password" autocomplete="current-password">
                </div>
                <div class="form-group">
                    <label>Nouveau mot de passe</label>
                    <input type="password" name="new_password" minlength="12" placeholder="Min. 12 caractères" autocomplete="new-password">
                </div>
                <div class="form-group">
                    <label>Confirmer</label>
                    <input type="password" name="confirm_password" autocomplete="new-password">
                </div>
            </div>

            <div style="margin-top:1.5rem;">
                <button type="submit" class="btn-submit"><i class="fas fa-save"></i> Enregistrer</button>
            </div>
        </form>
    </div>
</div>
</body>
</html>
