<?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'];
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $status = isset($_POST['status']) ? 1 : 0;
    $rootFolder = __DIR__ . '/../../../Images/popup/';
    if (!is_dir($rootFolder)) {
        mkdir($rootFolder, 0777, true);
    }

    function uploadPopupImage($file) {
        global $rootFolder;
        $allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedExt)) {
            return ['error' => "Invalid file type."];
        }
        $newName = uniqid('popup_') . '.' . $ext;
        $fullPath = $rootFolder . $newName;
        $relativePath = 'Images/popup/' . $newName;

        if (move_uploaded_file($file['tmp_name'], $fullPath)) {
            return ['path' => $relativePath];
        } else {
            return ['error' => "Failed to upload file."];
        }
    }

    if ($action === 'add') {
        $imagePath = null;

        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $upload = uploadPopupImage($_FILES['image']);
            if (isset($upload['error'])) {
                echo json_encode(['status' => 'error', 'message' => $upload['error']]);
                exit();
            }
            $imagePath = $upload['path'];
        }

        $sql = "INSERT INTO popup (title, image, description, status, created_at) 
                VALUES (:title, :image, :description, :status, NOW())";
        $stmt = $db->prepare($sql);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':image', $imagePath);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':status', $status);

        if ($stmt->execute()) {
            echo json_encode(['status' => 'success', 'message' => 'Popup berhasil ditambahkan.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal menambahkan popup.']);
        }

    } elseif ($action === 'edit') {
        $id = $_POST['id'] ?? '';
        $imagePath = null;

        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $stmtOld = $db->prepare("SELECT image FROM popup WHERE id = :id");
            $stmtOld->bindParam(':id', $id);
            $stmtOld->execute();
            $oldImage = $stmtOld->fetchColumn();

            $upload = uploadPopupImage($_FILES['image']);
            if (isset($upload['error'])) {
                echo json_encode(['status' => 'error', 'message' => $upload['error']]);
                exit();
            }
            $imagePath = $upload['path'];

            if (!empty($oldImage) && file_exists(__DIR__ . '/../../../' . $oldImage)) {
                unlink(__DIR__ . '/../../../' . $oldImage);
            }
        }

        $sql = "UPDATE popup SET title = :title, description = :description, status = :status, updated_at = NOW()";
        if ($imagePath) {
            $sql .= ", image = :image";
        }
        $sql .= " WHERE id = :id";

        $stmt = $db->prepare($sql);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':status', $status);
        $stmt->bindParam(':id', $id);
        if ($imagePath) {
            $stmt->bindParam(':image', $imagePath);
        }

        if ($stmt->execute()) {
            echo json_encode(['status' => 'success', 'message' => 'Popup berhasil diperbarui.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal memperbarui popup.']);
        }

    } elseif ($action === 'delete') {
        $id = $_POST['id'] ?? '';

        $stmt = $db->prepare("SELECT image FROM popup WHERE id = :id");
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        $oldImage = $stmt->fetchColumn();

        $sql = "DELETE FROM popup WHERE id = :id";
        $stmt = $db->prepare($sql);
        $stmt->bindParam(':id', $id);

        if ($stmt->execute()) {
            if (!empty($oldImage) && file_exists(__DIR__ . '/../../../' . $oldImage)) {
                unlink(__DIR__ . '/../../../' . $oldImage);
            }
            echo json_encode(['status' => 'success', 'message' => 'Popup berhasil dihapus.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal menghapus popup.']);
        }
    }
}
?>
