<?php
require_once '../includes/auth.php';
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $prefix = $_POST['prefix'];
    $type = $_POST['type'];
    $fy = $_POST['financial_year'];
    $start = (int)$_POST['current_no'];

    $stmt = $conn->prepare("INSERT INTO invoice_sequences (prefix, type, financial_year, current_no)
                             VALUES (?, ?, ?, ?)
                             ON DUPLICATE KEY UPDATE current_no = VALUES(current_no)");
    $stmt->bind_param("sssi", $prefix, $type, $fy, $start);
    $stmt->execute();
}

$list = $conn->query("SELECT * FROM invoice_sequences ORDER BY financial_year DESC, type");
?>

<div class="main-content">
<h2>Invoice Number Sequence Master</h2>

<form method="post">
    <label>Prefix</label>
    <input type="text" name="prefix" value="MSH" required>

    <label>Type</label>
    <select name="type">
        <option value="B2C">B2C</option>
        <option value="B2B">B2B</option>
    </select>

    <label>Financial Year</label>
    <input type="text" name="financial_year" placeholder="25-26" required>

    <label>Current Number</label>
    <input type="number" name="current_no" required>

    <button type="submit">Save / Update</button>
</form>

<hr>

<table class="list-table">
<tr>
    <th>Prefix</th>
    <th>Type</th>
    <th>Financial Year</th>
    <th>Current No</th>
</tr>
<?php while($r = $list->fetch_assoc()): ?>
<tr>
    <td><?= $r['prefix'] ?></td>
    <td><?= $r['type'] ?></td>
    <td><?= $r['financial_year'] ?></td>
    <td><?= $r['current_no'] ?></td>
</tr>
<?php endwhile; ?>
</table>
</div>

<?php require_once '../includes/footer.php'; ?>
