<?php
/**
 * ICV (Invoice Counter Value) Generator API
 * فوترة بلس - POS System
 * 
 * Generates and increments ICV counter for sellers
 */

require_once 'db.php';

// Only allow GET or POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Method not allowed', null, 405);
}

// Get seller_id from query or body
$sellerId = $_GET['seller_id'] ?? '';
if (empty($sellerId) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = getJsonInput();
    $sellerId = $input['seller_id'] ?? '';
}

if (empty($sellerId)) {
    jsonResponse(false, 'seller_id is required', null, 400);
}

try {
    global $pdo;
    
    // Begin transaction
    $pdo->beginTransaction();
    
    // Get current ICV counter with lock
    $stmt = $pdo->prepare("SELECT current_icv_counter FROM sellers WHERE id = ? FOR UPDATE");
    $stmt->execute([$sellerId]);
    $result = $stmt->fetch();
    
    if (!$result) {
        $pdo->rollBack();
        jsonResponse(false, 'Seller not found', null, 404);
    }
    
    $currentICV = $result['current_icv_counter'] ?? 0;
    $newICV = $currentICV + 1;
    
    // Update the counter
    $stmt = $pdo->prepare("UPDATE sellers SET current_icv_counter = ?, updated_at = ? WHERE id = ?");
    $stmt->execute([$newICV, getCurrentTimestamp(), $sellerId]);
    
    // Commit transaction
    $pdo->commit();
    
    jsonResponse(true, 'ICV generated', [
        'icv' => (string)$newICV,
        'previous_icv' => (string)$currentICV
    ]);
    
} catch (PDOException $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    jsonResponse(false, 'Failed to generate ICV: ' . $e->getMessage(), null, 500);
}
?>
