<?php
declare(strict_types=1);

session_start();
require_once __DIR__ . '/../../includes/db_connect.php';

if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'] ?? '', ['admin','teacher'], true)) {
    header("Location: ../../index.php");
    exit();
}

$role  = (string)($_SESSION['role'] ?? '');
$my_id = (int)($_SESSION['user_id'] ?? 0);

function h(?string $s): string { return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

function safe_subject_folder(string $name): string {
    $name = trim($name);
    if ($name === '') return 'subject';
    $conv = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $name);
    if ($conv === false || $conv === '') $conv = $name;
    $conv = preg_replace('~[^A-Za-z0-9_\-]+~', '_', $conv);
    $conv = preg_replace('~_+~', '_', $conv);
    $conv = trim($conv, '_');
    return $conv !== '' ? $conv : 'subject';
}

function is_post(): bool { return (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST'); }

function load_mail_config(): array {
    $cfgPath = realpath(__DIR__ . '/../../includes/config_mail.php');
    if (!$cfgPath || !file_exists($cfgPath)) return [];
    $cfg = require $cfgPath;
    return is_array($cfg) ? $cfg : [];
}

function mailer_make(): \PHPMailer\PHPMailer\PHPMailer {
    require_once __DIR__ . '/../../includes/PHPMailer/src/PHPMailer.php';
    require_once __DIR__ . '/../../includes/PHPMailer/src/SMTP.php';
    require_once __DIR__ . '/../../includes/PHPMailer/src/Exception.php';
    return new \PHPMailer\PHPMailer\PHPMailer(true);
}

function send_one_mail(array $cfg, string $toEmail, string $toName, string $subject, string $html, string $alt, array $attachmentsAbs): bool {
    try {
        $mail = mailer_make();
        $mail->CharSet = 'UTF-8';
        $mail->isSMTP();
        $mail->Host     = (string)($cfg['host'] ?? '');
        $mail->SMTPAuth = true;
        $mail->Username = (string)($cfg['username'] ?? '');
        $mail->Password = (string)($cfg['password'] ?? '');
        $enc = strtolower((string)($cfg['encryption'] ?? 'tls'));
        if ($enc === 'ssl') {
            $mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
        } else {
            $mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        }
        $mail->Port = (int)($cfg['port'] ?? 587);

        $mail->setFrom((string)($cfg['from_email'] ?? ''), (string)($cfg['from_name'] ?? 'Електронний журнал'));
        $mail->addAddress($toEmail, $toName);

        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $html;
        $mail->AltBody = $alt;

        foreach ($attachmentsAbs as $abs) {
            if (is_string($abs) && $abs !== '' && file_exists($abs)) {
                $mail->addAttachment($abs);
            }
        }

        $mail->send();
        return true;
    } catch (\Throwable $e) {
        error_log('dz mail send failed: '.$e->getMessage());
        return false;
    }
}

/* ===== Групи для вибору ===== */
$groups = [];
if ($role === 'admin') {
    $q = $conn->query("SELECT id, group_name FROM `groups` ORDER BY group_name ASC");
    if ($q) {
        while ($r = $q->fetch_assoc()) $groups[] = $r;
        $q->free();
    }
} else {
    // teacher: тільки групи, де він читає хоч 1 предмет
    $st = $conn->prepare("
        SELECT DISTINCT g.id, g.group_name
        FROM subjects s
        JOIN `groups` g ON g.id = s.group_id
        WHERE s.teacher_id = ?
        ORDER BY g.group_name ASC
    ");
    if ($st) {
        $st->bind_param('i', $my_id);
        $st->execute();
        $res = $st->get_result();
        while ($r = $res->fetch_assoc()) $groups[] = $r;
        $st->close();
    }
}

/* ===== Поточні значення ===== */
$group_id   = (int)($_GET['group_id'] ?? ($_POST['group_id'] ?? 0));
$subject_id = (int)($_GET['subject_id'] ?? ($_POST['subject_id'] ?? 0));

/* ===== Предмети по групі ===== */
$subjects = [];
$group_ok = false;
foreach ($groups as $g) {
    if ((int)$g['id'] === $group_id) { $group_ok = true; break; }
}
if ($group_id > 0 && ($role === 'admin' || $group_ok)) {
    if ($role === 'admin') {
        $st = $conn->prepare("
            SELECT s.id AS subject_id, s.subject_name, s.teacher_id
            FROM subjects s
            WHERE s.group_id = ?
            ORDER BY s.subject_name ASC
        ");
        if ($st) {
            $st->bind_param('i', $group_id);
            $st->execute();
            $res = $st->get_result();
            while ($r = $res->fetch_assoc()) $subjects[] = $r;
            $st->close();
        }
    } else {
        $st = $conn->prepare("
            SELECT s.id AS subject_id, s.subject_name, s.teacher_id
            FROM subjects s
            WHERE s.group_id = ? AND s.teacher_id = ?
            ORDER BY s.subject_name ASC
        ");
        if ($st) {
            $st->bind_param('ii', $group_id, $my_id);
            $st->execute();
            $res = $st->get_result();
            while ($r = $res->fetch_assoc()) $subjects[] = $r;
            $st->close();
        }
    }
}

/* ===== Відправка ===== */
$info = '';
$err  = '';

if (is_post()) {
    // базові перевірки доступу
    if ($group_id <= 0 || $subject_id <= 0) {
        $err = 'Оберіть групу та предмет.';
    } else {
        if ($role === 'teacher') {
            $allowed = false;
            foreach ($subjects as $s) {
                if ((int)$s['subject_id'] === $subject_id) { $allowed = true; break; }
            }
            if (!$allowed) $err = 'Недостатньо прав для цього предмета/групи.';
        }
    }

    $body = trim((string)($_POST['body'] ?? ''));
    if ($err === '' && $body === '') $err = 'Текст завдання не може бути порожнім.';

    $due_date = trim((string)($_POST['due_date'] ?? ''));
    if ($due_date !== '' && !preg_match('~^\d{4}-\d{2}-\d{2}$~', $due_date)) {
        $due_date = '';
    }

    // лінки
    $links_in = $_POST['links'] ?? [];
    if (!is_array($links_in)) $links_in = [];
    $links = [];
    foreach ($links_in as $u) {
        $u = trim((string)$u);
        if ($u === '') continue;
        if (!preg_match('~^https?://~i', $u)) $u = 'https://' . $u;
        if (filter_var($u, FILTER_VALIDATE_URL)) $links[] = $u;
    }

    // дістаємо назви
    $group_name = '';
    foreach ($groups as $g) if ((int)$g['id'] === $group_id) { $group_name = (string)$g['group_name']; break; }

    $subject_name = '';
    foreach ($subjects as $s) if ((int)$s['subject_id'] === $subject_id) { $subject_name = (string)$s['subject_name']; break; }

    if ($err === '' && $subject_name === '') $err = 'Предмет не знайдено.';
    if ($err === '' && $group_name === '') $err = 'Групу не знайдено.';

    // файли
    $maxFile = 25 * 1024 * 1024;
    $allowedExt = ['pdf','ppt','pptx','doc','docx','xls','xlsx'];

    $savedFiles = []; // [ [web, abs, orig, size, mime], ... ]
    if ($err === '' && isset($_FILES['files']) && is_array($_FILES['files']['name'] ?? null)) {
        $baseRoot = realpath(__DIR__ . '/../../');
        $uploadsRootAbs = $baseRoot ? ($baseRoot . '/uploads') : '';
        if ($uploadsRootAbs === '' || !is_dir($uploadsRootAbs)) {
            $err = 'Не знайдено папку uploads на сервері.';
        } else {
            $today = date('Y-m-d');
            $subFolder = safe_subject_folder($subject_name);

            $targetAbs = $uploadsRootAbs . '/' . $group_id . '/' . $subFolder . '/' . $today;
            if (!is_dir($targetAbs)) {
                @mkdir($targetAbs, 0775, true);
            }
            if (!is_dir($targetAbs)) {
                $err = 'Не вдалося створити папку для файлів.';
            } else {
                $names = $_FILES['files']['name'];
                $tmps  = $_FILES['files']['tmp_name'];
                $errs  = $_FILES['files']['error'];
                $sizes = $_FILES['files']['size'];

                for ($i=0; $i<count($names); $i++) {
                    $orig = (string)$names[$i];
                    $tmp  = (string)$tmps[$i];
                    $e    = (int)$errs[$i];
                    $sz   = (int)$sizes[$i];

                    if ($orig === '' && $tmp === '') continue;
                    if ($e === UPLOAD_ERR_NO_FILE) continue;

                    if ($e !== UPLOAD_ERR_OK) { $err = 'Помилка завантаження файлу.'; break; }
                    if ($sz <= 0 || $sz > $maxFile) { $err = 'Файл більше 25MB або порожній.'; break; }

                    $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
                    if (!in_array($ext, $allowedExt, true)) { $err = 'Дозволені файли: pdf, ppt/pptx, doc/docx, xls/xlsx.'; break; }

                    $safeBase = preg_replace('~[^A-Za-z0-9_\-]+~', '_', pathinfo($orig, PATHINFO_FILENAME));
                    $safeBase = trim(preg_replace('~_+~', '_', $safeBase), '_');
                    if ($safeBase === '') $safeBase = 'file';

                    $final = $safeBase . '_' . date('His') . '_' . bin2hex(random_bytes(3)) . '.' . $ext;
                    $abs = $targetAbs . '/' . $final;

                    if (!@move_uploaded_file($tmp, $abs)) { $err = 'Не вдалося зберегти файл.'; break; }

                    $mime = '';
                    if (function_exists('mime_content_type')) {
                        $mime = (string)@mime_content_type($abs);
                    }

                    $web = '/uploads/' . $group_id . '/' . $subFolder . '/' . $today . '/' . $final;
                    $savedFiles[] = [$web, $abs, $orig, $sz, $mime];
                }
            }
        }
    }

    if ($err === '') {
        // запис у БД
        $st = $conn->prepare("INSERT INTO homework_tasks (group_id, subject_id, teacher_id, body, due_date, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
        if (!$st) {
            $err = 'DB помилка (insert homework_tasks).';
        } else {
            $dueParam = ($due_date !== '') ? $due_date : null;
            $st->bind_param('iiiss', $group_id, $subject_id, $my_id, $body, $dueParam);
            if (!$st->execute()) {
                $err = 'DB помилка (execute homework_tasks).';
            }
            $task_id = (int)$st->insert_id;
            $st->close();

            if ($err === '' && $task_id > 0) {
                // links
                if (!empty($links)) {
                    $ins = $conn->prepare("INSERT INTO homework_links (task_id, url, title, sort_order) VALUES (?, ?, NULL, ?)");
                    if ($ins) {
                        $k = 0;
                        foreach ($links as $u) {
                            $k++;
                            $ins->bind_param('isi', $task_id, $u, $k);
                            $ins->execute();
                        }
                        $ins->close();
                    }
                }

                // files
                if (!empty($savedFiles)) {
                    $insf = $conn->prepare("INSERT INTO homework_files (task_id, file_path, original_name, file_size, mime, uploaded_at) VALUES (?, ?, ?, ?, ?, NOW())");
                    if ($insf) {
                        foreach ($savedFiles as $f) {
                            [$web, $abs, $orig, $sz, $mime] = $f;
                            $insf->bind_param('issis', $task_id, $web, $orig, $sz, $mime);
                            $insf->execute();
                        }
                        $insf->close();
                    }
                }

                // recipients: students of group
                $recipients = [];
                $stR = $conn->prepare("SELECT email, full_name FROM users WHERE role='student' AND group_id=? AND active=1 AND email<>'' ORDER BY full_name ASC");
                if ($stR) {
                    $stR->bind_param('i', $group_id);
                    $stR->execute();
                    $res = $stR->get_result();
                    while ($r = $res->fetch_assoc()) {
                        $em = trim((string)($r['email'] ?? ''));
                        if ($em !== '' && filter_var($em, FILTER_VALIDATE_EMAIL)) {
                            $recipients[] = ['email'=>$em, 'name'=>(string)($r['full_name'] ?? '')];
                        }
                    }
                    $stR->close();
                }

                // email
                $cfg = load_mail_config();
                if (empty($cfg['host']) || empty($cfg['username']) || empty($cfg['password']) || empty($cfg['from_email'])) {
                    $err = 'Пошта не налаштована (config_mail.php).';
                } else {
                    $createdHuman = date('d.m.Y');
                    $dueHuman = ($due_date !== '') ? date('d.m.Y', strtotime($due_date)) : '';

                    $subjectMail = "Домашнє завдання: {$subject_name} ({$group_name})";
                    $dueLine = $dueHuman !== ''
                        ? '<div style="margin:10px 0 0; font-weight:900; color:#b91c1c;">Виконати до: <span style="font-weight:900; color:#b91c1c;">'.$dueHuman.'</span></div>'
                        : '';

                    $linksHtml = '';
                    if (!empty($links)) {
                        $linksHtml .= '<div style="margin:12px 0 0; font-weight:900;">Посилання:</div><ul style="margin:6px 0 0; padding-left:18px;">';
                        foreach ($links as $u) {
                            $uu = h($u);
                            $linksHtml .= '<li style="margin:6px 0;"><a href="'.$uu.'" target="_blank" rel="noopener noreferrer">'.$uu.'</a></li>';
                        }
                        $linksHtml .= '</ul>';
                    }

                    $filesHtml = '';
                    if (!empty($savedFiles)) {
                        $filesHtml .= '<div style="margin:12px 0 0; font-weight:900;">Файли:</div><ul style="margin:6px 0 0; padding-left:18px;">';
                        foreach ($savedFiles as $f) {
                            $filesHtml .= '<li style="margin:6px 0;">'.h((string)$f[2]).'</li>';
                        }
                        $filesHtml .= '</ul>';
                    }

                    $html = ''
                      . '<div style="font-family:Arial, sans-serif; font-size:14px; color:#111;">'
                      . '<div style="font-size:16px; font-weight:900; color:#432755;">Домашнє завдання</div>'
                      . '<div style="margin-top:6px;"><b>Предмет:</b> '.h($subject_name).'</div>'
                      . '<div><b>Група:</b> '.h($group_name).'</div>'
                      . '<div><b>Дата:</b> '.$createdHuman.'</div>'
                      . $dueLine
                      . '<hr style="margin:12px 0; border:none; border-top:1px solid #e5e7eb;">'
                      . '<div style="white-space:pre-line;">'.nl2br(h($body)).'</div>'
                      . $linksHtml
                      . $filesHtml
                      . '<hr style="margin:12px 0; border:none; border-top:1px solid #e5e7eb;">'
                      . '<div style="font-size:12px; color:#6b7280;">Електронний журнал</div>'
                      . '</div>';

                    $alt = "Домашнє завдання\nПредмет: {$subject_name}\nГрупа: {$group_name}\nДата: {$createdHuman}\n"
                         . ($dueHuman !== '' ? "Виконати до: {$dueHuman}\n" : "")
                         . "\n{$body}\n"
                         . (!empty($links) ? ("\nПосилання:\n- ".implode("\n- ", $links)."\n") : '');

                    $attachmentsAbs = array_map(static fn($x) => (string)$x[1], $savedFiles);

                    $sent = 0; $fail = 0;
                    foreach ($recipients as $rc) {
                        $ok = send_one_mail($cfg, (string)$rc['email'], (string)$rc['name'], $subjectMail, $html, $alt, $attachmentsAbs);
                        if ($ok) $sent++; else $fail++;
                    }

                    $info = "Збережено. Листи: надіслано {$sent}, помилки {$fail}.";
                    // очистка форми
                    $_POST = [];
                }
            } else {
                $err = 'Не вдалося створити завдання.';
            }
        }
    }

    if ($err !== '' && !empty($savedFiles)) {
        // якщо помилка — чистимо вже завантажені файли
        foreach ($savedFiles as $f) {
            $abs = (string)$f[1];
            if ($abs && file_exists($abs)) @unlink($abs);
        }
    }
}

$header_title = 'Домашнє завдання (адмін)';

$current_file = basename($_SERVER['PHP_SELF'] ?? 'index.php');
?>
<!DOCTYPE html>
<html lang="uk">
<head>
    <meta charset="UTF-8">
    <meta name="robots" content="noindex, nofollow">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= h($header_title) ?></title>
    <link rel="stylesheet" href="/assets/css/style.css">
    <style>
        :root{
            --brand-mint:#a3e8d3;
            --brand-mint-2:#92dec7;
            --brand-purple:#432755;
            --brand-purple-2:#3a244d;

            --ink:#1f2937;
            --muted:#4b5563;
            --bg:#f6f7fb;
            --card:#ffffff;
            --shadow: 0 10px 24px rgba(0,0,0,.08);
            --border: rgba(0,0,0,.10);
            --focus: rgba(67,39,85,.25);
            --danger:#b91c1c;
            --ok:#065f46;
        }
        *{box-sizing:border-box}
        body{margin:0;background:var(--bg);color:var(--ink);font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,"Helvetica Neue",Arial,sans-serif;}
        .wrap{max-width:1000px;margin:16px auto;padding:16px;}
        .card{background:var(--card);border:1px solid var(--border);border-radius:16px;box-shadow:var(--shadow);padding:18px;}
        h1{margin:0 0 10px;color:var(--brand-purple);font-size:22px;font-weight:1000;}
        label{display:block;margin:10px 0 6px;font-weight:900;color:var(--brand-purple);font-size:14px;}
        select,input[type="date"],textarea{
            width:100%;
            padding:12px;
            border:1px solid rgba(0,0,0,.14);
            border-radius:12px;
            font-size:15px;
            outline:none;
            background:#fff;
        }
        textarea{min-height:140px;resize:vertical;}
        select:focus,input:focus,textarea:focus{border-color:rgba(67,39,85,.35);box-shadow:0 0 0 4px var(--focus);}
        .row{display:grid;grid-template-columns: 1fr 1fr;gap:12px;}
        @media (max-width:720px){.row{grid-template-columns:1fr}}

        .msg{margin:12px 0 0;padding:12px 14px;border-radius:14px;font-weight:900;border:1px solid rgba(0,0,0,.10);}
        .msg.ok{background:rgba(6,95,70,.10);border-color:rgba(6,95,70,.22);color:var(--ok);}
        .msg.err{background:rgba(185,28,28,.08);border-color:rgba(185,28,28,.22);color:var(--danger);}
        .btn{
            display:inline-flex;align-items:center;justify-content:center;gap:8px;
            padding:12px 16px;border-radius:999px;border:1px solid rgba(255,255,255,.18);
            background:linear-gradient(180deg,var(--brand-purple),var(--brand-purple-2));
            color:#fff;text-decoration:none;font-weight:1000;cursor:pointer;
            box-shadow: 0 10px 18px rgba(67,39,85,.16);
        }
        .btn:active{transform:translateY(1px)}
        .btn.secondary{background:#fff;color:var(--brand-purple);border-color:rgba(67,39,85,.22);box-shadow: 0 10px 18px rgba(0,0,0,.08);}
        .btn.small{padding:10px 12px;font-size:13px}

        .fieldlist{display:flex;flex-direction:column;gap:8px;}

        /* ===== FIX mobile overflow: row stacks on narrow screens; prevent button from pushing outside ===== */
        .fieldrow{
            display:flex;
            gap:8px;
            align-items:stretch;
            flex-wrap:wrap;
        }
        .fieldrow input[type="text"],
        .fieldrow input[type="file"]{
            flex: 1 1 260px;
            min-width: 0;
        }
        .fieldrow .btn{
            flex: 0 0 auto;
            white-space: nowrap;
        }

        @media (max-width:520px){
            .fieldrow input[type="text"],
            .fieldrow input[type="file"]{
                flex: 1 1 100%;
                width: 100%;
            }
            .fieldrow .btn{
                width: 100%;
                justify-content:center;
            }
        }

        .hint{color:var(--muted);font-weight:700;font-size:13px;margin-top:6px}
        .duehint{color:#b91c1c;font-weight:1000}

        /* ===== Tabs (як у admin/dashboard.php) ===== */
        .admin-tabs{
            display:flex;
            gap:10px;
            flex-wrap:wrap;
            align-items:center;
            margin: 2px 0 14px;
        }
        .admin-tabs a{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            gap:8px;
            padding:10px 14px;
            border-radius:999px;
            text-decoration:none;
            font-weight:900;
            font-size:14px;
            color: var(--ink);
            background: rgba(67,40,85,.08);
            border: 1px solid rgba(67,40,85,.18);
            box-shadow: 0 10px 22px rgba(67,40,85,.08);
            transition: transform .08s ease, box-shadow .12s ease, background .12s ease, border-color .12s ease;
        }
        .admin-tabs a:hover{
            transform: translateY(-1px);
            background: rgba(163,232,211,.45);
            border-color: rgba(67,40,85,.22);
            box-shadow: 0 14px 28px rgba(67,40,85,.10);
        }
        .admin-tabs a.active{
            color:#fff;
            background: linear-gradient(135deg, var(--brand-purple) 0%, #4b2a61 55%, rgba(163,232,211,.95) 120%);
            border-color: rgba(255,255,255,.22);
            box-shadow: 0 18px 40px rgba(67,40,85,.18);
        }
    </style>
</head>
<body>

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

<main class="wrap">

    <?php
    $tabs = [
        ['href' => '/admin/dashboard.php',        'label' => 'Журнали'],
        ['href' => '/journal/group_journal.php',   'label' => 'Управління журналами'],
        ['href' => '/admin/dz/index.php',         'label' => 'Домашнє завдання'],
        ['href' => '/admin/admin_students.php',   'label' => 'Учні'],
        ['href' => '/admin/admin_father.php',     'label' => 'Батьки'],
        ['href' => '/admin/admin_teachers.php',   'label' => 'Вчителі'],
        ['href' => '/admin/admin_system.php',     'label' => 'Система'],
    ];
    ?>
    <nav class="admin-tabs" aria-label="Адмін навігація">
        <?php foreach ($tabs as $t):
            $href = (string)($t['href'] ?? '');
            $label = (string)($t['label'] ?? '');
            $active = (basename(parse_url($href, PHP_URL_PATH) ?? '') === $current_file) ? 'active' : '';
        ?>
            <a class="<?= h($active) ?>" href="<?= h($href) ?>"><?= h($label) ?></a>
        <?php endforeach; ?>
    </nav>

    <section class="card">
        <h1>Домашнє завдання — створити та відправити</h1>

        <?php if ($info !== ''): ?><div class="msg ok"><?= h($info) ?></div><?php endif; ?>
        <?php if ($err  !== ''): ?><div class="msg err"><?= h($err) ?></div><?php endif; ?>

        <form method="post" enctype="multipart/form-data">
            <div class="row">
                <div>
                    <label>Група</label>
                    <select name="group_id" onchange="window.location='?group_id='+this.value">
                        <option value="0">— оберіть групу —</option>
                        <?php foreach ($groups as $g): ?>
                            <option value="<?= (int)$g['id'] ?>" <?= ((int)$g['id']===$group_id?'selected':'') ?>>
                                <?= h((string)$g['group_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label>Предмет</label>
                    <select name="subject_id" <?= ($group_id<=0?'disabled':'') ?>>
                        <option value="0">— оберіть предмет —</option>
                        <?php foreach ($subjects as $s): ?>
                            <option value="<?= (int)$s['subject_id'] ?>" <?= ((int)$s['subject_id']===$subject_id?'selected':'') ?>>
                                <?= h((string)$s['subject_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <label>Текст завдання</label>
            <textarea name="body" placeholder="Введіть домашнє завдання..."><?= h((string)($_POST['body'] ?? '')) ?></textarea>

            <label>Посилання (можна додавати/видаляти)</label>
            <div class="fieldlist" id="linksBox">
                <div class="fieldrow">
                    <input type="text" name="links[]" placeholder="https://..." value="">
                    <button class="btn secondary small" type="button" onclick="removeRow(this)">Видалити</button>
                </div>
            </div>
            <button class="btn secondary small" type="button" onclick="addLink()">+ Додати посилання</button>

            <label>Файли (до 25MB кожен)</label>
            <div class="fieldlist" id="filesBox">
                <div class="fieldrow">
                    <input type="file" name="files[]">
                    <button class="btn secondary small" type="button" onclick="removeRow(this)">Видалити</button>
                </div>
            </div>
            <button class="btn secondary small" type="button" onclick="addFile()">+ Додати файл</button>
            <div class="hint">Дозволено: pdf, ppt/pptx, doc/docx, xls/xlsx</div>

            <label>Виконати до (в листі буде жирним червоним)</label>
            <input type="date" name="due_date" value="<?= h((string)($_POST['due_date'] ?? '')) ?>">
            <div class="hint duehint">Цей рядок піде в лист червоним.</div>

            <div style="margin-top:14px; display:flex; gap:10px; flex-wrap:wrap;">
                <button class="btn" type="submit">Відправити</button>
                <a class="btn secondary" href="/dz/dz.php">Перегляд (як користувач)</a>
            </div>
        </form>
    </section>
</main>

<script>
function removeRow(btn){
  const row = btn.closest('.fieldrow');
  if (!row) return;
  const box = row.parentElement;
  row.remove();
  if (box && box.querySelectorAll('.fieldrow').length === 0) {
    // залишаємо хоча б 1 рядок
    if (box.id === 'linksBox') addLink();
    if (box.id === 'filesBox') addFile();
  }
}
function addLink(){
  const box = document.getElementById('linksBox');
  const div = document.createElement('div');
  div.className = 'fieldrow';
  div.innerHTML = '<input type="text" name="links[]" placeholder="https://..." value="">' +
                  '<button class="btn secondary small" type="button" onclick="removeRow(this)">Видалити</button>';
  box.appendChild(div);
}
function addFile(){
  const box = document.getElementById('filesBox');
  const div = document.createElement('div');
  div.className = 'fieldrow';
  div.innerHTML = '<input type="file" name="files[]">' +
                  '<button class="btn secondary small" type="button" onclick="removeRow(this)">Видалити</button>';
  box.appendChild(div);
}
</script>

</body>
</html>