#!/usr/bin/env bash
set -e

BASE="./"
DOCS="$BASE/docs"
JSON="$BASE/json-definitions/forms"
PAGES="$BASE/pages"
PHP="$BASE/php"
COMP="$PHP/components/life"
VIEWS="$PHP/views/life"

echo "Creating directories..."
mkdir -p "$DOCS" "$JSON" "$PAGES" "$PHP" "$COMP" "$VIEWS"

###############################################
# MD docs
###############################################

cat > "$DOCS/project.ideas.md" << 'EOF'
# Project Ideas – Life Archive Application
Status: Complete

## Core Purpose
A unified Life Archive system that captures, organizes, and displays a person’s life events — with photos, documents, and media — across categories, timeframes, and locations.

## Primary Goals
- Centralized life event repository  
- Dynamic JSON-defined forms  
- Multi-mode viewing (timeline, slideshow)  
- Smart filtering  
- Attachment management  

EOF

cat > "$DOCS/architecture.md" << 'EOF'
# Architecture – Life Archive Application
Status: Complete

## Layers
- Viewer (pages/life.php)
- Admin (pages/life.admin.php)
- JSON Definition Layer (json-definitions/forms)
- PHP Components (php/components/life)
- Views (php/views/life)
- Database (MySQL/MariaDB)
- Media Storage (filesystem)

EOF

cat > "$DOCS/data-model.md" << 'EOF'
# Data Model – Life Archive Application
Status: Complete

Core tables:
- persons
- family_tree
- categories
- subcategories
- life_events
- life_event_attachments
- locations
- timeframes

EOF

cat > "$DOCS/json.schema.md" << 'EOF'
# JSON Schema – Life Archive Application
Status: Incomplete

Form:
{
  "form_key": "string",
  "label": "string",
  "description": "string",
  "version": "1.0",
  "fields": []
}

Field:
{
  "name": "string",
  "label": "string",
  "type": "text|textarea|number|date|select|attachments|repeatable|conditional",
  "required": true,
  "validation": "string",
  "help": "string",
  "icon": "fa-icon",
  "order": 1,
  "multiple": false,
  "allowed_types": ["jpeg","png","gif","pdf","txt"]
}

EOF

cat > "$DOCS/ui.flow.md" << 'EOF'
# UI Flow – Life Archive

Viewer:
1. Select person
2. Filter by category/timeframe/location
3. Choose view mode (timeline/slideshow/gallery)
4. View event details and attachments

Admin:
1. Open life.admin.php
2. Choose module (settings, categories, forms, persons, events)
3. Configure system

EOF

cat > "$DOCS/ui.wireframes.md" << 'EOF'
# UI Wireframes – Life Archive

Person Selection:
- Tree + search

Filter Screen:
- Category, timeframe, location

Timeline:
- Event cards in chronological order

Slideshow:
- Full-width media, auto/manual controls

EOF

cat > "$DOCS/admin.wireframes.md" << 'EOF'
# Admin Wireframes – Life Archive

Modules:
- Settings (.env)
- Categories
- JSON Forms
- Persons & Family Tree
- Events & Attachments

EOF

cat > "$DOCS/component.library.md" << 'EOF'
# Component Library – Life Archive

Viewer:
- PersonSelector
- FilterBar
- TimelineRenderer
- SlideshowRenderer
- EventDetailModal

Admin:
- SettingsForm
- CategoryTable
- JsonFormEditor
- PersonTable
- EventTable
- AttachmentUploader

EOF

cat > "$DOCS/timeline.behavior.md" << 'EOF'
# Timeline Behavior – Life Archive

- Exact chronological order by event_date
- Optional year headers
- Event cards clickable → detail modal

EOF

cat > "$DOCS/slideshow.behavior.md" << 'EOF'
# Slideshow Behavior – Life Archive

Modes:
- Auto (timer from .env)
- Manual (prev/next, optional keyboard)

Media:
- Images full-screen
- PDF first page
- TXT text slide
- Error: "Unable to convert {source} to {target}"

EOF

cat > "$DOCS/md.status.md" << 'EOF'
# MD Status Dashboard – Life Archive

project.ideas.md – Complete  
architecture.md – Complete  
data-model.md – Complete  
json.schema.md – Incomplete  
ui.flow.md – Complete  
ui.wireframes.md – Complete  
admin.wireframes.md – Complete  
component.library.md – Complete  
timeline.behavior.md – Complete  
slideshow.behavior.md – Complete  

EOF

###############################################
# JSON forms
###############################################

cat > "$JSON/homes.json" << 'EOF'
{
  "form_key": "homes_event",
  "label": "Home Event",
  "description": "Record a home-related life event.",
  "version": "1.0",
  "fields": [
    { "name": "event_date", "label": "Event Date", "type": "date", "required": true, "icon": "fa-calendar", "order": 1 },
    { "name": "title", "label": "Title", "type": "text", "required": true, "icon": "fa-home", "order": 2 },
    { "name": "address", "label": "Address", "type": "text", "required": false, "icon": "fa-map-marker-alt", "order": 3 },
    { "name": "city", "label": "City", "type": "text", "required": false, "icon": "fa-city", "order": 4 },
    { "name": "description", "label": "Description", "type": "textarea", "required": false, "icon": "fa-align-left", "order": 5 },
    { "name": "attachments", "label": "Attachments", "type": "attachments", "required": false, "multiple": true, "allowed_types": ["jpeg","png","gif","pdf","txt"], "icon": "fa-paperclip", "order": 6 }
  ]
}
EOF

cat > "$JSON/cars.json" << 'EOF'
{
  "form_key": "cars_event",
  "label": "Car Event",
  "description": "Record a car-related life event.",
  "version": "1.0",
  "fields": [
    { "name": "event_date", "label": "Event Date", "type": "date", "required": true, "icon": "fa-calendar", "order": 1 },
    { "name": "title", "label": "Title", "type": "text", "required": true, "icon": "fa-car", "order": 2 },
    { "name": "make", "label": "Make", "type": "text", "required": false, "icon": "fa-industry", "order": 3 },
    { "name": "model", "label": "Model", "type": "text", "required": false, "icon": "fa-car-side", "order": 4 },
    { "name": "year", "label": "Year", "type": "number", "required": false, "icon": "fa-hashtag", "order": 5 },
    { "name": "description", "label": "Description", "type": "textarea", "required": false, "icon": "fa-align-left", "order": 6 },
    { "name": "attachments", "label": "Attachments", "type": "attachments", "required": false, "multiple": true, "allowed_types": ["jpeg","png","gif","pdf","txt"], "icon": "fa-paperclip", "order": 7 }
  ]
}
EOF

cat > "$JSON/education.json" << 'EOF'
{
  "form_key": "education_event",
  "label": "Education Event",
  "description": "Record an education milestone.",
  "version": "1.0",
  "fields": [
    { "name": "event_date", "label": "Event Date", "type": "date", "required": true, "icon": "fa-calendar", "order": 1 },
    { "name": "title", "label": "Title", "type": "text", "required": true, "icon": "fa-graduation-cap", "order": 2 },
    { "name": "institution", "label": "Institution", "type": "text", "required": false, "icon": "fa-university", "order": 3 },
    { "name": "degree", "label": "Degree", "type": "text", "required": false, "icon": "fa-certificate", "order": 4 },
    { "name": "description", "label": "Description", "type": "textarea", "required": false, "icon": "fa-align-left", "order": 5 },
    { "name": "attachments", "label": "Attachments", "type": "attachments", "required": false, "multiple": true, "allowed_types": ["jpeg","png","gif","pdf","txt"], "icon": "fa-paperclip", "order": 6 }
  ]
}
EOF

###############################################
# PHP components – JSON form renderer
###############################################

cat > "$COMP/form.renderer.php" << 'EOF'
<?php
// JSON Form Renderer – Bootstrap + AdminLTE

function life_load_form_definition(string $formKey): ?array {
    $base = dirname(__DIR__, 2); // /apps/life/php/components -> /apps/life
    $file = $base . "/json-definitions/forms/" . $formKey . ".json";
    if (!file_exists($file)) {
        return null;
    }
    $json = file_get_contents($file);
    return json_decode($json, true);
}

function life_render_form(array $form, string $action = "", string $method = "post") {
    echo '<form action="' . htmlspecialchars($action) . '" method="' . htmlspecialchars($method) . '" enctype="multipart/form-data" class="card card-body">';
    if (!empty($form['label'])) {
        echo '<h3>' . htmlspecialchars($form['label']) . '</h3>';
    }
    if (!empty($form['description'])) {
        echo '<p class="text-muted">' . htmlspecialchars($form['description']) . '</p>';
    }
    foreach ($form['fields'] as $field) {
        life_render_field($field);
    }
    echo '<button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Save</button>';
    echo '</form>';
}

function life_render_field(array $f) {
    $name  = $f['name'] ?? '';
    $label = $f['label'] ?? $name;
    $type  = $f['type'] ?? 'text';
    $help  = $f['help'] ?? '';
    $icon  = $f['icon'] ?? '';
    $required = !empty($f['required']);

    echo '<div class="form-group">';
    echo '<label for="' . htmlspecialchars($name) . '">';
    if ($icon) {
        echo '<i class="fa ' . htmlspecialchars($icon) . '"></i> ';
    }
    echo htmlspecialchars($label);
    if ($required) {
        echo ' <span class="text-danger">*</span>';
    }
    echo '</label>';

    switch ($type) {
        case 'textarea':
            echo '<textarea class="form-control" name="' . htmlspecialchars($name) . '" id="' . htmlspecialchars($name) . '"></textarea>';
            break;
        case 'number':
            echo '<input type="number" class="form-control" name="' . htmlspecialchars($name) . '" id="' . htmlspecialchars($name) . '">';
            break;
        case 'date':
            echo '<input type="date" class="form-control" name="' . htmlspecialchars($name) . '" id="' . htmlspecialchars($name) . '">';
            break;
        case 'attachments':
            $multiple = !empty($f['multiple']);
            $multipleAttr = $multiple ? ' multiple' : '';
            echo '<input type="file" class="form-control-file" name="' . htmlspecialchars($name) . ($multiple ? '[]' : '') . '" id="' . htmlspecialchars($name) . '"' . $multipleAttr . '>';
            break;
        default:
            echo '<input type="text" class="form-control" name="' . htmlspecialchars($name) . '" id="' . htmlspecialchars($name) . '">';
            break;
    }

    if ($help) {
        echo '<small class="form-text text-muted">' . htmlspecialchars($help) . '</small>';
    }
    echo '</div>';
}
EOF

###############################################
# PHP components – timeline renderer
###############################################

cat > "$COMP/timeline.renderer.php" << 'EOF'
<?php
// Timeline Renderer – full version skeleton

function life_render_timeline(array $events) {
    echo '<div class="timeline">';
    // events should already be sorted by event_date ascending
    foreach ($events as $event) {
        $date = htmlspecialchars($event['event_date'] ?? '');
        $title = htmlspecialchars($event['title'] ?? '');
        $categoryIcon = htmlspecialchars($event['category_icon'] ?? 'fa-circle');
        echo '<div class="timeline-item">';
        echo '<span class="time"><i class="fa fa-calendar"></i> ' . $date . '</span>';
        echo '<h3 class="timeline-header"><i class="fa ' . $categoryIcon . '"></i> ' . $title . '</h3>';
        echo '<div class="timeline-body">';
        if (!empty($event['description'])) {
            echo '<p>' . htmlspecialchars($event['description']) . '</p>';
        }
        if (!empty($event['attachments'])) {
            echo '<div class="row">';
            foreach ($event['attachments'] as $att) {
                $thumb = htmlspecialchars($att['thumbnail_url'] ?? '');
                $name  = htmlspecialchars($att['name'] ?? '');
                echo '<div class="col-3">';
                if ($thumb) {
                    echo '<img src="' . $thumb . '" class="img-fluid img-thumbnail" alt="' . $name . '">';
                } else {
                    echo '<div class="border p-2 text-center">' . $name . '</div>';
                }
                echo '</div>';
            }
            echo '</div>';
        }
        echo '</div>'; // body
        echo '</div>'; // item
    }
    echo '</div>';
}
EOF

###############################################
# PHP components – slideshow renderer
###############################################

cat > "$COMP/slideshow.renderer.php" << 'EOF'
<?php
// Slideshow Renderer – full version skeleton

function life_render_slideshow(array $events, int $intervalSeconds = 5) {
    echo '<div id="life-slideshow" class="card">';
    echo '<div class="card-body">';
    echo '<div class="slideshow-media"></div>';
    echo '<div class="slideshow-meta"></div>';
    echo '<div class="slideshow-controls">';
    echo '<button class="btn btn-secondary" data-action="prev"><i class="fa fa-arrow-left"></i></button> ';
    echo '<button class="btn btn-secondary" data-action="next"><i class="fa fa-arrow-right"></i></button> ';
    echo '<button class="btn btn-primary" data-action="toggle"><i class="fa fa-play"></i>/<i class="fa fa-pause"></i></button>';
    echo '</div>';
    echo '</div>';
    echo '</div>';

    // Basic JS hook (you can expand)
    echo '<script>
    window.lifeSlideshowData = ' . json_encode($events) . ';
    window.lifeSlideshowInterval = ' . (int)$intervalSeconds . ';
    // TODO: implement JS slideshow logic (auto/manual, PDF/TXT handling, error messages)
    </script>';
}
EOF

###############################################
# Viewer – pages/life.php
###############################################

cat > "$PAGES/life.php" << 'EOF'
<?php
// Life Archive Viewer

$base = dirname(__DIR__); // /apps/life/pages -> /apps/life
require_once $base . "/php/components/life/form.renderer.php";
require_once $base . "/php/components/life/timeline.renderer.php";
require_once $base . "/php/components/life/slideshow.renderer.php";

// TODO: load person, filters, events from DB
$view = $_GET['view'] ?? 'timeline'; // timeline|slideshow|gallery
$formKey = $_GET['form'] ?? 'homes_event'; // example

$form = life_load_form_definition($formKey);
$events = []; // TODO: query DB for events

?>
<!DOCTYPE html>
<html>
<head>
    <title>Life Archive Viewer</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <section class="content-header">
        <h1>Life Archive</h1>
    </section>
    <section class="content">
        <div class="row">
            <div class="col-md-4">
                <?php if ($form): ?>
                    <?php life_render_form($form, "life.php?view=" . htmlspecialchars($view) . "&form=" . htmlspecialchars($formKey)); ?>
                <?php else: ?>
                    <p>No form definition found for key: <?= htmlspecialchars($formKey) ?></p>
                <?php endif; ?>
            </div>
            <div class="col-md-8">
                <?php
                if ($view === 'timeline') {
                    life_render_timeline($events);
                } elseif ($view === 'slideshow') {
                    life_render_slideshow($events, 5);
                } else {
                    echo "<p>Gallery view not yet implemented.</p>";
                }
                ?>
            </div>
        </div>
    </section>
</div>
</body>
</html>
EOF

###############################################
# Admin – pages/life.admin.php
###############################################

cat > "$PAGES/life.admin.php" << 'EOF'
<?php
// Life Archive Admin

$base = dirname(__DIR__);
require_once $base . "/php/components/life/form.renderer.php";

$module = $_GET['module'] ?? 'dashboard';

?>
<!DOCTYPE html>
<html>
<head>
    <title>Life Archive Administration</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <aside class="main-sidebar sidebar-dark-primary elevation-4">
        <a href="?module=dashboard" class="brand-link">Life Archive Admin</a>
        <div class="sidebar">
            <nav>
                <ul class="nav nav-pills nav-sidebar flex-column">
                    <li class="nav-item"><a href="?module=settings" class="nav-link">Settings</a></li>
                    <li class="nav-item"><a href="?module=categories" class="nav-link">Categories</a></li>
                    <li class="nav-item"><a href="?module=forms" class="nav-link">JSON Forms</a></li>
                    <li class="nav-item"><a href="?module=persons" class="nav-link">Persons</a></li>
                    <li class="nav-item"><a href="?module=events" class="nav-link">Events</a></li>
                </ul>
            </nav>
        </div>
    </aside>

    <div class="content-wrapper">
        <section class="content-header">
            <h1><?= htmlspecialchars(ucfirst($module)) ?></h1>
        </section>
        <section class="content">
            <?php
            switch ($module) {
                case 'forms':
                    $form = life_load_form_definition('homes_event');
                    if ($form) {
                        life_render_form($form, "life.admin.php?module=forms");
                    } else {
                        echo "<p>No form definitions found.</p>";
                    }
                    break;
                default:
                    echo "<p>Module skeleton – implement settings, categories, persons, events.</p>";
                    break;
            }
            ?>
        </section>
    </div>
</div>
</body>
</html>
EOF

echo "All Life Archive docs, JSON, and views installed and wired."

