<?php
/**
 * CMS Theme Upload Handler
 */
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['userid'])) {
    http_response_code(401);
    exit(json_encode(['error' => 'Unauthorized']));
}

require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');
$db = new App_DB(DBU::$dba_user);

$upload_dir = '../../web/themes/';

if ($_FILES['theme_zip']) {
    $file = $_FILES['theme_zip'];

    if (pathinfo($file['name'], PATHINFO_EXTENSION) !== 'zip') {
        exit(json_encode(['error' => 'Only ZIP files are allowed']));
    }

    $zip = new ZipArchive;
    if ($zip->open($file['tmp_name']) === TRUE) {
        $theme_name = basename($file['name'], ".zip");
        $extract_to = $upload_dir . $theme_name . "_" . time();

        mkdir($extract_to, 0755, true);
        $zip->extractTo($extract_to);
        $zip->close();

        // Register in DB
        $dir_name = basename($extract_to);
        $db->dbQuery(
            "INSERT INTO cms_themes (theme_name, directory_name, is_active) VALUES (:name, :dir, 0)",
            ['name' => str_replace('_', ' ', $theme_name), 'dir' => $dir_name]
        );

        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['error' => 'Failed to open ZIP']);
    }
}
?>