<?php
/**
 * ADMIN AJAX: Create Product
 */
header('Content-Type: application/json; charset=utf-8');

try {
    // 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') {
        echo json_encode(['success' => false, 'message' => 'Invalid request']);
        exit;
    }
    
    // Must be admin
    if (!isAdminLoggedIn()) {
        echo json_encode(['success' => false, 'message' => 'অ্যাডমিন লগইন প্রয়োজন']);
        exit;
    }

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

// 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'), // Allow HTML
    '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());
}

// Validate category exists
$categoryExists = Database::fetchColumn(
    "SELECT id FROM categories WHERE id = ?",
    [$data['category_id']]
);

if (!$categoryExists) {
    Response::error('অবৈধ ক্যাটাগরি');
}

// Create product
try {
    Database::beginTransaction();
    
    $productId = ProductService::create($data);
    
    // Handle 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()) {
            // Log errors but continue (product created, images failed)
            logError('Product image upload errors', $uploader->getErrors());
        }
        
        // Add images to product
        $isFirst = true;
        foreach ($uploadedFiles as $filename) {
            ProductService::addImage(
                $productId,
                date('Y/m') . '/' . $filename,
                $isFirst // First image is primary
            );
            $isFirst = false;
        }
    }
    
    Database::commit();
    
    Response::success('পণ্য সফলভাবে তৈরি হয়েছে', [
        'product_id' => $productId
    ]);
    
} catch (Exception $e) {
    if (Database::inTransaction()) Database::rollback();
    echo json_encode(['success' => false, 'message' => 'পণ্য তৈরিতে সমস্যা: ' . $e->getMessage()]);
}

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'ত্রুটি: ' . $e->getMessage()]);
}
