<?php
declare(strict_types = 1);
require dirname(__DIR__) . '/app/bootstrap.php';
$db = db();
$root = dirname(__DIR__);
$uploadDir = $root . '/storage/uploads';
$path = trim((string)($_GET['path'] ?? ''), '/');
$route = (string)($_GET['route'] ?? '');
if ($route === 'brand') {
    $key = (string)($_GET['key'] ?? '');
    if (!isset(cms_media_kinds()[$key])) { http_response_code(404); exit; }
    $filename = cms_media_file($db,$key);
    $full = $filename ? $root . '/storage/branding/' . $filename : '';
    if (!$filename || !is_file($full)) { http_response_code(404); exit; }
    header('Content-Type: ' . (str_ends_with($filename,'.jpg') ? 'image/jpeg' : 'image/png'));
    header('X-Content-Type-Options: nosniff');
    header('Cache-Control: public, max-age=300');
    header('Content-Length: ' . filesize($full));
    readfile($full); exit;
}
if ($route === 'quote_attachment') {
    if (!admin_logged_in()) { http_response_code(403); exit('Accès refusé.'); }
    $id = (int)($_GET['id'] ?? 0);
    $file = (string)($_GET['file'] ?? '');
    if ($id < 1 || !preg_match('/^[a-f0-9]{32}\.(jpg|png|webp|pdf)$/D',$file)) { http_response_code(404); exit; }
    $stmt = $db->prepare('SELECT attachment_names FROM quote_requests WHERE id=?');
    $stmt->execute([$id]);
    $manifest=json_decode((string)$stmt->fetchColumn(),true);
    $allowed=false; $display='piece-jointe';
    if(is_array($manifest)) foreach($manifest as $item) {
        if(is_array($item) && ($item['stored']??'')===$file) {
            $allowed=true; $display=(string)($item['name']??'piece-jointe'); break;
        }
    }
    $full = $root . '/storage/uploads/' . $file;
    if (!$allowed || !is_file($full)) { http_response_code(404); exit; }
    // Pièce jointe privée, téléchargée sans interprétation dans le navigateur.
    header('Content-Type: application/octet-stream');
    header('X-Content-Type-Options: nosniff');
    header('Cache-Control: no-store');
    header('Content-Disposition: attachment; filename="piece-jointe"; filename*=UTF-8\'\'' . rawurlencode(basename($display)));
    header('Content-Length: ' . filesize($full));
    readfile($full);exit;
}
if ($route === 'media') {
    $file = basename((string)($_GET['file'] ?? ''));
    if (!preg_match('/^(thumb_)?[a-f0-9]{36}\.jpg$/', $file)) {
        http_response_code(404);
        exit;
    }
    $full = $uploadDir . '/' . $file;
    if (!is_file($full)) {
        http_response_code(404);
        exit;
    }
    header('Content-Type: image/jpeg');
    header('X-Content-Type-Options: nosniff');
    header('Cache-Control: public, max-age=604800, immutable');
    readfile($full);
    exit;
}

// ==========================================================================
// OUTILS — construction des URL
// ==========================================================================
function url(string $path = '') : string {
    return '/' . ltrim($path, '/');
}


// ==========================================================================
// AFFICHAGE PUBLIC — structure commune, alimentée par le CMS
// ==========================================================================
function page_start(string $title, string $description = '') : void {
    global $db;
    $base = rtrim($_ENV['APP_URL'] ?? '', '/');
    $pathname = parse_url((string)($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH) ?: '/';
    $canonical = $base . $pathname;
    $favicon = cms_media_url($db, 'favicon');
    $og = cms_media_url($db, 'og');
    echo '<!doctype html><html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">';
    echo '<title>' . e($title) . '</title><meta name="description" content="' . e($description) . '">';
    if ($base !== '') echo '<link rel="canonical" href="' . e($canonical) . '">';
    echo '<meta property="og:type" content="website"><meta property="og:title" content="' . e($title) . '"><meta property="og:description" content="' . e($description) . '">';
    if ($og) echo '<meta property="og:image" content="' . e($base . str_replace('&amp;', '&', $og)) . '">';
    if ($favicon) echo '<link rel="icon" type="image/png" href="' . e(str_replace('&amp;', '&', $favicon)) . '">';
    echo '<meta name="theme-color" content="' . e(cms_get($db, 'theme_navy')) . '">';
    echo '<link rel="stylesheet" href="/assets/css/style.css"><style>' . cms_theme_css($db) . '</style><script defer src="/assets/js/site.js"></script></head><body>';
    echo '<header class="site-header"><div class="container nav"><a class="logo" href="/">' . cms_site_brand($db,'header') . '</a><button class="nav-toggle" aria-expanded="false" aria-label="Ouvrir le menu">Menu ☰</button><nav class="nav-links" aria-label="Navigation principale">';
    cms_render_menu($db,'header');
    echo '<a class="btn btn-small" href="' . e(cms_get($db,'site_nav_cta_url')) . '">' . cms_e($db,'site_nav_cta') . '</a></nav></div></header><main>';
}
function page_end() : void {
    global $db;
    echo '</main><footer class="site-footer"><div class="container"><div class="footer-grid"><div><a class="logo" style="color:white" href="/">' . cms_site_brand($db,'footer') . '</a><p>' . cms_e($db,'site_tagline',true) . '</p><p class="muted">SIRET : ' . cms_e($db,'company_siret') . '</p></div>';
    echo '<div><h3>' . cms_e($db,'site_footer_nav_heading') . '</h3>'; 
    foreach(cms_menu($db,'footer_nav') as $item) echo '<p><a href="'.e($item['url']).'">'.e($item['label']).'</a></p>';
    echo '</div><div><h3>' . cms_e($db,'site_footer_info_heading') . '</h3>';
    foreach(cms_menu($db,'footer_info') as $item) echo '<p><a href="'.e($item['url']).'">'.e($item['label']).'</a></p>';
    echo '</div></div><div class="footer-bottom"><span>© ' . date('Y') . ' ' . cms_e($db,'site_name') . '</span><span>' . cms_e($db,'site_footer_bottom') . '</span></div></div></footer></body></html>';
}

// ==========================================================================
// CHANTIERS — lecture de la base de données

// ==========================================================================
function projects(PDO $db, bool $all = false) : array {
    $sql = 'SELECT p.*, (SELECT pi.filename FROM project_images pi WHERE pi.project_id=p.id ORDER BY pi.sort_order,pi.id LIMIT 1) AS first_image FROM projects p';
    if (!$all) $sql .= ' WHERE p.published=1';
    $sql .= ' ORDER BY p.featured DESC,p.updated_at DESC';
    return $db->query($sql)->fetchAll();
}

// ==========================================================================
// CHANTIERS — aperçu d’un chantier
// ==========================================================================
function project_card(array $p) : void {
    global $db;
    $image = $p['cover_image'] ? : ($p['first_image'] ?? null);
    echo '<article class="project-card" data-category="' . e($p['category']) . '"><a href="/chantier/' . e($p['slug']) . '"><img loading="lazy" src="' . e(image_url($image, true)) . '" alt="' . e($p['title']) . '"></a><div class="project-content"><span class="tag">' . e($p['category']) . '</span><h3><a href="/chantier/' . e($p['slug']) . '">' . e($p['title']) . '</a></h3><p>' . e($p['summary']) . '</p><a class="text-link" href="/chantier/' . e($p['slug']) . '">' . cms_e($db,'project_link') . '</a></div></article>';
}

// ==========================================================================
// ADMINISTRATION — structure des pages
// ==========================================================================
function admin_header(string $title) : void {
    global $db;
    echo '<div class="admin-shell"><div class="admin-top"><div class="container" style="display:flex;justify-content:space-between;gap:15px;align-items:center"><strong>Fla\'v · Administration</strong><a href="/" target="_blank" rel="noopener">Voir le site ↗</a></div></div><div class="container admin-layout"><aside class="admin-menu">' . cms_admin_menu($db) . '</aside><section class="admin-panel"><h1 style="font-size:2rem">' . e($title) . '</h1>';
}
function admin_footer() : void {
    echo '</section></div></div></body></html>';
}
function admin_page_start(string $title) : void {
    header('X-Robots-Tag: noindex, nofollow');
    echo '<!doctype html><html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>' . e($title) . ' · Fla\'v</title><link rel="stylesheet" href="/assets/css/style.css"></head><body>';
}

// ==========================================================================
// FORMULAIRES — champ réutilisable
// ==========================================================================
function input_field(string $label, string $name, string $value = '', string $type = 'text', bool $required = false) : void {
    echo '<div class="field"><label for="' . e($name) . '">' . e($label) . ($required ? ' *': '') . '</label><input id="' . e($name) . '" name="' . e($name) . '" type="' . e($type) . '" value="' . e($value) . '"' . ($required ? ' required': '') . '></div>';
}

// ==========================================================================
// ADMINISTRATION — formulaire de connexion
// ==========================================================================
function render_login(string $error = '') : void {
    admin_page_start("Connexion administration");
    echo '<div class="container" style="max-width:520px;padding:70px 0"><div class="form-card"><a class="logo" href="/">Fla<span>\'v</span></a><h1 style="font-size:2rem">Administration</h1><p class="muted">Connectez-vous pour gérer vos chantiers et contenus.</p>';
    if ($error) echo '<div class="notice error">' . e($error) . '</div>';
    echo '<form method="post" action="/admin"><input type="hidden" name="_csrf" value="' . e($_SESSION['_csrf']) . '"><div class="field"><label for="username">Identifiant</label><input id="username" name="username" autocomplete="username" required></div><div class="field" style="margin-top:14px"><label for="password">Mot de passe</label><input id="password" type="password" name="password" autocomplete="current-password" required></div><button class="btn" style="margin-top:22px" type="submit">Se connecter</button></form></div></div></body></html>';
}

// ==========================================================================
// ADMINISTRATION — traitement des actions et pages
// ==========================================================================
function handle_admin(PDO $db, string $path, string $root, string $uploadDir) : void {
    // Déconnexion administrateur
    if ($path === 'admin/deconnexion') {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit('Utilisez le bouton de déconnexion.'); }
        verify_csrf();
        $_SESSION = [];
        session_destroy();
        redirect('/admin?login=1');
    }
    // Connexion et authentification
    if (!admin_logged_in()) {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf();
            if (login_rate_limited()) {
                render_login('Trop de tentatives. Réessayez dans 15 minutes.');
                return;
            }
            $stmt = $db->prepare('SELECT * FROM admins WHERE username=?');
            $stmt->execute([trim((string)($_POST['username'] ?? ''))]);
            $admin = $stmt->fetch();
            if ($admin && password_verify((string)($_POST['password'] ?? ''), $admin['password_hash'])) {
                login_success($admin);
                $db->prepare('UPDATE admins SET last_login_at=NOW() WHERE id=?')->execute([$admin['id']]);
                redirect('/admin');
            }
            record_login_failure();
            usleep(350000);
            render_login('Identifiant ou mot de passe incorrect.');
            return;
        }
        render_login();
        return;
    }
    // Tableau de bord
    if ($path === 'admin' || $path === 'admin/') {
        admin_page_start('Administration');
        admin_header('Tableau de bord');
        $count = (int) $db->query('SELECT COUNT(*) FROM projects')->fetchColumn();
        $pub = (int) $db->query('SELECT COUNT(*) FROM projects WHERE published=1')->fetchColumn();
        echo '<div class="value-grid"><div class="value"><div class="value-mark">01</div><h3>Chantiers</h3><p>' . $count . ' chantier(s) enregistré(s)</p><a class="btn btn-small" href="/admin/chantiers">Gérer les chantiers</a></div><div class="value"><div class="value-mark">02</div><h3>En ligne</h3><p>' . $pub . ' chantier(s) publié(s)</p><a class="btn btn-small" href="/chantiers">Voir la galerie</a></div><div class="value"><div class="value-mark">03</div><h3>Pages</h3><p>Modifier tous les textes, menus, images et paramètres.</p><a class="btn btn-small" href="/admin/contenu">Personnaliser</a></div></div>';
        echo '<div class="cms-quicklinks"><a href="/admin/media">Logos et visuels</a><a href="/admin/menus">Navigation</a><a href="/admin/contenu?section=seo">SEO</a><a href="/admin/contenu?section=apparence">Apparence</a><a href="/admin/devis">Demandes de devis</a></div>';
        admin_footer();
        return;
    }
    // Modification des textes et informations du site
    // Interface CMS : pages, menus, médias et demandes de devis.
    if ($path === 'admin/contenu') { cms_admin_contents($db); return; }
    if ($path === 'admin/menus') { cms_admin_menus($db); return; }
    if ($path === 'admin/media') { cms_admin_media($db,$root); return; }
    if ($path === 'admin/devis') { cms_admin_quotes($db); return; }
    // Création, modification et suppression des chantiers et photos
    if ($path === 'admin/chantiers' || $path === 'admin/chantiers/edit') {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf();
            $action = $_POST['action'] ?? '';
            // Actions sur les photos : rotation, remplacement, couverture, suppression
            if (in_array($action, ['rotate_left', 'rotate_right', 'remove_photo', 'replace_photo', 'cover_photo', 'save_caption', 'photo_up', 'photo_down'], true)) {
                $projectId = (int)($_POST['id'] ?? 0);
                $photoId = (int)($_POST['photo_id'] ?? 0);
                $st = $db->prepare('SELECT pi.* FROM project_images pi JOIN projects p ON p.id=pi.project_id WHERE pi.id=? AND pi.project_id=?');
                $st->execute([$photoId, $projectId]);
                $photo = $st->fetch();
                if (!$photo) {
                    flash('Photo introuvable.', 'error');
                    redirect('/admin/chantiers');
                }
                try {
                    if ($action === 'save_caption') {
                        $caption = trim((string)($_POST['caption'] ?? ''));
                        if (mb_strlen($caption) > 255) throw new RuntimeException('Légende limitée à 255 caractères.');
                        $db->prepare('UPDATE project_images SET caption=? WHERE id=? AND project_id=?')->execute([$caption !== '' ? $caption : null, $photoId, $projectId]);
                        flash('Légende enregistrée.');
                    } elseif ($action === 'photo_up' || $action === 'photo_down') {
                        $ordered = $db->prepare('SELECT id FROM project_images WHERE project_id=? ORDER BY sort_order,id');
                        $ordered->execute([$projectId]);
                        $ids = array_map('intval',$ordered->fetchAll(PDO::FETCH_COLUMN));
                        $pos = array_search($photoId, $ids, true);
                        $target = $pos === false ? -1 : $pos + ($action === 'photo_up' ? -1 : 1);
                        if ($target >= 0 && $target < count($ids)) {
                            [$ids[$pos],$ids[$target]] = [$ids[$target],$ids[$pos]];
                            $db->beginTransaction();
                            try {
                                $update = $db->prepare('UPDATE project_images SET sort_order=? WHERE id=? AND project_id=?');
                                foreach ($ids as $order=>$imageId) $update->execute([$order+1,$imageId,$projectId]);
                                $db->commit();
                            } catch (Throwable $ex) { $db->rollBack(); throw $ex; }
                        }
                        flash('Ordre des photos mis à jour.');
                    } elseif ($action === 'rotate_left' || $action === 'rotate_right') {
                        $new = ImageService::rotate($photo['filename'], $uploadDir, $action === 'rotate_left' ? 90: -90);
                        $db->prepare('UPDATE project_images SET filename=?,thumb_filename=? WHERE id=?')->execute([$new['filename'], $new['thumb_filename'], $photoId]);
                        $db->prepare('UPDATE projects SET cover_image=? WHERE id=? AND cover_image=?')->execute([$new['filename'], $projectId, $photo['filename']]);
                        ImageService::deleteFiles($photo, $uploadDir);
                        flash('Photo tournée de 90°.');
                    } elseif($action === 'replace_photo') {
                        $new = ImageService::store($_FILES['replacement'] ?? [], $uploadDir, (int)($_ENV['UPLOAD_MAX_MB'] ?? 8)*1024*1024);
                        $db->prepare('UPDATE project_images SET filename=?,thumb_filename=? WHERE id=?')->execute([$new['filename'], $new['thumb_filename'], $photoId]);
                        $db->prepare('UPDATE projects SET cover_image=? WHERE id=? AND cover_image=?')->execute([$new['filename'], $projectId, $photo['filename']]);
                        ImageService::deleteFiles($photo, $uploadDir);
                        flash('Photo remplacée.');
                    } elseif($action === 'cover_photo') {
                        $db->prepare('UPDATE projects SET cover_image=? WHERE id=?')->execute([$photo['filename'], $projectId]);
                        flash('Photo de couverture modifiée.');
                    } else {
                        $db->prepare('DELETE FROM project_images WHERE id=? AND project_id=?')->execute([$photoId, $projectId]);
                        $db->prepare('UPDATE projects SET cover_image=NULL WHERE id=? AND cover_image=?')->execute([$projectId, $photo['filename']]);
                        ImageService::deleteFiles($photo, $uploadDir);
                        flash('Photo supprimée.');
                    }
                } catch (Throwable $e) {
                    error_log('Photo admin: ' . $e->getMessage());
                    flash('Impossible de modifier la photo : ' . $e->getMessage(), 'error');
                }
                redirect('/admin/chantiers/edit?id=' . $projectId);
            }
            // Suppression complète d’un chantier
            if ($action === 'delete') {
                $id = (int)($_POST['id'] ?? 0);
                $st = $db->prepare('DELETE FROM projects WHERE id=?');
                $st->execute([$id]);
                flash('Chantier supprimé de la base. Les photos associées doivent être gérées selon la politique de sauvegarde.');
                redirect('/admin/chantiers');
            }
            $title = trim((string)($_POST['title'] ?? ''));
            $id = (int)($_POST['id'] ?? 0);
            if ($title === '') {
                flash('Le titre est obligatoire.', 'error');
                redirect('/admin/chantiers');
            }
            $slug = slugify($title);
            $exists = $db->prepare('SELECT id FROM projects WHERE slug=? AND id<>?');
            $exists->execute([$slug, $id]);
            if ($exists->fetch()) $slug .= '-' . bin2hex(random_bytes(3));
            $data = [$slug, $title, trim((string)($_POST['category'] ?? 'Autres travaux')), trim((string)($_POST['summary'] ?? '')), trim((string)($_POST['description'] ?? '')), trim((string)($_POST['work_date'] ?? '')) ? : null, isset($_POST['published']) ? 1 : 0, isset($_POST['featured']) ? 1 : 0, trim((string)($_POST['seo_title'] ?? '')) ? : null, trim((string)($_POST['seo_description'] ?? '')) ? : null];
            if ($id > 0) {
                $st = $db->prepare('UPDATE projects SET slug=?,title=?,category=?,summary=?,description=?,work_date=?,published=?,featured=?,seo_title=?,seo_description=? WHERE id=?');
                $st->execute([...$data, $id]);
            } else {
                $st = $db->prepare('INSERT INTO projects(slug,title,category,summary,description,work_date,published,featured,seo_title,seo_description) VALUES(?,?,?,?,?,?,?,?,?,?)');
                $st->execute($data);
                $id = (int) $db->lastInsertId();
            }
            if (!empty($_FILES['photos']['name'][0])) {
                $max = (int)($_ENV['UPLOAD_MAX_MB'] ?? 8)*1024*1024;
                foreach ($_FILES['photos']['name']as $i => $original) {
                    $upload = ['name' => $original, 'type' => $_FILES['photos']['type'][$i] ?? '', 'tmp_name' => $_FILES['photos']['tmp_name'][$i] ?? '', 'error' => $_FILES['photos']['error'][$i] ?? UPLOAD_ERR_NO_FILE, 'size' => $_FILES['photos']['size'][$i] ?? 0];
                    try {
                        $stored = ImageService::store($upload, $uploadDir, $max);
                        $ins = $db->prepare('INSERT INTO project_images(project_id,filename,thumb_filename,caption,sort_order) VALUES(?,?,?,?,?)');
                        $ins->execute([$id, $stored['filename'], $stored['thumb_filename'], null, (int) $db->query('SELECT COALESCE(MAX(sort_order),0)+1 FROM project_images WHERE project_id=' . (int) $id)->fetchColumn()]);
                        if (empty($_POST['cover_image'])) $db->prepare('UPDATE projects SET cover_image=? WHERE id=? AND (cover_image IS NULL OR cover_image="")')->execute([$stored['filename'], $id]);
                    } catch (Throwable $e) {
                        error_log('Image upload: ' . $e->getMessage());
                        flash('Chantier enregistré, mais au moins une photo a échoué : ' . $e->getMessage(), 'error');
                    }
                }
            }
            flash('Chantier enregistré.');
            redirect('/admin/chantiers/edit?id=' . $id);
        }
        $editId = (int)($_GET['id'] ?? 0);
        $p = null;
        if ($editId) {
            $st = $db->prepare('SELECT * FROM projects WHERE id=?');
            $st->execute([$editId]);
            $p = $st->fetch();
        }
        admin_page_start('Chantiers');
        admin_header('Gestion des chantiers');
        $f = take_flash();
        if ($f) echo '<div class="notice ' . e($f['type'] === 'error' ? 'error': '') . '">' . e($f['message']) . '</div>';
        if ($path === 'admin/chantiers/edit' && !$p) echo '<div class="notice error">Chantier introuvable.</div>';
        echo '<h2>' . ($p ? 'Modifier le chantier': 'Ajouter un chantier') . '</h2><form method="post" enctype="multipart/form-data">' . csrf_field() . '<input type="hidden" name="action" value="save"><input type="hidden" name="id" value="' . (int)($p['id'] ?? 0) . '"><div class="form-grid">';
        input_field('Titre', 'title', $p['title'] ?? '', 'text', true);
        input_field('Catégorie', 'category', $p['category'] ?? 'Autres travaux', 'text', true);
        input_field('Résumé court', 'summary', $p['summary'] ?? '');
        input_field('Date / période', 'work_date', $p['work_date'] ?? '');
        echo '<div class="field full"><label for="description">Description détaillée</label><textarea id="description" name="description">' . e($p['description'] ?? '') . '</textarea></div>';
        input_field('Titre SEO', 'seo_title', $p['seo_title'] ?? '');
        input_field('Description SEO', 'seo_description', $p['seo_description'] ?? '');
        echo '<div class="field full"><label for="photos">Photos (plusieurs fichiers possibles, JPEG/PNG/WebP)</label><input id="photos" type="file" name="photos[]" accept="image/jpeg,image/png,image/webp" multiple><small>Limite par image : ' . (int)($_ENV['UPLOAD_MAX_MB'] ?? 8) . ' Mo. Les images sont redimensionnées et converties en JPEG optimisé.</small></div></div><p><label><input type="checkbox" name="published" ' . (!empty($p['published']) ? 'checked': '') . '> Publier le chantier</label> &nbsp; <label><input type="checkbox" name="featured" ' . (!empty($p['featured']) ? 'checked': '') . '> Mettre en avant</label></p><button class="btn">Enregistrer le chantier</button> <a class="btn btn-outline" href="/admin/chantiers">Annuler</a></form>';
        if ($p) {
            $st = $db->prepare('SELECT * FROM project_images WHERE project_id=? ORDER BY sort_order,id');
            $st->execute([$p['id']]);
            $photos = $st->fetchAll();
            echo '<section style="margin-top:32px"><h2>Gérer les photos du chantier</h2><p>Tournez chaque photo de 90° ou remplacez-la sans modifier les autres. Les changements sont immédiatement visibles sur le site.</p><div class="photo-manager">';
            foreach ($photos as $photo) {
                $pid = (int) $photo['id'];
                $projectId = (int) $p['id'];
                echo '<div class="photo-manager-item"><img loading="lazy" src="' . e(image_url($photo['thumb_filename'])) . '" alt="Photo du chantier"><div class="photo-manager-actions">';
                foreach (['rotate_left' => '↶ 90° gauche', 'rotate_right' => '↷ 90° droite', 'cover_photo' => 'Photo principale', 'remove_photo' => 'Supprimer']as $act => $label) {
                    echo '<form method="post"' . ($act === 'remove_photo' ? ' onsubmit="return confirm(\'Supprimer cette photo ?\')"': '') . '>' . csrf_field() . '<input type="hidden" name="action" value="' . e($act) . '"><input type="hidden" name="id" value="' . $projectId . '"><input type="hidden" name="photo_id" value="' . $pid . '"><button class="btn btn-small btn-outline" type="submit">' . e($label) . '</button></form>';
                }
                foreach (['photo_up' => '↑ Monter', 'photo_down' => '↓ Descendre'] as $actionName=>$actionText) {
                    echo '<form method="post">' . csrf_field() . '<input type="hidden" name="action" value="'.e($actionName).'"><input type="hidden" name="id" value="'.$projectId.'"><input type="hidden" name="photo_id" value="'.$pid.'"><button class="btn btn-small btn-outline" type="submit">'.e($actionText).'</button></form>';
                }
                echo '<form method="post" class="cms-caption-form">'.csrf_field().'<input type="hidden" name="action" value="save_caption"><input type="hidden" name="id" value="'.$projectId.'"><input type="hidden" name="photo_id" value="'.$pid.'"><label for="caption_'.$pid.'">Légende de la photo</label><input id="caption_'.$pid.'" type="text" maxlength="255" name="caption" value="'.e((string)($photo['caption']??'')).'"><button type="submit" class="btn btn-small btn-outline">Enregistrer la légende</button></form>';
                echo '<form method="post" enctype="multipart/form-data">' . csrf_field() . '<input type="hidden" name="action" value="replace_photo"><input type="hidden" name="id" value="' . $projectId . '"><input type="hidden" name="photo_id" value="' . $pid . '"><label>Remplacer <input required type="file" name="replacement" accept="image/jpeg,image/png,image/webp"></label><button class="btn btn-small" type="submit">Envoyer</button></form></div></div>';
            }
            if (!$photos) echo '<p>Aucune photo pour le moment. Ajoutez-en avec le formulaire ci-dessus.</p>';
            echo '</div></section>';
        }
        echo '<hr style="margin:32px 0;border:0;border-top:1px solid var(--line)"><h2>Chantiers enregistrés</h2><div style="overflow-x:auto"><table class="admin-table"><thead><tr><th>Photo</th><th>Titre</th><th>Statut</th><th>Actions</th></tr></thead><tbody>';
        foreach (projects($db, true) as $row) {
            echo '<tr><td><img src="' . e(image_url($row['cover_image'] ? : ($row['first_image'] ?? null), true)) . '" alt=""></td><td><strong>' . e($row['title']) . '</strong><br><small>' . e($row['category']) . '</small></td><td>' . (!empty($row['published']) ? 'Publié': 'Brouillon') . '</td><td><div class="admin-actions"><a class="btn btn-small" href="/admin/chantiers/edit?id=' . (int) $row['id'] . '">Modifier</a><form method="post" onsubmit="return confirm(\'Supprimer ce chantier ? Cette action retire aussi ses entrées photo de la base.\')">' . csrf_field() . '<input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="' . (int) $row['id'] . '"><button class="btn btn-small btn-outline">Supprimer</button></form></div></td></tr>';
        }
        echo '</tbody></table></div>';
        admin_footer();
        return;
    }
    http_response_code(404);
    echo 'Page administration introuvable.';
}
if (str_starts_with($path, 'admin')) {
    handle_admin($db, $path, $root, $uploadDir);
    exit;
}
// Pages publiques : leurs textes proviennent désormais du catalogue CMS.
if ($path === '') { cms_home_page($db); exit; }
if ($path === 'chantiers') { cms_projects_page($db); exit; }
if (str_starts_with($path, 'chantier/')) {
    cms_project_detail($db,substr($path,strlen('chantier/')));
    exit;
}
if ($path === 'presentation') { cms_presentation_page($db); exit; }
if ($path === 'contact') {
    $sent = false;
    $error = '';
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        verify_csrf();
        if (!empty($_POST['website'] ?? '')) {
            $sent = true;
        } else {
            $name = trim((string)($_POST['name'] ?? ''));
            $email = trim((string)($_POST['email'] ?? ''));
            $phone = trim((string)($_POST['phone'] ?? ''));
            $work = trim((string)($_POST['work_type'] ?? ''));
            $location = trim((string)($_POST['location'] ?? ''));
            $budget = trim((string)($_POST['budget'] ?? ''));
            $date = trim((string)($_POST['desired_date'] ?? ''));
            $message = trim((string)($_POST['message'] ?? ''));
            $captchaValid = verify_contact_captcha($_POST['captcha_answer'] ?? '');
            if (mb_strlen($name) < 2 || mb_strlen($name) > 180 || !filter_var($email, FILTER_VALIDATE_EMAIL) || mb_strlen($work) < 2 || mb_strlen($message) < 15 || mb_strlen($message) > 10000 || empty($_POST['privacy'])) $error = cms_get($db,'contact_validation_error');
            elseif (!$captchaValid) $error = cms_get($db,'contact_captcha_error');
            else {
                $saved = [];
                try {
                    if (!empty($_FILES['attachments']['name'][0])) {
                        if (count($_FILES['attachments']['name']) > 5) throw new RuntimeException('Cinq pièces jointes maximum.');
                        foreach ($_FILES['attachments']['name']as $i => $orig) {
                            if (($_FILES['attachments']['error'][$i] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) throw new RuntimeException('Une pièce jointe n’a pas pu être importée.');
                            if (($_FILES['attachments']['size'][$i] ?? 0) > 5*1024*1024) throw new RuntimeException('Chaque pièce jointe doit faire 5 Mo maximum.');
                            $tmp = $_FILES['attachments']['tmp_name'][$i];
                            $mime = (new finfo(FILEINFO_MIME_TYPE))->file($tmp);
                            $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp', 'application/pdf' => 'pdf'];
                            if (!isset($allowed[$mime])) throw new RuntimeException('Formats autorisés pour les pièces jointes : JPEG, PNG, WebP, PDF.');
                            if (str_starts_with($mime, 'image/') && !getimagesize($tmp)) throw new RuntimeException('Image jointe invalide.');
                            $safe = bin2hex(random_bytes(16)) . '.' . $allowed[$mime];
                            $dest = $root . '/storage/uploads/' . $safe;
                            if (!move_uploaded_file($tmp, $dest)) throw new RuntimeException('Impossible de stocker une pièce jointe.');
                            $saved[$dest] = basename((string) $orig);
                        }
                    }
                    $data = compact('name', 'email', 'phone', 'work', 'location', 'budget', 'date', 'message');
                    $st = $db->prepare('INSERT INTO quote_requests(name,email,phone,work_type,location,budget,desired_date,message,attachment_names) VALUES(?,?,?,?,?,?,?,?,?)');
                    $st->execute([$name, $email, $phone, $work, $location, $budget, $date, $message, json_encode(array_map(fn($stored,$original) => ['stored'=>basename($stored),'name'=>$original], array_keys($saved), array_values($saved)), JSON_UNESCAPED_UNICODE)]);
                    $mailData = ['name' => $name, 'email' => $email, 'phone' => $phone, 'work_type' => $work, 'location' => $location, 'budget' => $budget, 'desired_date' => $date, 'message' => $message];
                    send_quote_email($mailData, $saved);
                    $sent = true;
                } catch (Throwable $ex) {
                    error_log('Quote form: ' . $ex->getMessage());
                    $error = cms_get($db,'contact_delivery_error');
                }
            }
        }
    }
    cms_contact_form($db,$sent,$error);
    exit;
}
if ($path === 'mentions-legales') { cms_legal_page($db); exit; }
if ($path === 'confidentialite') { cms_privacy_page($db); exit; }

if ($path === 'sitemap.xml') {
    header('Content-Type: application/xml; charset=utf-8');
    $base = rtrim($_ENV['APP_URL'] ?? '', '/');
    echo '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    foreach (['', 'chantiers', 'presentation', 'contact', 'mentions-legales', 'confidentialite']as $p) echo '<url><loc>' . e($base . '/' . $p) . '</loc></url>';
    foreach (projects($db) as $p) echo '<url><loc>' . e($base . '/chantier/' . $p['slug']) . '</loc></url>';
    echo '</urlset>';
    exit;
}
http_response_code(404);
page_start(cms_get($db,'site_notfound_title'));
echo '<section class="section container"><h1>' . cms_e($db,'site_notfound_title') . '</h1><p>' . cms_e($db,'site_notfound_body') . '</p><a class="btn" href="/">' . cms_e($db,'site_notfound_button') . '</a></section>';
page_end();
