<?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 = htmlspecialchars($_POST['title'] ?? '');
    $description = htmlspecialchars($_POST['description'] ?? '');
    $status = isset($_POST['status']) ? 1 : 0;

    $rootFolder = __DIR__ . '/../../../Images/promotion/';
    if (!is_dir($rootFolder)) {
        mkdir($rootFolder, 0777, true);
    }

    function uploadImage($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('promo_') . '.' . $ext;
        $fullPath = $rootFolder . $newName;
        $relativePath = 'Images/promotion/' . $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 = uploadImage($_FILES['image']);
            if (isset($upload['error'])) {
                echo json_encode(['status' => 'error', 'message' => $upload['error']]);
                exit();
            }
            $imagePath = $upload['path'];
        }

        $sql = "INSERT INTO promotion (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' => 'Promo berhasil ditambahkan.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal menambahkan promo.']);
        }

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

        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            // Ambil gambar lama
            $stmtOld = $db->prepare("SELECT image FROM promotion WHERE id = :id");
            $stmtOld->bindParam(':id', $id);
            $stmtOld->execute();
            $oldData = $stmtOld->fetch(PDO::FETCH_ASSOC);

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

            // Hapus file lama
            if (!empty($oldData['image']) && file_exists(__DIR__ . '/../../../' . $oldData['image'])) {
                unlink(__DIR__ . '/../../../' . $oldData['image']);
            }
        }

        $sql = "UPDATE promotion 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' => 'Promo berhasil diperbarui.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal memperbarui promo.']);
        }

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

        // Ambil gambar lama
        $stmtOld = $db->prepare("SELECT image FROM promotion WHERE id = :id");
        $stmtOld->bindParam(':id', $id);
        $stmtOld->execute();
        $oldData = $stmtOld->fetch(PDO::FETCH_ASSOC);

        // Hapus dari database
        $sql = "DELETE FROM promotion WHERE id = :id";
        $stmt = $db->prepare($sql);
        $stmt->bindParam(':id', $id);

        if ($stmt->execute()) {
            // Hapus file lama
            if (!empty($oldData['image']) && file_exists(__DIR__ . '/../../../' . $oldData['image'])) {
                unlink(__DIR__ . '/../../../' . $oldData['image']);
            }
            echo json_encode(['status' => 'success', 'message' => 'Promo berhasil dihapus.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal menghapus promo.']);
        }
    }
}
?>
