<?php
require_once __DIR__ . '/lib/functions.php';
mdw_require_login();
global $mdw_downloads_file, $mdw_public_download_dir, $mdw_allowed_upload_ext;
$downloads = mdw_read_json($mdw_downloads_file, []);
$editIndex = isset($_GET['edit']) ? (int)$_GET['edit'] : -1;
$editing = $downloads[$editIndex] ?? null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'delete') {
        $idx = (int)($_POST['index'] ?? -1);
        if (isset($downloads[$idx])) {
            array_splice($downloads, $idx, 1);
            mdw_write_json($mdw_downloads_file, array_values($downloads));
            mdw_flash('Download entry deleted.');
        }
        header('Location: downloads.php'); exit;
    }
    if ($action === 'save') {
        $idx = $_POST['index'] === '' ? -1 : (int)$_POST['index'];
        $fileName = trim($_POST['file'] ?? '');
        if (!empty($_FILES['upload']['name'])) {
            if (!is_dir($mdw_public_download_dir)) mkdir($mdw_public_download_dir, 0755, true);
            $original = basename($_FILES['upload']['name']);
            $ext = strtolower(pathinfo($original, PATHINFO_EXTENSION));
            if (!in_array($ext, $mdw_allowed_upload_ext, true)) {
                mdw_flash('File type not allowed.', 'error');
                header('Location: downloads.php'); exit;
            }
            $safeName = mdw_slug(pathinfo($original, PATHINFO_FILENAME)) . '.' . $ext;
            if (!move_uploaded_file($_FILES['upload']['tmp_name'], $mdw_public_download_dir . '/' . $safeName)) {
                mdw_flash('Upload failed. Check public-downloads folder permissions.', 'error');
                header('Location: downloads.php'); exit;
            }
            $fileName = $safeName;
        }
        $entry = [
            'title' => trim($_POST['title'] ?? ''),
            'group' => trim($_POST['group'] ?? 'General Resources'),
            'description' => trim($_POST['description'] ?? ''),
            'file' => $fileName,
            'button' => trim($_POST['button'] ?? 'Open File'),
            'active' => !empty($_POST['active']),
            'sort' => (int)($_POST['sort'] ?? 100),
        ];
        if ($entry['title'] === '' || $entry['file'] === '') {
            mdw_flash('Title and file are required.', 'error');
            header('Location: downloads.php'); exit;
        }
        if ($idx >= 0 && isset($downloads[$idx])) $downloads[$idx] = $entry; else $downloads[] = $entry;
        usort($downloads, fn($a,$b) => ($a['sort'] ?? 100) <=> ($b['sort'] ?? 100));
        mdw_write_json($mdw_downloads_file, array_values($downloads));
        mdw_flash('Download entry saved.');
        header('Location: downloads.php'); exit;
    }
}
mdw_render_header('Downloads Manager');
?>
<div class="split">
<section class="panel">
  <h2><?php echo $editing ? 'Edit Download' : 'Add Download'; ?></h2>
  <form method="post" enctype="multipart/form-data">
    <input type="hidden" name="action" value="save">
    <input type="hidden" name="index" value="<?php echo $editing ? (int)$editIndex : ''; ?>">
    <label>Title</label><input name="title" value="<?php echo mdw_h($editing['title'] ?? ''); ?>" required>
    <label>Group / Product</label><input name="group" value="<?php echo mdw_h($editing['group'] ?? 'General Resources'); ?>">
    <label>Description</label><textarea name="description"><?php echo mdw_h($editing['description'] ?? ''); ?></textarea>
    <label>Current File Name</label><input name="file" value="<?php echo mdw_h($editing['file'] ?? ''); ?>" placeholder="example.pdf">
    <label>Upload New File</label><input type="file" name="upload">
    <label>Button Text</label><input name="button" value="<?php echo mdw_h($editing['button'] ?? 'Open File'); ?>">
    <label>Sort Order</label><input type="number" name="sort" value="<?php echo (int)($editing['sort'] ?? 100); ?>">
    <label><input style="width:auto" type="checkbox" name="active" value="1" <?php echo ($editing['active'] ?? true) ? 'checked' : ''; ?>> Active / show publicly</label>
    <br><button class="button" type="submit">Save Download</button> <a class="button ghost" href="downloads.php">Clear</a>
  </form>
</section>
<section class="panel">
  <h2>Notes</h2>
  <p>Files upload to:</p><p><code>/public-downloads/</code></p>
  <p>The public downloads page reads this JSON file:</p><p><code>/devworks-admin/data/downloads.json</code></p>
  <p class="muted">PDF files open in a new tab. ZIP files download directly by browser behavior.</p>
</section>
</div>
<section class="panel" style="margin-top:20px"><h2>Current Downloads</h2><table><tr><th>Sort</th><th>Group</th><th>Title</th><th>File</th><th>Status</th><th>Actions</th></tr><?php foreach($downloads as $i=>$d): ?><tr><td><?php echo (int)($d['sort'] ?? 100); ?></td><td><?php echo mdw_h($d['group'] ?? ''); ?></td><td><?php echo mdw_h($d['title'] ?? ''); ?><br><span class="muted small"><?php echo mdw_h($d['description'] ?? ''); ?></span></td><td><code><?php echo mdw_h($d['file'] ?? ''); ?></code></td><td><?php echo !empty($d['active']) ? 'Active' : 'Hidden'; ?></td><td class="row-actions"><a class="button" href="downloads.php?edit=<?php echo $i; ?>">Edit</a><form method="post" onsubmit="return confirm('Delete this download entry?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="index" value="<?php echo $i; ?>"><button class="button danger" type="submit">Delete</button></form></td></tr><?php endforeach; ?></table></section>
<?php mdw_render_footer(); ?>
