<?php
/**
 * API: Get Next Invoice Number Based on Sales Type
 * Returns the next invoice number with appropriate prefix based on sales type
 */

header('Content-Type: application/json');
session_start();
include_once('../../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Get sales type from request
$salesType = isset($_GET['salesType']) ? $_GET['salesType'] : 'GST';

// Validate sales type
$validTypes = ['GST', 'NON-GST', 'ONLINE'];
if (!in_array($salesType, $validTypes)) {
    echo json_encode(['success' => false, 'message' => 'Invalid sales type']);
    exit();
}

try {
    // Get invoice prefix for the sales type
    $prefixQuery = "SELECT InvoicePrefix FROM tblsales_type_config WHERE SalesType = ? AND IsActive = 1";
    $stmt = mysqli_prepare($con, $prefixQuery);
    mysqli_stmt_bind_param($stmt, 's', $salesType);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if (mysqli_num_rows($result) == 0) {
        echo json_encode(['success' => false, 'message' => 'Sales type configuration not found']);
        exit();
    }
    
    $config = mysqli_fetch_assoc($result);
    $prefix = $config['InvoicePrefix'];
    
    // Generate financial year format: GST/2025-26/0001
    // Financial year: April to March
    $currentMonth = date('n'); // 1-12
    $currentYear = date('Y');
    if ($currentMonth >= 4) {
        // April onwards - current year to next year
        $financialYear = $currentYear . '-' . substr($currentYear + 1, 2);
    } else {
        // January to March - previous year to current year
        $financialYear = ($currentYear - 1) . '-' . substr($currentYear, 2);
    }
    
    $datePrefix = $prefix . '/' . $financialYear . '/';
    
    // Get last invoice number with this prefix
    $lastInvoiceQuery = "SELECT InvoiceNumber FROM tblsales 
                        WHERE InvoiceNumber LIKE ? 
                        AND SalesType = ?
                        ORDER BY ID DESC LIMIT 1";
    
    $stmt = mysqli_prepare($con, $lastInvoiceQuery);
    $searchPattern = $datePrefix . '%';
    mysqli_stmt_bind_param($stmt, 'ss', $searchPattern, $salesType);
    mysqli_stmt_execute($stmt);
    $lastResult = mysqli_stmt_get_result($stmt);
    
    if (mysqli_num_rows($lastResult) > 0) {
        $lastInvoice = mysqli_fetch_assoc($lastResult)['InvoiceNumber'];
        // Extract the last number and increment
        $lastNumber = intval(substr($lastInvoice, -4));
        $newNumber = $lastNumber + 1;
    } else {
        $newNumber = 1;
    }
    
    // Generate new invoice number with 4-digit padding
    $invoiceNumber = $datePrefix . str_pad($newNumber, 4, '0', STR_PAD_LEFT);
    
    echo json_encode([
        'success' => true,
        'invoiceNumber' => $invoiceNumber,
        'salesType' => $salesType,
        'prefix' => $prefix
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error generating invoice number: ' . $e->getMessage()
    ]);
}
?>
