<?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'];
    $rootFolder = __DIR__ . '/../../../Images/banner/';
    if (!is_dir($rootFolder)) {
        mkdir($rootFolder, 0777, true);
    }

    function uploadBannerImage($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('banner_') . '.' . $ext;
        $fullPath = $rootFolder . $newName;
        $relativePath = 'Images/banner/' . $newName;

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

    if ($action === 'add') {
        $title = trim($_POST['title'] ?? '');
        $imagePath = null;

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

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

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

    } elseif ($action === 'edit') {
        $id = $_POST['id'] ?? '';
        $title = trim($_POST['title'] ?? '');
        $status = isset($_POST['status']) ? 1 : 0;
        $imagePath = null;

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

            $upload = uploadBannerImage($_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 banner SET title = :title, status = :status, updated_at = NOW()";
        if ($imagePath) {
            $sql .= ", image = :image";
        }
        $sql .= " WHERE id = :id";

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

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

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

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

        $sql = "DELETE FROM banner 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' => 'Banner berhasil dihapus.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal menghapus banner.']);
        }
    }
}
?>
