<?php
$file = "events.json";

/* DELETE EVENT */
if(isset($_GET['delete'])){
    $data = json_decode(file_get_contents($file), true);
    $index = $_GET['delete'];
    unset($data[$index]);
    $data = array_values($data);
    file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT));
    header("Location: post-event.php");
    exit;
}

/* ADD EVENT */
if(isset($_POST['submit'])){
    $title       = htmlspecialchars($_POST['title']);
    $description = htmlspecialchars($_POST['description']);
    $type        = $_POST['media_type']; // image | audio | video | pdf
    $date        = date("F j, Y");

    /* Allowed extensions per type */
    $allowed = [
        'image' => ['jpg','jpeg','png','gif','webp'],
        'audio' => ['mp3','wav','ogg','m4a'],
        'video' => ['mp4','webm','mov','avi'],
        'pdf'   => ['pdf']
    ];

    $file_name = $_FILES['media']['name'];
    $tmp       = $_FILES['media']['tmp_name'];
    $ext       = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

    /* Validate extension */
    if(!in_array($ext, $allowed[$type] ?? [])){
        $error = "Invalid file type for selected media category.";
    } else {
        $safe_name   = time() . '_' . preg_replace('/\s+/', '_', $file_name);
        $uploadPath  = "uploads/" . $safe_name;
        $savePath    = "admin/uploads/" . $safe_name;

        if(move_uploaded_file($tmp, $uploadPath)){
            $data = [];
            if(file_exists($file)){
                $data = json_decode(file_get_contents($file), true);
            }
            $data[] = [
                "title"       => $title,
                "description" => $description,
                "media_type"  => $type,
                "media"       => $savePath,
                "date"        => $date
            ];
            file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT));
            $success = "Content posted successfully!";
        } else {
            $error = "File upload failed. Check folder permissions.";
        }
    }
}

/* LOAD EVENTS */
$data = [];
if(file_exists($file)){
    $data = json_decode(file_get_contents($file), true);
}

/* Icon map */
$icons = [
    'image' => '🖼️',
    'audio' => '🎵',
    'video' => '🎬',
    'pdf'   => '📄'
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin — Post Content | OLPH Schools</title>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Playfair+Display:wght@700&display=swap" rel="stylesheet">
<style>
*{ box-sizing:border-box; margin:0; padding:0; }

:root{
    --green:#1B5E20;
    --green-mid:#2E7D32;
    --green-light:#E8F5E9;
    --accent:#F9A825;
    --red:#C62828;
    --text:#1a1a1a;
    --muted:#666;
    --border:#e0e0e0;
    --radius:12px;
}

body{
    font-family:'DM Sans', sans-serif;
    background:#f0f4f0;
    color:var(--text);
    padding:40px 20px;
    min-height:100vh;
}

h1.page-title{
    font-family:'Playfair Display', serif;
    font-size:32px;
    color:var(--green);
    text-align:center;
    margin-bottom:8px;
}
.page-subtitle{
    text-align:center;
    color:var(--muted);
    margin-bottom:40px;
    font-size:15px;
}

.layout{
    max-width:1100px;
    margin:auto;
    display:grid;
    grid-template-columns:1fr 1.4fr;
    gap:30px;
    align-items:start;
}

/* FORM CARD */
.form-card{
    background:white;
    border-radius:var(--radius);
    padding:32px;
    box-shadow:0 4px 20px rgba(0,0,0,0.07);
}

.form-card h2{
    font-size:20px;
    margin-bottom:24px;
    color:var(--green);
    border-bottom:2px solid var(--green-light);
    padding-bottom:12px;
}

label{
    display:block;
    font-size:13px;
    font-weight:600;
    margin-bottom:6px;
    color:var(--muted);
    text-transform:uppercase;
    letter-spacing:.5px;
}

input[type=text],
textarea,
select{
    width:100%;
    padding:12px 14px;
    border:1.5px solid var(--border);
    border-radius:8px;
    font-family:inherit;
    font-size:15px;
    margin-bottom:18px;
    transition:border-color .2s;
    background:#fafafa;
}
input[type=text]:focus,
textarea:focus,
select:focus{
    outline:none;
    border-color:var(--green-mid);
    background:white;
}
textarea{ height:100px; resize:vertical; }

/* Type selector tabs */
.type-tabs{
    display:flex;
    gap:8px;
    margin-bottom:18px;
    flex-wrap:wrap;
}
.type-tab{
    flex:1;
    min-width:70px;
    padding:10px 6px;
    border:1.5px solid var(--border);
    border-radius:8px;
    background:#fafafa;
    cursor:pointer;
    text-align:center;
    font-size:13px;
    font-weight:600;
    transition:.2s;
}
.type-tab:hover{ border-color:var(--green-mid); }
.type-tab.active{
    border-color:var(--green-mid);
    background:var(--green-light);
    color:var(--green);
}
.type-tab span{ display:block; font-size:22px; margin-bottom:4px; }

/* Hidden real type input */
#media_type{ display:none; }

/* File input */
.file-area{
    border:2px dashed var(--border);
    border-radius:8px;
    padding:24px;
    text-align:center;
    cursor:pointer;
    margin-bottom:18px;
    transition:.2s;
    background:#fafafa;
}
.file-area:hover{ border-color:var(--green-mid); background:var(--green-light); }
.file-area input{ display:none; }
.file-area .file-icon{ font-size:32px; margin-bottom:8px; }
.file-area p{ font-size:14px; color:var(--muted); }
.file-area .file-name{ font-size:13px; color:var(--green-mid); font-weight:600; margin-top:6px; }
#accept-hint{ font-size:12px; color:#aaa; margin-top:4px; }

button[type=submit]{
    width:100%;
    padding:14px;
    background:var(--green-mid);
    color:white;
    border:none;
    border-radius:8px;
    font-size:16px;
    font-weight:700;
    cursor:pointer;
    font-family:inherit;
    transition:background .2s;
    letter-spacing:.3px;
}
button[type=submit]:hover{ background:var(--green); }

.alert{
    padding:12px 16px;
    border-radius:8px;
    margin-bottom:20px;
    font-weight:600;
    font-size:14px;
}
.alert.success{ background:#E8F5E9; color:#1B5E20; border:1px solid #A5D6A7; }
.alert.error  { background:#FFEBEE; color:var(--red); border:1px solid #EF9A9A; }

/* EVENTS LIST */
.events-card{
    background:white;
    border-radius:var(--radius);
    padding:28px;
    box-shadow:0 4px 20px rgba(0,0,0,0.07);
}
.events-card h2{
    font-size:20px;
    margin-bottom:20px;
    color:var(--green);
    border-bottom:2px solid var(--green-light);
    padding-bottom:12px;
    display:flex;
    justify-content:space-between;
    align-items:center;
}
.events-card h2 span{
    font-size:13px;
    background:var(--green-light);
    color:var(--green);
    padding:4px 10px;
    border-radius:20px;
    font-family:'DM Sans',sans-serif;
}

.event-item{
    display:flex;
    gap:16px;
    padding:16px 0;
    border-bottom:1px solid var(--border);
    align-items:flex-start;
}
.event-item:last-child{ border-bottom:none; }

.event-thumb{
    width:70px;
    height:70px;
    border-radius:8px;
    object-fit:cover;
    flex-shrink:0;
    background:var(--green-light);
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:30px;
    overflow:hidden;
}
.event-thumb img{ width:100%; height:100%; object-fit:cover; }

.event-info{ flex:1; min-width:0; }
.event-info h3{
    font-size:15px;
    font-weight:700;
    margin-bottom:4px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
}
.event-info p{
    font-size:13px;
    color:var(--muted);
    margin-bottom:6px;
    display:-webkit-box;
    -webkit-line-clamp:2;
    -webkit-box-orient:vertical;
    overflow:hidden;
}
.event-meta{
    display:flex;
    align-items:center;
    gap:10px;
    font-size:12px;
    color:#999;
}
.badge{
    display:inline-flex;
    align-items:center;
    gap:4px;
    padding:2px 8px;
    border-radius:20px;
    font-size:11px;
    font-weight:700;
    text-transform:uppercase;
}
.badge-image{ background:#E3F2FD; color:#1565C0; }
.badge-audio{ background:#F3E5F5; color:#6A1B9A; }
.badge-video{ background:#FFF3E0; color:#E65100; }
.badge-pdf  { background:#FCE4EC; color:#880E4F; }

.delete-btn{
    color:var(--red);
    font-size:12px;
    font-weight:700;
    text-decoration:none;
    padding:4px 10px;
    border-radius:6px;
    border:1px solid #FFCDD2;
    background:#FFF;
    transition:.2s;
    white-space:nowrap;
}
.delete-btn:hover{ background:#FFEBEE; }

.empty-state{
    text-align:center;
    padding:40px 20px;
    color:var(--muted);
}
.empty-state .icon{ font-size:48px; margin-bottom:12px; }

@media(max-width:750px){
    .layout{ grid-template-columns:1fr; }
}
</style>
</head>
<body>

<h1 class="page-title">OLPH Schools — Admin</h1>
<p class="page-subtitle">Manage news, events, and learning resources</p>

<div class="layout">

    <!-- FORM -->
    <div class="form-card">
        <h2>Post New Content</h2>

        <?php if(isset($success)): ?>
            <div class="alert success">✅ <?= $success ?></div>
        <?php endif; ?>
        <?php if(isset($error)): ?>
            <div class="alert error">❌ <?= $error ?></div>
        <?php endif; ?>

        <form method="POST" enctype="multipart/form-data" id="postForm">

            <label>Content Title</label>
            <input type="text" name="title" placeholder="e.g. End of Term Concert" required>

            <label>Description</label>
            <textarea name="description" placeholder="Brief description of this content..." required></textarea>

            <label>Media Type</label>
            <div class="type-tabs">
                <div class="type-tab active" onclick="setType('image',this)">
                    <span>🖼️</span>Image
                </div>
                <div class="type-tab" onclick="setType('audio',this)">
                    <span>🎵</span>Audio
                </div>
                <div class="type-tab" onclick="setType('video',this)">
                    <span>🎬</span>Video
                </div>
                <div class="type-tab" onclick="setType('pdf',this)">
                    <span>📄</span>PDF
                </div>
            </div>
            <input type="hidden" name="media_type" id="media_type" value="image">

            <label>Upload File</label>
            <div class="file-area" onclick="document.getElementById('mediaFile').click()">
                <div class="file-icon" id="uploadIcon">🖼️</div>
                <p>Click to browse or drag & drop</p>
                <p id="accept-hint">Accepted: JPG, PNG, GIF, WEBP</p>
                <p class="file-name" id="fileName">No file chosen</p>
                <input type="file" id="mediaFile" name="media" required
                       accept="image/*"
                       onchange="document.getElementById('fileName').textContent=this.files[0]?.name||'No file chosen'">
            </div>

            <button type="submit" name="submit">🚀 Post Content</button>
        </form>
    </div>

    <!-- EVENTS LIST -->
    <div class="events-card">
        <h2>
            Posted Content
            <span><?= count($data) ?> item<?= count($data)!=1?'s':'' ?></span>
        </h2>

        <?php if(empty($data)): ?>
            <div class="empty-state">
                <div class="icon">📭</div>
                <p>No content posted yet.<br>Use the form to add your first item.</p>
            </div>
        <?php else: ?>

            <?php foreach(array_reverse($data, true) as $index => $event): ?>
            <div class="event-item">

                <!-- Thumbnail / icon -->
                <div class="event-thumb">
                    <?php if($event['media_type'] === 'image'): ?>
                        <img src="<?= htmlspecialchars($event['media']) ?>" alt="">
                    <?php else: ?>
                        <?= $icons[$event['media_type']] ?? '📁' ?>
                    <?php endif; ?>
                </div>

                <div class="event-info">
                    <h3><?= htmlspecialchars($event['title']) ?></h3>
                    <p><?= htmlspecialchars($event['description']) ?></p>
                    <div class="event-meta">
                        <span class="badge badge-<?= $event['media_type'] ?>">
                            <?= $icons[$event['media_type']] ?? '' ?>
                            <?= ucfirst($event['media_type']) ?>
                        </span>
                        📅 <?= $event['date'] ?>
                        &nbsp;
                        <a href="?delete=<?= $index ?>"
                           class="delete-btn"
                           onclick="return confirm('Delete this item?')">🗑 Delete</a>
                    </div>
                </div>

            </div>
            <?php endforeach; ?>

        <?php endif; ?>
    </div>

</div>

<script>
const typeConfig = {
    image: { accept:'image/*',        hint:'JPG, PNG, GIF, WEBP',           icon:'🖼️' },
    audio: { accept:'audio/*',        hint:'MP3, WAV, OGG, M4A',            icon:'🎵' },
    video: { accept:'video/*',        hint:'MP4, WEBM, MOV, AVI',           icon:'🎬' },
    pdf:   { accept:'application/pdf',hint:'PDF files only',                icon:'📄' }
};

function setType(type, el){
    // update tabs
    document.querySelectorAll('.type-tab').forEach(t => t.classList.remove('active'));
    el.classList.add('active');
    // update hidden input
    document.getElementById('media_type').value = type;
    // update file input
    const cfg = typeConfig[type];
    const fi = document.getElementById('mediaFile');
    fi.accept = cfg.accept;
    fi.value = '';
    document.getElementById('fileName').textContent = 'No file chosen';
    document.getElementById('accept-hint').textContent = 'Accepted: ' + cfg.hint;
    document.getElementById('uploadIcon').textContent = cfg.icon;
}
</script>
</body>
</html>
