<?php
/**
 * ============================================================
 * ADMIN AJAX: Update Product
 * ============================================================
 * Updates existing product with optional new images
 */

// 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 ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

// Must be admin
if (!isAdminLoggedIn()) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'অ্যাডমিন লগইন প্রয়োজন']);
    exit;
}

// 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
$existingProduct = ProductService::getById($productId);
if (!$existingProduct) {
    Response::notFound('পণ্য পাওয়া যায়নি');
}

// Get data
$data = [
    'category_id' => (int)post('category_id'),
    'name' => sanitize(post('name')),
    'sku' => sanitize(post('sku')),
    'short_description' => sanitize(post('short_description')),
    'description' => post('description'),
    'price' => (float)post('price'),
    'sale_price' => post('sale_price') ? (float)post('sale_price') : null,
    'stock_qty' => (int)post('stock_qty'),
    'is_active' => post('is_active') ? 1 : 0,
    'is_featured' => post('is_featured') ? 1 : 0,
    'meta_title' => sanitize(post('meta_title')),
    'meta_description' => sanitize(post('meta_description'))
];

// Validate
$validator = Validator::make($data);
$validator->required('category_id', 'ক্যাটাগরি')
          ->required('name', 'পণ্যের নাম')
          ->minLength('name', 3, 'পণ্যের নাম')
          ->required('price', 'দাম')
          ->min('price', 1, 'দাম')
          ->min('stock_qty', 0, 'স্টক');

if ($validator->fails()) {
    Response::validationError($validator->errors());
}

// Update product
try {
    Database::beginTransaction();
    
    ProductService::update($productId, $data);
    
    // Handle new image uploads
    if (!empty($_FILES['images']) && $_FILES['images']['error'][0] !== UPLOAD_ERR_NO_FILE) {
        $uploader = new Upload();
        $uploadPath = 'products/' . date('Y/m');
        
        $uploadedFiles = $uploader->multiple($_FILES['images'], $uploadPath);
        
        if ($uploader->hasErrors()) {
            logError('Product image upload errors', $uploader->getErrors());
        }
        
        // Check if product has any images
        $hasImages = !empty($existingProduct['images']);
        
        foreach ($uploadedFiles as $index => $filename) {
            ProductService::addImage(
                $productId,
                date('Y/m') . '/' . $filename,
                !$hasImages && $index === 0 // Set first as primary if no existing images
            );
        }
    }
    
    // Handle image deletions
    $deleteImages = post('delete_images');
    if (!empty($deleteImages) && is_array($deleteImages)) {
        foreach ($deleteImages as $imageId) {
            ProductService::deleteImage((int)$imageId);
        }
    }
    
    // Handle primary image change
    $primaryImageId = (int)post('primary_image_id');
    if ($primaryImageId > 0) {
        ProductService::setPrimaryImage($productId, $primaryImageId);
    }
    
    Database::commit();
    
    Response::success('পণ্য সফলভাবে আপডেট হয়েছে', [
        'product_id' => $productId
    ]);
    
} catch (Exception $e) {
    Database::rollback();
    logError('Product update failed', ['error' => $e->getMessage()]);
    Response::serverError('পণ্য আপডেটে সমস্যা হয়েছে');
}
