<?php

$sliderFile = 'slider_images.json';
$uploadsDir = 'uploads/';

// If slider JSON file doesn't exist, create it
if (!file_exists($sliderFile)) {
    file_put_contents($sliderFile, json_encode([
        'interval' => 3000,
        'news' => 'আজ লাইভ দেখুন আমাদের অ্যাপে !',
        'images' => []
    ], JSON_PRETTY_PRINT));
}

// If uploads directory doesn't exist, create it
if (!file_exists($uploadsDir)) {
    mkdir($uploadsDir, 0777, true);
}

$data = json_decode(file_get_contents($sliderFile), true);
$action = $_GET['action'] ?? '';

if ($action === 'upload') {
    if (!isset($_FILES["photo"])) {
        echo json_encode(['error' => 'No file uploaded']);
        exit;
    }

    $id = uniqid();
    $fileName = $id . "_" . basename($_FILES["photo"]["name"]);
    $targetPath = $uploadsDir . $fileName;

    if (move_uploaded_file($_FILES["photo"]["tmp_name"], $targetPath)) {
        $image = [
            'id' => $id,
            'url' => $targetPath,
            'status' => 'unpublished',
            'created_at' => date('Y-m-d H:i:s')
        ];
        $data['images'][] = $image;
        file_put_contents($sliderFile, json_encode($data, JSON_PRETTY_PRINT));
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['error' => 'File upload failed']);
    }

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

    foreach ($data['images'] as &$image) {
        if ($image['id'] === $id) {
            $image['status'] = $status;
            break;
        }
    }

    file_put_contents($sliderFile, json_encode($data, JSON_PRETTY_PRINT));
    echo json_encode(['success' => true]);

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

    foreach ($data['images'] as $image) {
        if ($image['id'] === $id) {
            // Try deleting image file if it exists
            if (file_exists($image['url'])) {
                unlink($image['url']);
            }
            continue; // Skip adding this image
        }
        $newImages[] = $image;
    }

    $data['images'] = $newImages;
    file_put_contents($sliderFile, json_encode($data, JSON_PRETTY_PRINT));
    echo json_encode(['success' => true]);

} elseif ($action === 'list') {
    echo json_encode($data);

} elseif ($action === 'save_config') {
    $speed = intval($_POST['speed'] ?? 3000);
    $newsText = trim($_POST['newsText'] ?? '');
    $data['interval'] = $speed;
    $data['news'] = $newsText;
    file_put_contents($sliderFile, json_encode($data, JSON_PRETTY_PRINT));
    echo json_encode(['success' => true]);
}
