<?php
/**
 * Comptes parents — liste, création, activation, liaison d'enfants
 */
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']);
requirePermission('users', 'view');

$schoolFilter = currentSchoolId();
if (isSuperAdmin() && !empty($_GET['school_id'])) {
    $schoolFilter = (int)$_GET['school_id'];
}

$action = $_GET['action'] ?? 'list';
$id     = isset($_GET['id']) ? (int)$_GET['id'] : null;
$error  = '';

$schools = $pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll();

// Élèves disponibles pour la liaison (restreints à l'école filtrée)
$studentsForLink = [];
if ($schoolFilter) {
    $sl = $pdo->prepare("SELECT id, first_name, last_name, class_id FROM students WHERE school_id=? ORDER BY last_name, first_name");
    $sl->execute([$schoolFilter]);
    $studentsForLink = $sl->fetchAll();
} else {
    $studentsForLink = $pdo->query("SELECT id, first_name, last_name, class_id FROM students ORDER BY last_name, first_name")->fetchAll();
}

// ── Toggle activation ─────────────────────────────────────────────────────────
if ($action === 'toggle_active' && $id) {
    verifyCsrf();
    requirePermission('users','edit');
    if ($id === (int)$_SESSION['user_id']) {
        flashMessage('error','Vous ne pouvez pas désactiver votre propre compte.');
        header('Location: parent_accounts.php'); exit;
    }
    $pdo->prepare("UPDATE users SET active = NOT active WHERE id=? AND role='parent'")->execute([$id]);
    flashMessage('success','Statut du compte mis à jour.');
    header('Location: parent_accounts.php'); exit;
}

// ── Retrait d'un enfant ───────────────────────────────────────────────────────
if ($action === 'remove_child' && $id) {
    verifyCsrf();
    $parentId = (int)($_POST['parent_id'] ?? 0);
    if ($schoolFilter) {
        $chk = $pdo->prepare("SELECT id FROM users WHERE id=? AND role='parent' AND school_id=?");
        $chk->execute([$parentId, $schoolFilter]);
        if (!$chk->fetch()) { flashMessage('error','Action non autorisée.'); header('Location: parent_accounts.php'); exit; }
    }
    $pdo->prepare("DELETE FROM parent_students WHERE user_id=? AND student_id=?")->execute([$parentId, $id]);
    flashMessage('success','Enfant retiré.');
    header("Location: parent_accounts.php?action=edit&id=$parentId"); exit;
}

// ── Création d'un compte parent ───────────────────────────────────────────────
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && ($action === 'add' || $action === 'save')) {
    verifyCsrf();
    requirePermission('users', $action === 'add' ? 'create' : 'edit');

    $name      = trim($_POST['name']  ?? '');
    $email     = trim($_POST['email'] ?? '');
    $school_id = !empty($_POST['school_id']) ? (int)$_POST['school_id'] : $schoolFilter;
    $password  = $_POST['password']   ?? '';
    $active    = isset($_POST['active']) ? 1 : 0;
    $autoGen   = isset($_POST['auto_generate']);
    $children  = isset($_POST['children']) ? array_map('intval', (array)$_POST['children']) : [];
    $generatedPassword = '';

    if ($autoGen && !$id) {
        $base = strtolower(trim(preg_replace('/[^a-zA-Z0-9]/', '.', $name), '.'));
        $base = preg_replace('/\.+/', '.', $base);
        $digits = str_pad(random_int(0, 99), 2, '0', STR_PAD_LEFT);
        $email  = $base . $digits . '@nukunu.edu';
        $password = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'), 0, 6)
                  . substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZ'), 0, 2)
                  . str_pad(random_int(0, 99), 2, '0', STR_PAD_LEFT)
                  . '@'
                  . substr(str_shuffle('abcdefghjkmnpqrstuvwxyz'), 0, 2);
        $generatedPassword = $password;
    }

    if (empty($name)) $error = 'Le nom est requis.';
    elseif (!$autoGen && !validateEmail($email)) $error = 'Adresse email invalide.';
    elseif (!$id && empty($password)) $error = 'Le mot de passe est requis.';
    elseif (!empty($password) && strlen($password) < 12) $error = 'Mot de passe : 12 caractères minimum.';
    elseif (!empty($password) && !preg_match('/[A-Z]/', $password)) $error = 'Le mot de passe doit contenir au moins une majuscule.';
    elseif (!empty($password) && !preg_match('/[0-9]/', $password)) $error = 'Le mot de passe doit contenir au moins un chiffre.';
    else {
        $chk = $pdo->prepare("SELECT id FROM users WHERE email=? AND id!=?");
        $chk->execute([$email, $id ?? 0]);
        if ($chk->fetch()) $error = 'Cette adresse email est déjà utilisée.';
        if (!$id) {
            $chk2 = $pdo->prepare("SELECT id FROM users WHERE LOWER(TRIM(name))=LOWER(TRIM(?)) AND role='parent' AND COALESCE(school_id,0)=COALESCE(?,0)");
            $chk2->execute([$name, $school_id]);
            if ($chk2->fetch()) $error = 'Un parent avec ce nom existe déjà dans cette école.';
        }
    }

    if (empty($error)) {
        if ($id) {
            if (!empty($password)) {
                $hash = password_hash($password, PASSWORD_BCRYPT, ['cost'=>BCRYPT_COST]);
                $pdo->prepare("UPDATE users SET name=?,email=?,school_id=?,active=?,password=?,plain_password=? WHERE id=? AND role='parent'")
                    ->execute([$name,$email,$school_id,$active,$hash,$password,$id]);
            } else {
                $pdo->prepare("UPDATE users SET name=?,email=?,school_id=?,active=? WHERE id=? AND role='parent'")
                    ->execute([$name,$email,$school_id,$active,$id]);
            }
            flashMessage('success','Compte parent mis à jour.');
        } else {
            $hash = password_hash($password, PASSWORD_BCRYPT, ['cost'=>BCRYPT_COST]);
            $pdo->prepare("INSERT INTO users (name,email,password,plain_password,role,school_id,active) VALUES (?,?,?,?,'parent',?,?)")
                ->execute([$name,$email,$hash,$password,$school_id,$active]);
            $newId = (int)$pdo->lastInsertId();
            $id = $newId;
            flashMessage('success', 'Compte parent créé : <strong>' . e($email) . '</strong>' . ($generatedPassword ? ' / Mot de passe : <strong>' . e($generatedPassword) . '</strong>' : ''));
        }
        // Liaison des enfants
        $pdo->prepare("DELETE FROM parent_students WHERE user_id=?")->execute([$id]);
        foreach ($children as $cid) {
            $pdo->prepare("INSERT IGNORE INTO parent_students (user_id, student_id) VALUES (?,?)")->execute([$id, $cid]);
        }
        header('Location: parent_accounts.php'); exit;
    }
}

// ── Chargement édition ────────────────────────────────────────────────────────
$parent = null;
$linkedChildren = [];
if ($action === 'edit' && $id) {
    $st = $pdo->prepare("SELECT * FROM users WHERE id=? AND role='parent'");
    $st->execute([$id]); $parent = $st->fetch();
    if (!$parent) { flashMessage('error','Parent introuvable.'); header('Location: parent_accounts.php'); exit; }
    $lc = $pdo->prepare("SELECT s.id, s.first_name, s.last_name, c.name AS class_name FROM parent_students ps JOIN students s ON ps.student_id=s.id LEFT JOIN classes c ON s.class_id=c.id WHERE ps.user_id=? ORDER BY s.last_name, s.first_name");
    $lc->execute([$id]); $linkedChildren = $lc->fetchAll();
}

// ── Recherche et liste ────────────────────────────────────────────────────────
$q = trim($_GET['q'] ?? '');
$searchWhere = '';
$searchParams = [];
if ($q !== '') {
    $searchWhere = 'AND (u.name LIKE ? OR u.email LIKE ?)';
    $like = '%' . $q . '%';
    $searchParams = [$like, $like];
}
$schoolWhere = '';
$schoolParams = [];
if ($schoolFilter) {
    $schoolWhere = 'AND u.school_id=?';
    $schoolParams = [$schoolFilter];
}

$parents = $pdo->prepare("
    SELECT u.id, u.name, u.email, u.school_id, u.active, u.created_at, u.photo, u.gender,
           s.name AS school_name,
           (SELECT COUNT(*) FROM parent_students ps2 WHERE ps2.user_id=u.id) AS child_count,
           (SELECT COUNT(*) FROM parent_students ps3 JOIN students st3 ON ps3.student_id=st3.id WHERE ps3.user_id=u.id AND st3.dropped_out IS NOT NULL) AS abandoned_count
    FROM users u
    LEFT JOIN schools s ON u.school_id=s.id
    WHERE u.role='parent' $schoolWhere $searchWhere
    ORDER BY u.name
");
$parents->execute(array_merge($schoolParams, $searchParams));
$parents = $parents->fetchAll();

$total = count($parents);
$activeCount = 0;
foreach ($parents as $p) if ($p['active']) $activeCount++;
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Comptes parents - 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">
    <style>
        .pa-toolbar { display:flex; justify-content:space-between; align-items:center; gap:1rem; flex-wrap:wrap; margin-bottom:1.25rem; }
        .pa-toolbar h1 { font-size:1.4rem; margin:0; color:#1a202c; }
        .pa-toolbar p { margin:0; color:#718096; font-size:.9rem; }
        .pa-actions { display:flex; gap:.5rem; flex-wrap:wrap; }
        .pa-summary { display:flex; gap:1rem; flex-wrap:wrap; margin-bottom:1.5rem; }
        .pa-summary span { padding:.45rem 1rem; border-radius:8px; background:#edf2f7; font-size:.85rem; }
        .pa-summary .ok { background:#c6f6d5; color:#22543d; }
        .child-tags { display:flex; flex-wrap:wrap; gap:.3rem; }
        .child-tag {
            display:inline-flex; align-items:center; gap:.4rem;
            background:#f3f4f6; color:#374151; padding:.2rem .6rem;
            border-radius:20px; font-size:.8rem; white-space:nowrap;
        }
        .child-tag .cls { color:#718096; font-size:.7rem; }
        .child-tag .abandoned { color:#dc2626; font-size:.7rem; }
        .child-tag form { display:inline; }
        .child-tag button { background:none;border:none;color:#dc2626;cursor:pointer;padding:0;font-size:.8rem; }
        .search-box { display:flex; gap:.5rem; align-items:center; }
        .search-box input { padding:.55rem .75rem; border:1px solid #d1d5db; border-radius:6px; font-size:.85rem; min-width:220px; }
        .modal-box { max-width:640px; }
        .checkbox-list { max-height:220px; overflow-y:auto; border:1px solid #e2e8f0; border-radius:8px; padding:.75rem; background:#fafbfc; }
        .checkbox-list label { display:flex; align-items:center; gap:.5rem; padding:.3rem .2rem; font-size:.85rem; cursor:pointer; }
        .checkbox-list input { accent-color:#667eea; }
        @media (max-width:768px) {
            .search-box input { min-width:100%; }
            .pa-toolbar { flex-direction:column; align-items:flex-start; }
        }
    </style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-user-friends"></i> Comptes parents'; include '../includes/topbar.php'; ?>
        <?= showFlash() ?>

        <div class="pa-toolbar">
            <div>
                <h1><i class="fas fa-user-friends"></i> Comptes parents</h1>
                <p>Créez et gérez les comptes parents, puis liez leurs enfants.</p>
            </div>
            <div class="pa-actions">
                <a href="?action=add" class="btn-action" style="background:#667eea;color:#fff;"><i class="fas fa-plus"></i> Nouveau parent</a>
            </div>
        </div>

        <div class="pa-summary">
            <span><strong><?= $total ?></strong> parent(s)</span>
            <span class="ok"><i class="fas fa-check-circle"></i> Comptes actifs : <?= $activeCount ?></span>
        </div>

        <!-- Filtres -->
        <div class="card no-print" style="margin-bottom:1.25rem;">
            <form method="GET" style="display:flex;gap:.75rem;flex-wrap:wrap;align-items:end;padding:.5rem 0;">
                <?php if (isSuperAdmin()): ?>
                <div class="form-group" style="margin:0;">
                    <label>École</label>
                    <select name="school_id" onchange="this.form.submit()">
                        <option value="">Toutes</option>
                        <?php foreach ($schools as $sc): ?>
                        <option value="<?= $sc['id'] ?>" <?= $schoolFilter==$sc['id']?'selected':'' ?>><?= e($sc['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="form-group search-box" style="margin:0;">
                    <label>Recherche</label>
                    <input type="text" name="q" value="<?= e($q) ?>" placeholder="Nom ou email...">
                </div>
                <button type="submit" class="btn-action btn-view"><i class="fas fa-search"></i> Filtrer</button>
                <?php if ($q !== '' || $schoolFilter): ?>
                <a href="parent_accounts.php" class="btn-action btn-view"><i class="fas fa-times"></i> Réinitialiser</a>
                <?php endif; ?>
            </form>
        </div>

        <?php if ($action === 'add' || $action === 'edit'): ?>
        <!-- ═══ Formulaire ═══ -->
        <div class="card">
            <div class="card-header">
                <span class="card-title"><i class="fas fa-<?= $parent ? 'edit' : 'plus-circle' ?>"></i> <?= $parent ? 'Modifier' : 'Nouveau' ?> compte parent</span>
            </div>
            <?php if ($error): ?>
            <div class="error-message" style="margin-bottom:1rem;"><?= e($error) ?></div>
            <?php endif; ?>
            <form method="POST" action="?action=<?= $id ? 'edit&id='.$id : 'add' ?>">
                <?= csrfField() ?>
                <div class="form-grid-2">
                    <div class="form-group">
                        <label>Nom complet <span style="color:#dc2626;">*</span></label>
                        <input type="text" name="name" required value="<?= e($parent['name'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="email" name="email" value="<?= e($parent['email'] ?? '') ?>" <?= !$parent && isset($_POST['auto_generate']) ? 'disabled' : '' ?>>
                        <small style="color:#718096;font-size:.75rem;">Laisser vide + « Générer » pour créer automatiquement.</small>
                    </div>
                </div>
                <?php if (isSuperAdmin()): ?>
                <div class="form-group">
                    <label>École</label>
                    <select name="school_id" <?= $schoolFilter ? 'disabled' : '' ?>>
                        <option value="">Toutes</option>
                        <?php foreach ($schools as $sc): ?>
                        <option value="<?= $sc['id'] ?>" <?= ($parent['school_id'] ?? $schoolFilter) == $sc['id'] ? 'selected' : '' ?>><?= e($sc['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php if ($schoolFilter): ?><input type="hidden" name="school_id" value="<?= $schoolFilter ?>"><?php endif; ?>
                </div>
                <?php else: ?>
                <input type="hidden" name="school_id" value="<?= $schoolFilter ?>">
                <?php endif; ?>
                <div class="form-grid-2">
                    <div class="form-group" style="position:relative;">
                        <label>Mot de passe <?= $id ? '<small style="color:#6b7280;">(laisser vide pour ne pas changer)</small>' : '<span style="color:#dc2626;">*</span>' ?></label>
                        <div style="display:flex;gap:.5rem;">
                            <input type="password" name="password" id="passwordField" <?= !$id ? 'required' : '' ?> minlength="12" placeholder="Min. 12 caractères" style="flex:1;">
                            <button type="button" class="btn-action btn-view" onclick="generatePassword()" title="Générer un mot de passe"><i class="fas fa-key"></i></button>
                        </div>
                    </div>
                    <div class="form-group">
                        <label style="display:inline-flex;align-items:center;gap:6px;cursor:pointer;font-weight:400 !important;font-size:.85rem !important;margin-top:1.6rem;">
                            <input type="checkbox" name="active" value="1" <?= ($parent['active'] ?? 1) ? 'checked' : '' ?>>
                            <span>Compte actif</span>
                        </label>
                    </div>
                </div>
                <?php if (!$id): ?>
                <div class="form-group">
                    <label style="display:inline-flex;align-items:center;gap:6px;cursor:pointer;font-weight:400 !important;font-size:.85rem !important;">
                        <input type="checkbox" name="auto_generate" value="1">
                        <strong>Générer email + mot de passe automatiquement</strong>
                    </label>
                </div>
                <?php endif; ?>
                <div class="form-group">
                    <label><i class="fas fa-child"></i> Enfants (élèves liés)</label>
                    <?php if (empty($studentsForLink)): ?>
                    <div style="color:#718096;font-size:.85rem;">Aucun élève disponible pour cette école.</div>
                    <?php else: ?>
                    <div class="checkbox-list">
                        <?php foreach ($studentsForLink as $st):
                            $checked = false;
                            foreach ($linkedChildren as $lc) if ($lc['id'] == $st['id']) { $checked = true; break; }
                        ?>
                        <label>
                            <input type="checkbox" name="children[]" value="<?= $st['id'] ?>" <?= $checked ? 'checked' : '' ?>>
                            <?= e($st['last_name'].' '.$st['first_name']) ?>
                        </label>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                    <small style="color:#718096;font-size:.75rem;">Cochez les élèves dont ce parent doit voir les notes, paiements et bulletins.</small>
                </div>
                <div style="display:flex;gap:.75rem;padding-top:.5rem;">
                    <button type="submit" class="btn-action" style="background:#667eea;color:#fff;"><i class="fas fa-save"></i> Enregistrer</button>
                    <a href="parent_accounts.php" class="btn-action btn-view">Annuler</a>
                </div>
            </form>
        </div>

        <?php else: ?>
        <!-- ═══ Liste ═══ -->
        <div class="card" style="padding:0;overflow:hidden;">
            <div class="data-table-wrapper">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Parent</th>
                        <th>Email</th>
                        <th>École</th>
                        <th>Enfants liés</th>
                        <th>Statut</th>
                        <th>Créé le</th>
                        <th style="width:120px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($parents)): ?>
                    <tr><td colspan="7" style="text-align:center;color:#9ca3af;padding:2.5rem;">Aucun compte parent trouvé.</td></tr>
                <?php else: foreach ($parents as $p): ?>
                    <tr class="<?= $p['active'] ? '' : 'user-inactive' ?>">
                        <td>
                            <div style="display:flex;align-items:center;gap:.6rem;">
                                <?= userPhotoImg($p['photo'] ?? null, $p['name'], 'small') ?>
                                <div>
                                    <strong><?= e($p['name']) ?></strong>
                                    <?php if ($p['gender'] === 'F'): ?><i class="fas fa-female" style="color:#d53f8c;font-size:.7rem;" title="Féminin"></i><?php elseif ($p['gender'] === 'M'): ?><i class="fas fa-male" style="color:#3182ce;font-size:.7rem;" title="Masculin"></i><?php endif; ?>
                                </div>
                            </div>
                        </td>
                        <td><?= e($p['email']) ?></td>
                        <td><span style="font-size:.82rem;color:#4a5568;"><?= e($p['school_name'] ?? '—') ?></span></td>
                        <td>
                            <?php
                            $children = $pdo->prepare("SELECT s.id, s.first_name, s.last_name, s.dropped_out, c.name AS class_name FROM parent_students ps JOIN students s ON ps.student_id=s.id LEFT JOIN classes c ON s.class_id=c.id WHERE ps.user_id=? ORDER BY s.last_name, s.first_name");
                            $children->execute([$p['id']]);
                            $kids = $children->fetchAll();
                            ?>
                            <?php if (empty($kids)): ?>
                            <span style="color:#9ca3af;">Aucun</span>
                            <?php else: ?>
                            <div class="child-tags">
                                <?php foreach ($kids as $k): ?>
                                <span class="child-tag">
                                    <?= e($k['last_name'].' '.$k['first_name']) ?>
                                    <?php if (!empty($k['class_name'])): ?><span class="cls"><?= e($k['class_name']) ?></span><?php endif; ?>
                                    <?php if (!empty($k['dropped_out'])): ?><span class="abandoned" title="En abandon"><i class="fas fa-user-slash"></i></span><?php endif; ?>
                                    <?php if (hasPermission('users','edit')): ?>
                                    <form method="POST" action="?action=remove_child&id=<?= $k['id'] ?>" onsubmit="return confirm('Retirer cet enfant ?')">
                                        <?= csrfField() ?>
                                        <input type="hidden" name="parent_id" value="<?= $p['id'] ?>">
                                        <button type="submit" title="Retirer"><i class="fas fa-times"></i></button>
                                    </form>
                                    <?php endif; ?>
                                </span>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($p['active']): ?>
                            <span class="status-badge status-active"><i class="fas fa-check-circle"></i> Actif</span>
                            <?php else: ?>
                            <span class="status-badge status-inactive"><i class="fas fa-ban"></i> Inactif</span>
                            <?php endif; ?>
                        </td>
                        <td><?= formatDate($p['created_at']) ?></td>
                        <td style="white-space:nowrap;">
                            <?php if (hasPermission('users','edit')): ?>
                            <a href="?action=edit&id=<?= $p['id'] ?>" class="btn-action btn-view" title="Modifier" style="padding:.35rem .6rem;font-size:.75rem;"><i class="fas fa-edit"></i></a>
                            <?php if ($p['id'] !== (int)$_SESSION['user_id']): ?>
                            <form method="POST" action="?action=toggle_active&id=<?= $p['id'] ?>" style="display:inline" title="<?= $p['active'] ? 'Désactiver' : 'Activer' ?>">
                                <?= csrfField() ?>
                                <button type="submit" class="btn-action btn-view" style="padding:.35rem .6rem;font-size:.75rem;">
                                    <i class="fas fa-<?= $p['active'] ? 'toggle-on' : 'toggle-off' ?>"></i>
                                </button>
                            </form>
                            <?php endif; ?>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>
<script src="../assets/js/main.js"></script>
<script>
function generatePassword() {
    var charset = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
    var pwd = '';
    for (var i = 0; i < 6; i++) pwd += charset[Math.floor(Math.random() * charset.length)];
    pwd += charset[Math.floor(Math.random() * 24)].toUpperCase();
    pwd += charset[Math.floor(Math.random() * 24)].toUpperCase();
    pwd += Math.floor(Math.random() * 100).toString().padStart(2, '0') + '@';
    for (var j = 0; j < 2; j++) pwd += 'abcdefghjkmnpqrstuvwxyz'[Math.floor(Math.random() * 23)];
    var f = document.getElementById('passwordField');
    if (f) { f.value = pwd; f.type = 'text'; }
}
</script>
</body>
</html>
