<?php
require_once(__DIR__ . '/../../session.php');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo json_encode(['status' => 'error', 'message' => "Invalid CSRF Token!"]);
        exit();
    }

    $action = $_POST['action'] ?? '';

    switch ($action) {
        case 'website':
            $title        = htmlspecialchars($_POST['title'] ?? '');
            $description  = htmlspecialchars($_POST['description'] ?? '');
            $telegram     = htmlspecialchars($_POST['telegram'] ?? '');
            $facebook     = htmlspecialchars($_POST['facebook'] ?? '');
            $whatsapp     = htmlspecialchars($_POST['whatsapp'] ?? '');
            $livechat     = htmlspecialchars($_POST['livechat'] ?? '');
            $livechat_js  = htmlspecialchars($_POST['livechat_js'] ?? '');
            $theme        = htmlspecialchars($_POST['theme'] ?? '');
            $maintenance  = (int) ($_POST['maintenance'] ?? 0);

            $stmtOld = $db->query("SELECT logo, favicon FROM configuration WHERE id = 1");
            $oldData = $stmtOld->fetch(PDO::FETCH_ASSOC);

            $rootFolder = __DIR__ . '/../../../Images/';
            $logoPathRel = $oldData['logo'];
            $faviconPathRel = $oldData['favicon'];

            if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
                $logoFolder = $rootFolder . 'logo/';
                if (!is_dir($logoFolder)) {
                    mkdir($logoFolder, 0777, true);
                }
                $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
                $allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'ico'];
                if (!in_array($ext, $allowedExt)) {
                    echo json_encode(['status' => 'error', 'message' => "Invalid logo file type"]);
                    exit();
                }
                $newLogoName = uniqid('logo_') . '.' . $ext;
                $logoFullPath = $logoFolder . $newLogoName;
                $logoPathRel = 'Images/logo/' . $newLogoName;
                if (move_uploaded_file($_FILES['logo']['tmp_name'], $logoFullPath)) {
                    if (!empty($oldData['logo']) && file_exists(__DIR__ . '/../../' . $oldData['logo'])) {
                        unlink(__DIR__ . '/../../../' . $oldData['logo']);
                    }
                } else {
                    echo json_encode(['status' => 'error', 'message' => "Failed to upload logo"]);
                    exit();
                }
            }

            if (isset($_FILES['favicon']) && $_FILES['favicon']['error'] === UPLOAD_ERR_OK) {
                $faviconFolder = $rootFolder . 'favicon/';
                if (!is_dir($faviconFolder)) {
                    mkdir($faviconFolder, 0777, true);
                }
                $ext = strtolower(pathinfo($_FILES['favicon']['name'], PATHINFO_EXTENSION));
                if (!in_array($ext, $allowedExt)) {
                    echo json_encode(['status' => 'error', 'message' => "Invalid favicon file type"]);
                    exit();
                }
                $newFaviconName = uniqid('favicon_') . '.' . $ext;
                $faviconFullPath = $faviconFolder . $newFaviconName;
                $faviconPathRel = 'Images/favicon/' . $newFaviconName;
                if (move_uploaded_file($_FILES['favicon']['tmp_name'], $faviconFullPath)) {
                    if (!empty($oldData['favicon']) && file_exists(__DIR__ . '/../../' . $oldData['favicon'])) {
                        unlink(__DIR__ . '/../../../' . $oldData['favicon']);
                    }
                } else {
                    echo json_encode(['status' => 'error', 'message' => "Failed to upload favicon"]);
                    exit();
                }
            }

            $sql = "UPDATE configuration SET 
                        title = :title,
                        description = :description,
                        logo = :logo,
                        favicon = :favicon,
                        telegram = :telegram,
                        facebook = :facebook,
                        whatsapp = :whatsapp,
                        livechat = :livechat,
                        livechat_js = :livechat_js,
                        theme = :theme,
                        maintenance = :maintenance
                    WHERE id = 1";
            $stmt = $db->prepare($sql);
            $stmt->bindParam(':title', $title);
            $stmt->bindParam(':description', $description);
            $stmt->bindParam(':logo', $logoPathRel);
            $stmt->bindParam(':favicon', $faviconPathRel);
            $stmt->bindParam(':telegram', $telegram);
            $stmt->bindParam(':facebook', $facebook);
            $stmt->bindParam(':whatsapp', $whatsapp);
            $stmt->bindParam(':livechat', $livechat);
            $stmt->bindParam(':livechat_js', $livechat_js);
            $stmt->bindParam(':theme', $theme);
            $stmt->bindParam(':maintenance', $maintenance);
            if ($stmt->execute()) {
                echo json_encode(['status' => 'success', 'message' => "Data berhasil diperbarui."]);
            } else {
                echo json_encode(['status' => 'error', 'message' => "Gagal memperbarui data."]);
            }
            break;

        case 'seo':
            $canonical = htmlspecialchars($_POST['canonical'] ?? '');
            $amp = htmlspecialchars($_POST['amp'] ?? '');
            $seo = htmlspecialchars($_POST['seo'] ?? '');
            $keyword = htmlspecialchars($_POST['keyword'] ?? '');
            $sql = "UPDATE configuration SET 
                        canonical = :canonical, 
                        amp = :amp, 
                        seo = :seo, 
                        keyword = :keyword
                    WHERE id = 1";
            $stmt = $db->prepare($sql);
            $stmt->bindParam(':canonical', $canonical);
            $stmt->bindParam(':amp', $amp);
            $stmt->bindParam(':seo', $seo);
            $stmt->bindParam(':keyword', $keyword);
            if ($stmt->execute()) {
                echo json_encode(['status' => 'success', 'message' => "SEO data berhasil diperbarui."]);
            } else {
                echo json_encode(['status' => 'error', 'message' => "Gagal memperbarui SEO data."]);
            }
            break;

        default:
            echo json_encode(['status' => 'error', 'message' => "Invalid action!"]);
            break;
    }
}
?>
