<?php
/**
 * ============================================================
 *  বধুবরণ জুয়েলার্স ERP — Sales Module
 *  File: api/sales/get_next_invoice_no.php
 *  Date: 2026-05-16
 *
 *  পরবর্তী invoice number কেমন হবে তা preview করে (UI-এর জন্য)।
 *  Note: এটা actual increment করে না — শুধু preview।
 *        Actual invoice number generate হয় create_sale.php-এ।
 *
 *  Response:
 *  {
 *    "ok": true,
 *    "year": 2026,
 *    "last_number": 5,
 *    "next_number": 6,
 *    "preview": "INV-2026-0006"
 *  }
 * ============================================================
 */

require_once __DIR__ . '/../_core.php';
header('Content-Type: application/json; charset=utf-8');

if (!is_logged_in()) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'লগইন করুন']);
    exit;
}

$year = (int)date('Y');

try {
    $stmt = $pdo->prepare("SELECT last_number FROM sale_invoice_sequence WHERE year = ?");
    $stmt->execute([$year]);
    $row  = $stmt->fetch(PDO::FETCH_ASSOC);
    $last = $row ? (int)$row['last_number'] : 0;
    $next = $last + 1;
    $preview = sprintf('INV-%d-%04d', $year, $next);

    echo json_encode([
        'ok'          => true,
        'year'        => $year,
        'last_number' => $last,
        'next_number' => $next,
        'preview'     => $preview
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}