<?php
require_once '../includes/auth.php';
requirePermission('clients', 'edit');
require_once '../db.php';

// Handle bulk save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $ids    = $_POST['id']     ?? [];
    $gstins = $_POST['gstin']  ?? [];
    $codes  = $_POST['state_code'] ?? [];

    $saved = 0;
    foreach ($ids as $i => $id) {
        $id    = (int)$id;
        $gstin = strtoupper(trim($gstins[$i] ?? ''));
        $sc    = trim($codes[$i] ?? '');
        if ($id <= 0) continue;

        $stmt = $conn->prepare("UPDATE clients SET gstin = ?, state_code = ? WHERE id = ? AND company_id = ? AND customer_type = 'B2B'");
        $stmt->bind_param("ssii", $gstin, $sc, $id, $cid);
        $stmt->execute();
        if ($stmt->affected_rows > 0) $saved++;
    }

    header("Location: fix_gstin.php?saved=" . $saved);
    exit;
}

$saved = (int)($_GET['saved'] ?? -1);

// Load B2B clients with empty GSTIN
$res = $conn->query("SELECT id, name, phone, city, state FROM clients WHERE company_id = $cid AND customer_type = 'B2B' AND (gstin IS NULL OR gstin = '') AND status = 1 ORDER BY name");
$clients = [];
while ($r = $res->fetch_assoc()) $clients[] = $r;

require_once '../includes/header.php';
require_once '../includes/sidebar.php';
?>

<div class="page-header">
    <h2><i class="fas fa-id-card" style="color:var(--primary);margin-right:8px;"></i>Fix Missing GSTIN — B2B Clients</h2>
    <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back to Clients</a>
</div>

<?php if ($saved >= 0): ?>
<div class="alert alert-success" style="background:#dcfce7;border:1px solid #86efac;color:#166534;padding:12px 16px;border-radius:8px;margin-bottom:16px;">
    <i class="fas fa-check-circle"></i>
    <?= $saved ?> client(s) updated successfully.
    <?php if (count($clients) === 0): ?>
        All B2B clients now have GSTIN filled.
    <?php endif; ?>
</div>
<?php endif; ?>

<?php if (empty($clients)): ?>
<div class="panel">
    <div class="panel-body" style="text-align:center;padding:48px;color:var(--text-muted);">
        <i class="fas fa-check-circle" style="font-size:40px;color:var(--success);margin-bottom:12px;display:block;"></i>
        All B2B clients have GSTIN filled. Nothing to fix.
    </div>
</div>
<?php else: ?>

<div class="panel" style="margin-bottom:12px;background:#fffbeb;border-left:4px solid #f59e0b;">
    <div class="panel-body" style="padding:12px 16px;font-size:13px;color:#92400e;">
        <i class="fas fa-triangle-exclamation"></i>
        <strong><?= count($clients) ?> B2B client(s)</strong> have no GSTIN saved due to a previous form bug.
        Enter their GSTIN below and click <strong>Save All</strong>.
        Clients without GSTIN will not appear in the GSTR-1 B2B report.
    </div>
</div>

<form method="POST">
<div class="panel">
    <div class="panel-header">
        <span class="panel-title">B2B Clients — Missing GSTIN</span>
        <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-save"></i> Save All</button>
    </div>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Client Name</th>
                    <th>Phone</th>
                    <th>City / State</th>
                    <th>GSTIN <span style="color:var(--danger);">*</span></th>
                    <th style="width:90px;">State Code</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($clients as $i => $c): ?>
            <tr>
                <td style="color:var(--text-muted);font-size:12px;"><?= $i + 1 ?></td>
                <td><strong><?= htmlspecialchars($c['name']) ?></strong></td>
                <td style="color:var(--text-muted);"><?= htmlspecialchars($c['phone'] ?? '') ?></td>
                <td style="font-size:12px;color:var(--text-muted);"><?= htmlspecialchars(trim(($c['city'] ?? '') . ', ' . ($c['state'] ?? ''), ', ')) ?></td>
                <td>
                    <input type="hidden" name="id[]" value="<?= $c['id'] ?>">
                    <input type="text" name="gstin[]" id="gstin_<?= $i ?>"
                           maxlength="15" placeholder="15-digit GSTIN"
                           style="text-transform:uppercase;width:180px;font-family:monospace;letter-spacing:1px;"
                           oninput="this.value=this.value.toUpperCase(); autoFillState(<?= $i ?>);">
                </td>
                <td>
                    <input type="text" name="state_code[]" id="sc_<?= $i ?>"
                           maxlength="2" placeholder="e.g. 29"
                           style="width:70px;text-align:center;">
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div style="padding:12px 16px;border-top:1px solid var(--border);">
        <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save All</button>
        <span style="margin-left:12px;font-size:12px;color:var(--text-muted);">Rows with empty GSTIN will be saved as empty (skip them if you don't have the info yet).</span>
    </div>
</div>
</form>

<script>
const GST_STATES = {
    '01':'Jammu & Kashmir','02':'Himachal Pradesh','03':'Punjab','04':'Chandigarh',
    '05':'Uttarakhand','06':'Haryana','07':'Delhi','08':'Rajasthan','09':'Uttar Pradesh',
    '10':'Bihar','11':'Sikkim','12':'Arunachal Pradesh','13':'Nagaland','14':'Manipur',
    '15':'Mizoram','16':'Tripura','17':'Meghalaya','18':'Assam','19':'West Bengal',
    '20':'Jharkhand','21':'Odisha','22':'Chhattisgarh','23':'Madhya Pradesh','24':'Gujarat',
    '26':'Dadra & Nagar Haveli','27':'Maharashtra','29':'Karnataka','30':'Goa',
    '31':'Lakshadweep','32':'Kerala','33':'Tamil Nadu','34':'Puducherry',
    '35':'Andaman & Nicobar Islands','36':'Telangana','37':'Andhra Pradesh',
    '38':'Ladakh','97':'Other Territory'
};
function autoFillState(i) {
    const gstin = document.getElementById('gstin_' + i).value;
    const sc = gstin.substring(0, 2);
    if (gstin.length >= 2 && GST_STATES[sc]) {
        document.getElementById('sc_' + i).value = sc;
    } else if (gstin.length < 2) {
        document.getElementById('sc_' + i).value = '';
    }
}
</script>
<?php endif; ?>

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