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

// ── One-time schema migration ─────────────────────────────────────────────────
// The old UNIQUE KEY was (prefix, type, financial_year) — missing company_id.
// This caused INSERT conflicts for multi-company setups and the settings page
// was not saving company_id at all (defaulting to 0).
// We fix the key here so it is idempotent: errors mean it is already correct.
try {
    $conn->query("ALTER TABLE invoice_sequences DROP INDEX `prefix`");
} catch (Throwable $e) { /* already dropped or renamed — safe to ignore */ }
try {
    $conn->query("ALTER TABLE invoice_sequences ADD UNIQUE KEY `uniq_seq` (`company_id`,`prefix`,`type`,`financial_year`)");
} catch (Throwable $e) { /* already exists — safe to ignore */ }
// ─────────────────────────────────────────────────────────────────────────────

$msg = '';

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

    if ($coid <= 0 || $prefix === '' || $fy === '') {
        $msg = '<div class="alert alert-danger">Company, prefix, and financial year are required.</div>';
    } else {
        $stmt = $conn->prepare("
            INSERT INTO invoice_sequences (company_id, prefix, type, financial_year, current_no)
            VALUES (?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE current_no = VALUES(current_no)
        ");
        $stmt->bind_param("isssi", $coid, $prefix, $type, $fy, $start);
        $stmt->execute();
        $msg = '<div class="alert alert-success">Sequence saved.</div>';
    }
}

$companies = $conn->query("SELECT id, company_name, invoice_prefix FROM company_master ORDER BY company_name");
$companyList = [];
while ($c = $companies->fetch_assoc()) $companyList[] = $c;

$list = $conn->query("
    SELECT s.*, COALESCE(cm.company_name, '(unknown)') AS company_name
    FROM invoice_sequences s
    LEFT JOIN company_master cm ON cm.id = s.company_id
    ORDER BY s.financial_year DESC, company_name, s.type
");
?>

<div class="page-header">
    <h2><i class="fas fa-list-ol" style="color:var(--primary);margin-right:8px;"></i>Invoice Number Sequences</h2>
</div>

<?= $msg ?>

<div class="panel" style="margin-bottom:20px;">
    <div class="panel-header"><span class="panel-title">Add / Update Sequence</span></div>
    <div class="panel-body">
        <form method="post">
            <div class="form-row">
                <div class="form-group" style="flex:2;min-width:200px;">
                    <label>Company <span style="color:var(--danger)">*</span></label>
                    <select name="company_id" id="seqCompany" onchange="fillPrefix()" required style="width:100%;">
                        <option value="">— select —</option>
                        <?php foreach ($companyList as $co): ?>
                        <option value="<?= $co['id'] ?>"
                                data-prefix="<?= htmlspecialchars($co['invoice_prefix'] ?? '') ?>">
                            <?= htmlspecialchars($co['company_name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Prefix <span style="color:var(--danger)">*</span></label>
                    <input type="text" name="prefix" id="seqPrefix" maxlength="10"
                           style="text-transform:uppercase;width:100px;" required>
                </div>
                <div class="form-group">
                    <label>Type</label>
                    <select name="type" style="width:90px;">
                        <option value="B2B">B2B</option>
                        <option value="B2C">B2C</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Financial Year <span style="color:var(--danger)">*</span></label>
                    <input type="text" name="financial_year" placeholder="26-27" maxlength="9"
                           style="width:90px;" required>
                </div>
                <div class="form-group">
                    <label>Start From (current no)</label>
                    <input type="number" name="current_no" value="0" min="0" style="width:100px;" required>
                </div>
                <div class="form-group" style="align-self:flex-end;">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Save / Update
                    </button>
                </div>
            </div>
        </form>
        <p style="font-size:12px;color:var(--text-muted);margin-top:4px;">
            <i class="fas fa-info-circle"></i>
            "Current No" is the last number used. Set to 0 to start from 1, or set to 49 so the next invoice is /50.
            B2B is auto-selected for clients with a GSTIN; B2C for clients without.
        </p>
    </div>
</div>

<div class="panel">
    <div class="panel-header"><span class="panel-title">Existing Sequences</span></div>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Company</th>
                    <th>Prefix</th>
                    <th>Type</th>
                    <th>Financial Year</th>
                    <th style="text-align:right;">Current No</th>
                    <th>Next Invoice No</th>
                </tr>
            </thead>
            <tbody>
            <?php while ($r = $list->fetch_assoc()): ?>
            <tr>
                <td><?= htmlspecialchars($r['company_name']) ?></td>
                <td><code><?= htmlspecialchars($r['prefix']) ?></code></td>
                <td>
                    <span class="badge <?= $r['type'] === 'B2B' ? 'badge-primary' : 'badge-gray' ?>">
                        <?= $r['type'] ?>
                    </span>
                </td>
                <td><?= htmlspecialchars($r['financial_year']) ?></td>
                <td style="text-align:right;"><?= (int)$r['current_no'] ?></td>
                <td style="color:var(--text-muted);font-size:12px;">
                    <?= htmlspecialchars($r['prefix']) ?>/<?= $r['type'] ?>/<?= htmlspecialchars($r['financial_year']) ?>/<?= (int)$r['current_no'] + 1 ?>
                </td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
function fillPrefix() {
    const sel = document.getElementById('seqCompany');
    const opt = sel.options[sel.selectedIndex];
    const p   = opt ? (opt.dataset.prefix || '') : '';
    document.getElementById('seqPrefix').value = p.toUpperCase();
}
</script>

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