<?php
/**
 * ============================================================
 * ADMIN AJAX: Upload Product Images
 * ============================================================
 * Handles multiple image upload for products
 */

// Initialize
define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once BASE_PATH . '/app/config/config.php';
require_once APP_PATH . '/core/upload.php';

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

// Must be POST
if (!isPost()) {
    Response::error('Invalid request', [], 400);
}

// Validate CSRF
if (!csrf_validate()) {
    Response::csrfError();
}

// Must be admin
if (!isAdminLoggedIn()) {
    Response::unauthorized('অ্যাডমিন লগইন প্রয়োজন');
}

// Load service
require_once APP_PATH . '/services/product_service.php';

// Get product ID
$productId = (int)post('product_id');

if ($productId < 1) {
    Response::error('অবৈধ পণ্য');
}

// Check product exists
$product = ProductService::getById($productId);
if (!$product) {
    Response::notFound('পণ্য পাওয়া যায়নি');
}

// Check if files uploaded
if (empty($_FILES['images'])) {
    Response::error('কোনো ছবি সিলেক্ট করা হয়নি');
}

// Check max images limit
$currentImageCount = count($product['images']);
$newImageCount = count(array_filter($_FILES['images']['error'], fn($e) => $e !== UPLOAD_ERR_NO_FILE));

if ($currentImageCount + $newImageCount > MAX_PRODUCT_IMAGES) {
    Response::error('সর্বোচ্চ ' . MAX_PRODUCT_IMAGES . 'টি ছবি আপলোড করা যাবে');
}

// Upload images
$uploader = new Upload();
$uploadPath = 'products/' . date('Y/m');

$uploadedFiles = $uploader->multiple($_FILES['images'], $uploadPath);

if (empty($uploadedFiles)) {
    Response::error($uploader->getFirstError() ?? 'ছবি আপলোড ব্যর্থ হয়েছে');
}

// Add images to product
$addedImages = [];
$hasImages = !empty($product['images']);

foreach ($uploadedFiles as $index => $filename) {
    $filePath = date('Y/m') . '/' . $filename;
    $imageId = ProductService::addImage(
        $productId,
        $filePath,
        !$hasImages && $index === 0 // Set first as primary if no existing images
    );
    
    $addedImages[] = [
        'id' => $imageId,
        'file_path' => $filePath,
        'url' => UPLOADS_URL . '/products/' . $filePath
    ];
    
    $hasImages = true;
}

$message = count($addedImages) . 'টি ছবি আপলোড হয়েছে';

if ($uploader->hasErrors()) {
    $message .= ' (' . count($uploader->getErrors()) . 'টি ব্যর্থ)';
}

Response::success($message, [
    'images' => $addedImages,
    'errors' => $uploader->getErrors()
]);
