<?php
require_once __DIR__ . '/../../includes/functions.php';
requireLogin();

// ── Handle Document Delete ────────────────────────────────────
if (isset($_GET['action']) && $_GET['action'] === 'delete_doc' && isset($_GET['doc_id'])) {
    $docId = (int)$_GET['doc_id'];
    $stmt = $pdo->prepare("SELECT * FROM vendor_documents WHERE id=?");
    $stmt->execute([$docId]);
    $doc = $stmt->fetch();
    if ($doc) {
        if (file_exists(__DIR__ . '/../../' . $doc['file_path'])) {
            unlink(__DIR__ . '/../../' . $doc['file_path']);
        }
        $pdo->prepare("DELETE FROM vendor_documents WHERE id=?")->execute([$docId]);
        setFlash('success', 'Document deleted.');
    }
    header('Location: purchase_vendors.php?view=' . ($doc['vendor_id'] ?? '')); exit;
}

// ── Handle Create / Update (with file uploads) ────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger', 'Invalid request token.');
        header('Location: purchase_vendors.php'); exit;
    }

    $data = [
        'company_name'   => trim($_POST['company_name'] ?? ''),
        'vendor_name'    => trim($_POST['vendor_name']),
        'contact_person' => trim($_POST['contact_person']),
        'phone'          => trim($_POST['phone']),
        'alt_phone'      => trim($_POST['alt_phone']),
        'email'          => trim($_POST['email']),
        'gst_number'     => trim($_POST['gst_number']),
        'pan_no'         => trim($_POST['pan_no'] ?? ''),
        'address'        => trim($_POST['address']),
        'city'           => trim($_POST['city']),
        'state'          => trim($_POST['state']),
        'pincode'        => trim($_POST['pincode']),
        'bank_name'      => trim($_POST['bank_name']),
        'bank_account_no'=> trim($_POST['bank_account_no']),
        'bank_ifsc'      => trim($_POST['bank_ifsc']),
        'opening_balance'=> (float)($_POST['opening_balance'] ?? 0),
        'vendor_rating'  => max(1, min(5, (int)($_POST['vendor_rating'] ?? 3))),
        'notes'          => trim($_POST['notes']),
    ];

    if ($_POST['action'] === 'create') {
        $count = $pdo->query("SELECT COUNT(*) c FROM purchase_vendors")->fetch()['c'] + 1;
        $data['vendor_code'] = 'PV' . str_pad($count, 4, '0', STR_PAD_LEFT);

        $stmt = $pdo->prepare("INSERT INTO purchase_vendors
            (vendor_code, company_name, vendor_name, contact_person, phone, alt_phone, email,
             gst_number, pan_no, address, city, state, pincode, bank_name, bank_account_no,
             bank_ifsc, opening_balance, vendor_rating, notes)
            VALUES (:vendor_code,:company_name,:vendor_name,:contact_person,:phone,:alt_phone,
                    :email,:gst_number,:pan_no,:address,:city,:state,:pincode,:bank_name,
                    :bank_account_no,:bank_ifsc,:opening_balance,:vendor_rating,:notes)");
        $stmt->execute($data);
        $vendorId = $pdo->lastInsertId();
        setFlash('success', 'Purchase vendor created successfully.');

    } elseif ($_POST['action'] === 'update') {
        $vendorId = (int)$_POST['id'];
        $data['id'] = $vendorId;
        $stmt = $pdo->prepare("UPDATE purchase_vendors SET
            company_name=:company_name, vendor_name=:vendor_name, contact_person=:contact_person,
            phone=:phone, alt_phone=:alt_phone, email=:email, gst_number=:gst_number,
            pan_no=:pan_no, address=:address, city=:city, state=:state, pincode=:pincode,
            bank_name=:bank_name, bank_account_no=:bank_account_no, bank_ifsc=:bank_ifsc,
            opening_balance=:opening_balance, vendor_rating=:vendor_rating, notes=:notes
            WHERE id=:id");
        $stmt->execute($data);
        setFlash('success', 'Purchase vendor updated successfully.');
    }

    // Handle multiple document uploads
    if (!empty($_FILES['doc_files']['name'][0])) {
        $allowedTypes = ['application/pdf','image/jpeg','image/png','image/jpg'];
        $docTypes = $_POST['doc_types'] ?? [];
        $docNames = $_POST['doc_names'] ?? [];

        foreach ($_FILES['doc_files']['name'] as $idx => $fileName) {
            if (empty($fileName)) continue;
            $fileType = $_FILES['doc_files']['type'][$idx];
            $tmpPath  = $_FILES['doc_files']['tmp_name'][$idx];
            $docType  = $docTypes[$idx] ?? 'other';
            $docLabel = trim($docNames[$idx] ?? '') ?: pathinfo($fileName, PATHINFO_FILENAME);

            if (!in_array($fileType, $allowedTypes)) continue;

            $ext      = pathinfo($fileName, PATHINFO_EXTENSION);
            $saveName = 'vendor_' . $vendorId . '_' . time() . '_' . $idx . '.' . $ext;
            $savePath = 'uploads/vendor_docs/' . $saveName;
            $fullPath = __DIR__ . '/../../' . $savePath;

            if (move_uploaded_file($tmpPath, $fullPath)) {
                $pdo->prepare("INSERT INTO vendor_documents (vendor_id, doc_type, doc_name, file_path)
                               VALUES (?,?,?,?)")
                    ->execute([$vendorId, $docType, $docLabel, $savePath]);
            }
        }
    }

    header('Location: purchase_vendors.php'); exit;
}

// Toggle status / Delete
if (isset($_GET['action'])) {
    if ($_GET['action'] === 'toggle' && isset($_GET['id'])) {
        $pdo->prepare("UPDATE purchase_vendors SET status = 1-status WHERE id=?")->execute([(int)$_GET['id']]);
        setFlash('success', 'Vendor status updated.');
        header('Location: purchase_vendors.php'); exit;
    }
    if ($_GET['action'] === 'delete' && isset($_GET['id'])) {
        $id = (int)$_GET['id'];
        $check = $pdo->prepare("SELECT COUNT(*) c FROM purchases WHERE vendor_id=?");
        $check->execute([$id]);
        if ($check->fetch()['c'] > 0) {
            setFlash('danger', 'Cannot delete: vendor has purchase records. Deactivate instead.');
        } else {
            // Delete documents from disk
            $docs = $pdo->prepare("SELECT file_path FROM vendor_documents WHERE vendor_id=?");
            $docs->execute([$id]);
            foreach ($docs->fetchAll() as $d) {
                $fp = __DIR__ . '/../../' . $d['file_path'];
                if (file_exists($fp)) unlink($fp);
            }
            $pdo->prepare("DELETE FROM purchase_vendors WHERE id=?")->execute([$id]);
            setFlash('success', 'Vendor deleted successfully.');
        }
        header('Location: purchase_vendors.php'); exit;
    }
}

// Search
$search = trim($_GET['search'] ?? '');
$where  = '';
$params = [];
if ($search) {
    $where  = "WHERE vendor_name LIKE ? OR company_name LIKE ? OR vendor_code LIKE ? OR phone LIKE ? OR gst_number LIKE ?";
    $params = ["%$search%","%$search%","%$search%","%$search%","%$search%"];
}
$stmt = $pdo->prepare("SELECT * FROM purchase_vendors $where ORDER BY id DESC");
$stmt->execute($params);
$vendors = $stmt->fetchAll();

// View single vendor detail
$viewVendor = null;
$viewDocs   = [];
if (isset($_GET['view'])) {
    $stmt = $pdo->prepare("SELECT * FROM purchase_vendors WHERE id=?");
    $stmt->execute([(int)$_GET['view']]);
    $viewVendor = $stmt->fetch();
    if ($viewVendor) {
        $stmt = $pdo->prepare("SELECT * FROM vendor_documents WHERE vendor_id=? ORDER BY id DESC");
        $stmt->execute([(int)$_GET['view']]);
        $viewDocs = $stmt->fetchAll();
    }
}

$editVendor = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM purchase_vendors WHERE id=?");
    $stmt->execute([(int)$_GET['edit']]);
    $editVendor = $stmt->fetch();
}

$csrf = generateCSRFToken();

function starRating($n) {
    $out = '';
    for ($i=1;$i<=5;$i++) {
        $out .= $i<=$n ? '★' : '☆';
    }
    return $out;
}

// All redirect logic above is done - safe to render layout now
$pageTitle = 'Purchase Vendors';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <div class="eyebrow">Parties</div>
        <h2 class="mb-0">Purchase Vendors</h2>
    </div>
    <div class="flex gap-8">
        <form method="GET" class="flex gap-8">
            <input type="text" name="search" placeholder="Search vendors..." value="<?= sanitize($search) ?>" style="width:220px">
            <button class="btn btn-icon" title="Search" style="width:38px;height:38px;"><?= icon('search') ?></button>
        </form>
        <button class="btn btn-primary" onclick="openVendorModal()"><?= icon('plus') ?> Add Vendor</button>
    </div>
</div>

<?php if ($viewVendor): ?>
<!-- ── VENDOR DETAIL VIEW ─────────────────────────────────── -->
<div class="card">
    <div class="card-title flex-between">
        <span><?= icon('truck-delivery') ?> <?= sanitize($viewVendor['vendor_name']) ?>
            <?php if ($viewVendor['company_name']): ?>
            <span class="text-muted text-sm"> · <?= sanitize($viewVendor['company_name']) ?></span>
            <?php endif; ?>
        </span>
        <div class="flex gap-8">
            <button class="btn btn-sm" onclick='editVendor(<?= json_encode($viewVendor) ?>)'><?= icon('edit') ?> Edit</button>
            <a href="purchase_vendors.php" class="btn btn-sm"><?= icon('arrow-left') ?> Back</a>
        </div>
    </div>

    <div class="form-grid">
        <div><div class="text-sm text-muted">Vendor Code</div><strong class="mono"><?= sanitize($viewVendor['vendor_code']) ?></strong></div>
        <div><div class="text-sm text-muted">Company</div><?= sanitize($viewVendor['company_name']) ?: '-' ?></div>
        <div><div class="text-sm text-muted">Rating</div><span style="color:#c9622a;font-size:18px;"><?= starRating($viewVendor['vendor_rating']) ?></span></div>
        <div><div class="text-sm text-muted">Contact Person</div><?= sanitize($viewVendor['contact_person']) ?: '-' ?></div>
        <div><div class="text-sm text-muted">Phone</div><?= sanitize($viewVendor['phone']) ?: '-' ?></div>
        <div><div class="text-sm text-muted">Alt Phone</div><?= sanitize($viewVendor['alt_phone']) ?: '-' ?></div>
        <div><div class="text-sm text-muted">Email</div><?= sanitize($viewVendor['email']) ?: '-' ?></div>
        <div><div class="text-sm text-muted">City / State</div><?= sanitize($viewVendor['city']) ?>, <?= sanitize($viewVendor['state']) ?></div>
        <div><div class="text-sm text-muted">Opening Balance</div><strong class="mono"><?= formatMoney($viewVendor['opening_balance']) ?></strong></div>
    </div>

    <div class="divider"></div>
    <div class="form-grid">
        <div>
            <div class="text-sm text-muted" style="font-weight:700;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px">Legal & Compliance</div>
            <table style="font-size:13px; border:none;">
                <tr><td class="text-muted" style="padding:3px 16px 3px 0;">GSTIN</td><td class="mono"><strong><?= sanitize($viewVendor['gst_number']) ?: '—' ?></strong></td></tr>
                <tr><td class="text-muted" style="padding:3px 16px 3px 0;">PAN No.</td><td class="mono"><strong><?= sanitize($viewVendor['pan_no']) ?: '—' ?></strong></td></tr>
            </table>
        </div>
        <div>
            <div class="text-sm text-muted" style="font-weight:700;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px">Bank Details</div>
            <table style="font-size:13px; border:none;">
                <tr><td class="text-muted" style="padding:3px 16px 3px 0;">Bank</td><td><?= sanitize($viewVendor['bank_name']) ?: '—' ?></td></tr>
                <tr><td class="text-muted" style="padding:3px 16px 3px 0;">Account</td><td class="mono"><?= sanitize($viewVendor['bank_account_no']) ?: '—' ?></td></tr>
                <tr><td class="text-muted" style="padding:3px 16px 3px 0;">IFSC</td><td class="mono"><?= sanitize($viewVendor['bank_ifsc']) ?: '—' ?></td></tr>
            </table>
        </div>
    </div>
</div>

<!-- Documents -->
<div class="card">
    <div class="card-title flex-between">
        <span><?= icon('files') ?> Documents</span>
        <button class="btn btn-sm btn-primary" onclick="document.getElementById('uploadDocModal').classList.add('show')"><?= icon('upload') ?> Upload Document</button>
    </div>
    <?php if ($viewDocs): ?>
    <div class="table-wrap">
        <table>
            <thead><tr><th>Document Name</th><th>Type</th><th>Uploaded</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach ($viewDocs as $doc): ?>
            <tr>
                <td><?= sanitize($doc['doc_name']) ?></td>
                <td><span class="badge badge-info"><?= str_replace('_',' ', strtoupper($doc['doc_type'])) ?></span></td>
                <td><?= formatDateTime($doc['uploaded_at']) ?></td>
                <td>
                    <div class="flex gap-8">
                        <a href="<?= APP_URL ?>/<?= sanitize($doc['file_path']) ?>" target="_blank" class="btn btn-sm btn-success"><?= icon('download') ?> View/Download</a>
                        <a href="?delete_doc=1&doc_id=<?= $doc['id'] ?>&action=delete_doc" class="btn btn-sm btn-danger" onclick="return confirm('Delete this document?')"><?= icon('trash') ?></a>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state" style="padding:24px;"><?= icon('file-off') ?> No documents uploaded yet.</div>
    <?php endif; ?>
</div>

<!-- Upload Document Modal -->
<div class="modal-backdrop" id="uploadDocModal">
    <div class="modal">
        <div class="modal-header">
            <h2>Upload Document</h2>
            <button class="btn btn-icon" onclick="document.getElementById('uploadDocModal').classList.remove('show')"><?= icon('x') ?></button>
        </div>
        <form method="POST" enctype="multipart/form-data" id="docUploadForm">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="action" value="update">
            <input type="hidden" name="id" value="<?= $viewVendor['id'] ?>">
            <!-- Pass all existing required fields as hidden to not overwrite -->
            <input type="hidden" name="company_name" value="<?= sanitize($viewVendor['company_name']) ?>">
            <input type="hidden" name="vendor_name" value="<?= sanitize($viewVendor['vendor_name']) ?>">
            <input type="hidden" name="contact_person" value="<?= sanitize($viewVendor['contact_person']) ?>">
            <input type="hidden" name="phone" value="<?= sanitize($viewVendor['phone']) ?>">
            <input type="hidden" name="alt_phone" value="<?= sanitize($viewVendor['alt_phone']) ?>">
            <input type="hidden" name="email" value="<?= sanitize($viewVendor['email']) ?>">
            <input type="hidden" name="gst_number" value="<?= sanitize($viewVendor['gst_number']) ?>">
            <input type="hidden" name="pan_no" value="<?= sanitize($viewVendor['pan_no']) ?>">
            <input type="hidden" name="address" value="<?= sanitize($viewVendor['address']) ?>">
            <input type="hidden" name="city" value="<?= sanitize($viewVendor['city']) ?>">
            <input type="hidden" name="state" value="<?= sanitize($viewVendor['state']) ?>">
            <input type="hidden" name="pincode" value="<?= sanitize($viewVendor['pincode']) ?>">
            <input type="hidden" name="bank_name" value="<?= sanitize($viewVendor['bank_name']) ?>">
            <input type="hidden" name="bank_account_no" value="<?= sanitize($viewVendor['bank_account_no']) ?>">
            <input type="hidden" name="bank_ifsc" value="<?= sanitize($viewVendor['bank_ifsc']) ?>">
            <input type="hidden" name="opening_balance" value="<?= $viewVendor['opening_balance'] ?>">
            <input type="hidden" name="vendor_rating" value="<?= $viewVendor['vendor_rating'] ?>">
            <input type="hidden" name="notes" value="<?= sanitize($viewVendor['notes']) ?>">

            <div id="docLines">
                <div class="doc-line" style="border:1px solid var(--color-border);border-radius:8px;padding:12px;margin-bottom:12px;">
                    <div class="form-group">
                        <label>Document Type</label>
                        <select name="doc_types[]">
                            <option value="gstin_certificate">GSTIN Certificate</option>
                            <option value="pan_card">PAN Card</option>
                            <option value="other">Other Document</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Document Label</label>
                        <input type="text" name="doc_names[]" placeholder="e.g. GSTIN Certificate 2024">
                    </div>
                    <div class="form-group">
                        <label>File (PDF, JPG, PNG) <span class="req">*</span></label>
                        <input type="file" name="doc_files[]" accept=".pdf,.jpg,.jpeg,.png" required>
                    </div>
                </div>
            </div>
            <button type="button" class="btn btn-sm" onclick="addDocLine()"><?= icon('plus') ?> Add Another File</button>

            <div class="flex-end gap-8 mt-16">
                <button type="button" class="btn" onclick="document.getElementById('uploadDocModal').classList.remove('show')">Cancel</button>
                <button type="submit" class="btn btn-primary"><?= icon('upload') ?> Upload</button>
            </div>
        </form>
    </div>
</div>

<?php else: ?>
<!-- ── VENDOR LIST ─────────────────────────────────────────── -->
<div class="card">
    <?php if ($vendors): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Code</th><th>Company / Vendor Name</th><th>Contact</th><th>Phone</th>
                    <th>GSTIN</th><th>PAN</th><th>Rating</th><th>Status</th><th>Actions</th></tr>
            </thead>
            <tbody>
            <?php foreach ($vendors as $v): ?>
            <tr>
                <td class="mono"><?= sanitize($v['vendor_code']) ?></td>
                <td>
                    <strong><?= sanitize($v['vendor_name']) ?></strong>
                    <?php if ($v['company_name']): ?><div class="text-sm text-muted"><?= sanitize($v['company_name']) ?></div><?php endif; ?>
                </td>
                <td><?= sanitize($v['contact_person']) ?: '-' ?></td>
                <td><?= sanitize($v['phone']) ?: '-' ?></td>
                <td class="mono"><?= sanitize($v['gst_number']) ?: '-' ?></td>
                <td class="mono"><?= sanitize($v['pan_no']) ?: '-' ?></td>
                <td style="color:#c9622a;"><?= starRating($v['vendor_rating'] ?? 3) ?></td>
                <td><span class="badge badge-<?= $v['status']?'success':'muted' ?>"><?= $v['status']?'Active':'Inactive' ?></span></td>
                <td>
                    <div class="flex gap-8">
                        <a href="?view=<?= $v['id'] ?>" class="btn btn-icon btn-sm" title="View Details"><?= icon('eye') ?></a>
                        <button class="btn btn-icon btn-sm" title="Edit" onclick='editVendor(<?= json_encode($v) ?>)'><?= icon('edit') ?></button>
                        <a href="?action=toggle&id=<?= $v['id'] ?>" class="btn btn-icon btn-sm" title="Toggle Status"><?= icon('power') ?></a>
                        <a href="?action=delete&id=<?= $v['id'] ?>" class="btn btn-icon btn-sm" title="Delete" onclick="return confirm('Delete this vendor?')"><?= icon('trash') ?></a>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('truck-delivery') ?> No purchase vendors yet.</div>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- ── ADD / EDIT VENDOR MODAL ────────────────────────────── -->
<div class="modal-backdrop" id="vendorModal">
    <div class="modal modal-lg" style="max-width:800px;">
        <div class="modal-header">
            <h2 id="modalTitle">Add Purchase Vendor</h2>
            <button class="btn btn-icon" onclick="closeVendorModal()"><?= icon('x') ?></button>
        </div>
        <form method="POST" id="vendorForm" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="action" id="formAction" value="create">
            <input type="hidden" name="id" id="vendorId">

            <!-- Tab Nav -->
            <div class="flex gap-8" style="margin-bottom:16px;border-bottom:1px solid var(--color-border);padding-bottom:8px;">
                <button type="button" class="btn btn-sm tab-btn active" onclick="showTab('tab-basic')">Basic</button>
                <button type="button" class="btn btn-sm tab-btn" onclick="showTab('tab-legal')">Legal &amp; Compliance</button>
                <button type="button" class="btn btn-sm tab-btn" onclick="showTab('tab-bank')">Bank</button>
                <button type="button" class="btn btn-sm tab-btn" onclick="showTab('tab-docs')" id="docsTabBtn">Documents</button>
            </div>

            <!-- TAB: Basic -->
            <div id="tab-basic" class="tab-panel">
                <fieldset><legend>Company &amp; Contact</legend>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Company Name</label>
                            <input type="text" name="company_name" id="company_name" placeholder="Registered company name">
                        </div>
                        <div class="form-group">
                            <label>Vendor / Contact Name <span class="req">*</span></label>
                            <input type="text" name="vendor_name" id="vendor_name" required>
                        </div>
                        <div class="form-group">
                            <label>Contact Person</label>
                            <input type="text" name="contact_person" id="contact_person">
                        </div>
                        <div class="form-group">
                            <label>Phone <span class="req">*</span></label>
                            <input type="tel" name="phone" id="phone" required>
                        </div>
                        <div class="form-group">
                            <label>Alternate Phone</label>
                            <input type="tel" name="alt_phone" id="alt_phone">
                        </div>
                        <div class="form-group">
                            <label>Email</label>
                            <input type="email" name="email" id="email">
                        </div>
                        <div class="form-group full">
                            <label>Vendor Rating</label>
                            <div class="flex gap-8" style="align-items:center;">
                                <input type="range" name="vendor_rating" id="vendor_rating" min="1" max="5" value="3" oninput="updateRating(this.value)" style="width:160px;">
                                <span id="ratingDisplay" style="font-size:22px;color:#c9622a;">★★★☆☆</span>
                                <span id="ratingLabel" class="text-sm text-muted">3 / 5</span>
                            </div>
                        </div>
                    </div>
                </fieldset>
                <fieldset><legend>Address</legend>
                    <div class="form-grid">
                        <div class="form-group full">
                            <label>Address</label>
                            <textarea name="address" id="address" rows="2"></textarea>
                        </div>
                        <div class="form-group"><label>City</label><input type="text" name="city" id="city"></div>
                        <div class="form-group"><label>State</label><input type="text" name="state" id="state"></div>
                        <div class="form-group"><label>Pincode</label><input type="text" name="pincode" id="pincode"></div>
                    </div>
                </fieldset>
                <div class="form-group">
                    <label>Opening Balance (Payable to vendor)</label>
                    <input type="number" step="0.01" name="opening_balance" id="opening_balance" value="0">
                </div>
                <div class="form-group">
                    <label>Notes</label>
                    <textarea name="notes" id="notes" rows="2"></textarea>
                </div>
            </div>

            <!-- TAB: Legal & Compliance -->
            <div id="tab-legal" class="tab-panel" style="display:none;">
                <fieldset><legend>Legal &amp; Compliance</legend>
                    <div class="alert alert-info" style="margin-bottom:14px;">
                        <?= icon('shield-check') ?> Enter official registration details. Upload GSTIN Certificate and PAN Card in the Documents tab.
                    </div>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>GSTIN Number</label>
                            <input type="text" name="gst_number" id="gst_number" placeholder="e.g. 33XXXXXXXXXXXZX" maxlength="15" style="text-transform:uppercase;">
                            <div class="text-sm text-faint">15-digit GST Identification Number</div>
                        </div>
                        <div class="form-group">
                            <label>PAN Number</label>
                            <input type="text" name="pan_no" id="pan_no" placeholder="e.g. ABCDE1234F" maxlength="10" style="text-transform:uppercase;">
                            <div class="text-sm text-faint">10-character Permanent Account Number</div>
                        </div>
                    </div>
                </fieldset>
            </div>

            <!-- TAB: Bank -->
            <div id="tab-bank" class="tab-panel" style="display:none;">
                <fieldset><legend>Bank Details</legend>
                    <div class="form-grid">
                        <div class="form-group"><label>Bank Name</label><input type="text" name="bank_name" id="bank_name"></div>
                        <div class="form-group"><label>Account Number</label><input type="text" name="bank_account_no" id="bank_account_no"></div>
                        <div class="form-group"><label>IFSC Code</label><input type="text" name="bank_ifsc" id="bank_ifsc"></div>
                    </div>
                </fieldset>
            </div>

            <!-- TAB: Documents (only for edit/create-after-save) -->
            <div id="tab-docs" class="tab-panel" style="display:none;">
                <div class="alert alert-info">
                    <?= icon('info-circle') ?>
                    <span id="docInfoNew">Documents can be uploaded after saving the vendor. Save first, then use the "Upload Document" button on the vendor detail page.</span>
                    <span id="docInfoEdit" style="display:none;">You can upload documents here. Existing documents are managed from the vendor detail page.</span>
                </div>
                <div id="docUploadArea" style="display:none;">
                    <div id="modalDocLines">
                        <div class="doc-line" style="border:1px solid var(--color-border);border-radius:8px;padding:12px;margin-bottom:10px;">
                            <div class="form-grid">
                                <div class="form-group">
                                    <label>Type</label>
                                    <select name="doc_types[]">
                                        <option value="gstin_certificate">GSTIN Certificate</option>
                                        <option value="pan_card">PAN Card</option>
                                        <option value="other">Other</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>Label</label>
                                    <input type="text" name="doc_names[]" placeholder="e.g. GSTIN Certificate">
                                </div>
                                <div class="form-group full">
                                    <label>File (PDF, JPG, PNG)</label>
                                    <input type="file" name="doc_files[]" accept=".pdf,.jpg,.jpeg,.png">
                                </div>
                            </div>
                        </div>
                    </div>
                    <button type="button" class="btn btn-sm" onclick="addModalDocLine()"><?= icon('plus') ?> Add Another File</button>
                </div>
            </div>

            <div class="flex-end gap-8 mt-16">
                <button type="button" class="btn" onclick="closeVendorModal()">Cancel</button>
                <button type="submit" class="btn btn-primary"><?= icon('check') ?> Save Vendor</button>
            </div>
        </form>
    </div>
</div>

<style>
.tab-btn.active { background:var(--color-primary);color:#fff;border-color:var(--color-primary); }
</style>
<script>
function showTab(id) {
    document.querySelectorAll('.tab-panel').forEach(p => p.style.display='none');
    document.getElementById(id).style.display='block';
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    event.target.classList.add('active');
}
function openVendorModal() {
    document.getElementById('modalTitle').textContent = 'Add Purchase Vendor';
    document.getElementById('formAction').value = 'create';
    document.getElementById('vendorForm').reset();
    document.getElementById('vendorId').value = '';
    document.getElementById('docInfoNew').style.display = 'inline';
    document.getElementById('docInfoEdit').style.display = 'none';
    document.getElementById('docUploadArea').style.display = 'none';
    updateRating(3);
    showTabByName('tab-basic');
    document.getElementById('vendorModal').classList.add('show');
}
function closeVendorModal() { document.getElementById('vendorModal').classList.remove('show'); }
function showTabByName(id) {
    document.querySelectorAll('.tab-panel').forEach(p => p.style.display='none');
    document.getElementById(id).style.display='block';
    document.querySelectorAll('.tab-btn').forEach((b,i) => {
        b.classList.toggle('active', ['tab-basic','tab-legal','tab-bank','tab-docs'][i]===id);
    });
}
function updateRating(val) {
    const stars = ['','★☆☆☆☆','★★☆☆☆','★★★☆☆','★★★★☆','★★★★★'];
    document.getElementById('ratingDisplay').textContent = stars[val] || '★★★☆☆';
    document.getElementById('ratingLabel').textContent = val + ' / 5';
}
function editVendor(v) {
    document.getElementById('modalTitle').textContent = 'Edit Vendor';
    document.getElementById('formAction').value = 'update';
    document.getElementById('vendorId').value = v.id;
    document.getElementById('company_name').value = v.company_name || '';
    document.getElementById('vendor_name').value = v.vendor_name || '';
    document.getElementById('contact_person').value = v.contact_person || '';
    document.getElementById('phone').value = v.phone || '';
    document.getElementById('alt_phone').value = v.alt_phone || '';
    document.getElementById('email').value = v.email || '';
    document.getElementById('gst_number').value = v.gst_number || '';
    document.getElementById('pan_no').value = v.pan_no || '';
    document.getElementById('address').value = v.address || '';
    document.getElementById('city').value = v.city || '';
    document.getElementById('state').value = v.state || '';
    document.getElementById('pincode').value = v.pincode || '';
    document.getElementById('bank_name').value = v.bank_name || '';
    document.getElementById('bank_account_no').value = v.bank_account_no || '';
    document.getElementById('bank_ifsc').value = v.bank_ifsc || '';
    document.getElementById('opening_balance').value = v.opening_balance || 0;
    document.getElementById('vendor_rating').value = v.vendor_rating || 3;
    document.getElementById('notes').value = v.notes || '';
    updateRating(v.vendor_rating || 3);
    document.getElementById('docInfoNew').style.display = 'none';
    document.getElementById('docInfoEdit').style.display = 'inline';
    document.getElementById('docUploadArea').style.display = 'block';
    showTabByName('tab-basic');
    document.getElementById('vendorModal').classList.add('show');
}
function addDocLine() {
    const clone = document.querySelector('#docLines .doc-line').cloneNode(true);
    clone.querySelectorAll('input,select').forEach(el => el.value = '');
    document.getElementById('docLines').appendChild(clone);
}
function addModalDocLine() {
    const clone = document.querySelector('#modalDocLines .doc-line').cloneNode(true);
    clone.querySelectorAll('input,select').forEach(el => el.value = '');
    document.getElementById('modalDocLines').appendChild(clone);
}
<?php if ($editVendor): ?>
editVendor(<?= json_encode($editVendor) ?>);
<?php endif; ?>
</script>

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