<?php
/**
 * Invoice Number Generator API
 * فوترة بلس - POS System
 * 
 * Generates unique invoice numbers 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;
    
    // Get seller details
    $stmt = $pdo->prepare("SELECT * FROM sellers WHERE id = ? LIMIT 1");
    $stmt->execute([$sellerId]);
    $seller = $stmt->fetch();
    
    if (!$seller) {
        jsonResponse(false, 'Seller not found', null, 404);
    }
    
    // Get current count of invoices for this seller
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM invoices WHERE seller_id = ?");
    $stmt->execute([$sellerId]);
    $result = $stmt->fetch();
    $totalInvoices = $result['count'];
    
    // Get starting number
    $startingNumber = $seller['starting_number'] ?? 1;
    
    // Generate username prefix
    $username = $seller['username'] ?? 'USR';
    $usernamePrefix = strtoupper(substr(preg_replace('/[^A-Za-z]/', '', $username), 0, 3));
    if (strlen($usernamePrefix) < 3) {
        $usernamePrefix = str_pad($usernamePrefix, 3, 'X');
    }
    if (empty($usernamePrefix)) {
        $usernamePrefix = 'USR';
    }
    
    // Generate date in DDMMYY format
    $dateFormatted = date('dmy');
    
    // Calculate new invoice number
    $newInvoiceNumber = $startingNumber + $totalInvoices + 1;
    
    // Generate the invoice number format: PREFIX-DDMMYY-EIN-NUMBER
    $invoiceNumber = $usernamePrefix . '-' . $dateFormatted . '-EIN-' . $newInvoiceNumber;
    
    jsonResponse(true, 'Invoice number generated', [
        'invoice_number' => $invoiceNumber,
        'sequence_number' => $newInvoiceNumber,
        'total_invoices' => $totalInvoices
    ]);
    
} catch (PDOException $e) {
    jsonResponse(false, 'Failed to generate invoice number: ' . $e->getMessage(), null, 500);
}
?>
