<?php
/**
 * ============================================================
 * ADMIN AJAX: Update Promo Code
 * ============================================================
 */

// Initialize
define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once BASE_PATH . '/app/config/config.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/promo_service.php';

// Get promo ID
$promoId = (int)post('promo_id');

if ($promoId < 1) {
    Response::error('অবৈধ প্রোমো কোড');
}

// Get data
$data = [
    'code' => sanitize(post('code')),
    'description' => sanitize(post('description')),
    'discount_type' => sanitize(post('discount_type')),
    'discount_value' => (float)post('discount_value'),
    'min_order_amount' => (float)post('min_order_amount'),
    'max_discount_amount' => post('max_discount_amount') ? (float)post('max_discount_amount') : null,
    'usage_limit' => post('usage_limit') ? (int)post('usage_limit') : null,
    'starts_at' => post('starts_at') ?: null,
    'expires_at' => post('expires_at') ?: null,
    'is_active' => post('is_active') ? 1 : 0
];

// Validate
$validator = Validator::make($data);
$validator->required('code', 'প্রোমো কোড')
          ->minLength('code', 3, 'প্রোমো কোড')
          ->required('discount_type', 'ডিসকাউন্ট টাইপ')
          ->in('discount_type', ['percent', 'fixed'], 'ডিসকাউন্ট টাইপ')
          ->required('discount_value', 'ডিসকাউন্ট পরিমাণ')
          ->min('discount_value', 1, 'ডিসকাউন্ট পরিমাণ');

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

// Update promo code
$updated = PromoService::update($promoId, $data);

if ($updated) {
    Response::success('প্রোমো কোড আপডেট হয়েছে');
} else {
    Response::error('এই কোড অন্য প্রোমোতে ব্যবহৃত হয়েছে');
}
