<?php
/**
 * AJAX handler for seat card logo upload/remove
 * Called from seat_card_grid.php via fetch()
 */
session_start();
header('Content-Type: application/json; charset=utf-8');

$action = isset($_POST['action']) ? $_POST['action'] : '';

if ($action === 'upload') {
    if (!isset($_FILES['logo_file']) || $_FILES['logo_file']['error'] !== UPLOAD_ERR_OK) {
        $code = isset($_FILES['logo_file']) ? $_FILES['logo_file']['error'] : -1;
        echo json_encode(['ok' => false, 'msg' => 'ফাইল পাওয়া যায়নি বা এরর কোড: '.$code]);
        exit;
    }

    $tmp  = $_FILES['logo_file']['tmp_name'];
    $name = $_FILES['logo_file']['name'];
    $size = $_FILES['logo_file']['size'];
    $ext  = strtolower(pathinfo($name, PATHINFO_EXTENSION));

    $extAllowed = ['png','jpg','jpeg','svg','webp'];

    if ($size > 2 * 1024 * 1024) {
        echo json_encode(['ok' => false, 'msg' => 'ফাইল সাইজ ২MB-এর বেশি।']);
        exit;
    }
    if (!in_array($ext, $extAllowed, true)) {
        echo json_encode(['ok' => false, 'msg' => 'শুধু PNG, JPG, SVG, WebP সমর্থিত। আপলোড করা এক্সটেনশন: .'.$ext]);
        exit;
    }

    $diskDir = realpath(__DIR__.'/..').'/uploads/temp/seat_cards';
    if (!is_dir($diskDir)) {
        if (!@mkdir($diskDir, 0777, true)) {
            echo json_encode(['ok' => false, 'msg' => 'ডিরেক্টরি তৈরি করা যায়নি: '.$diskDir]);
            exit;
        }
    }

    // Delete old file
    if (!empty($_SESSION['seat_logo_url'])) {
        $oldPath = $_SESSION['seat_logo_url']; // e.g. ../uploads/temp/seat_cards/logo_xxx.png
        $oldFile = realpath(__DIR__.'/../uploads/temp/seat_cards/'.basename($oldPath));
        if ($oldFile && file_exists($oldFile)) { @unlink($oldFile); }
    }

    $safe = 'logo_'.date('Ymd_His').'_'.bin2hex(random_bytes(4)).'.'.$ext;
    $dest = $diskDir.'/'.$safe;

    if (!@move_uploaded_file($tmp, $dest)) {
        echo json_encode(['ok' => false, 'msg' => 'ফাইল সেভ করা যায়নি। ডিরেক্টরি permission চেক করুন: '.$diskDir]);
        exit;
    }

    $webPath = '../uploads/temp/seat_cards/'.$safe;
    $_SESSION['seat_logo_url']  = $webPath;
    // Auto-set mode to centered if currently none
    if (empty($_SESSION['seat_logo_mode']) || $_SESSION['seat_logo_mode'] === 'none') {
        $_SESSION['seat_logo_mode'] = 'centered';
    }

    echo json_encode(['ok' => true, 'url' => $webPath, 'msg' => 'লোগো সফলভাবে আপলোড হয়েছে।']);
    exit;
}

if ($action === 'remove') {
    if (!empty($_SESSION['seat_logo_url'])) {
        $oldFile = realpath(__DIR__.'/../uploads/temp/seat_cards/'.basename($_SESSION['seat_logo_url']));
        if ($oldFile && file_exists($oldFile)) { @unlink($oldFile); }
    }
    unset($_SESSION['seat_logo_url']);
    unset($_SESSION['seat_logo_mode']);
    echo json_encode(['ok' => true, 'msg' => 'লোগো সরানো হয়েছে।']);
    exit;
}

echo json_encode(['ok' => false, 'msg' => 'অজানা action।']);
