<?php
require_once '../includes/auth.php';
requirePermission('vendors', 'edit');
require_once '../db.php';
$id = (int)$_GET['id'];
$vendor = $conn->query("SELECT * FROM vendors WHERE id = $id AND company_id = $cid")->fetch_assoc();
if (!$vendor) die('Vendor not found');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name            = trim($_POST['name']);
    $contact_person  = trim($_POST['contact_person'] ?? '');
    $phone           = trim($_POST['phone'] ?? '');
    $mobile          = trim($_POST['mobile'] ?? '');
    $email           = trim($_POST['email'] ?? '');
    $gstin           = strtoupper(trim($_POST['gstin'] ?? ''));
    $state_code      = trim($_POST['state_code'] ?? '');
    $state           = trim($_POST['state'] ?? '');
    $address         = trim($_POST['address'] ?? '');
    $pincode         = trim($_POST['pincode'] ?? '');
    $city            = trim($_POST['city'] ?? '');
    $opening_balance = (float)($_POST['opening_balance'] ?? 0);
    $stmt = $conn->prepare("
        UPDATE vendors SET
        name=?, contact_person=?, phone=?, mobile=?, email=?,
        gstin=?, state_code=?, state=?, address=?, pincode=?, city=?, opening_balance=?
        WHERE id=?
    ");
    $stmt->bind_param("sssssssssssdi",
        $name, $contact_person, $phone, $mobile, $email,
        $gstin, $state_code, $state, $address, $pincode, $city, $opening_balance, $id
    );
    $stmt->execute();
    header("Location: index.php"); exit;
}
require_once '../includes/header.php';
require_once '../includes/sidebar.php';
?>

<div class="page-header">
    <h2><i class="fas fa-edit" style="color:var(--primary);margin-right:8px;"></i>Edit Vendor</h2>
    <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
</div>

<form method="post">
<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;max-width:960px;">

    <!-- Left Column -->
    <div>
        <div class="panel" style="margin-bottom:16px;">
            <div class="panel-header">
                <span class="panel-title"><i class="fas fa-building" style="color:var(--primary);margin-right:7px;"></i>Business Details</span>
            </div>
            <div class="panel-body">
                <div class="form-group">
                    <label>Vendor / Company Name <span style="color:var(--danger)">*</span></label>
                    <input type="text" name="name" required value="<?= htmlspecialchars($vendor['name']) ?>">
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Phone</label>
                        <input type="text" name="phone" value="<?= htmlspecialchars($vendor['phone'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="email" name="email" value="<?= htmlspecialchars($vendor['email'] ?? '') ?>">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>GSTIN</label>
                        <div style="position:relative;">
                            <input type="text" name="gstin" id="gstin" maxlength="15"
                                   value="<?= htmlspecialchars($vendor['gstin'] ?? '') ?>"
                                   style="text-transform:uppercase;padding-right:36px;"
                                   oninput="this.value=this.value.toUpperCase(); autoFillGstState();">
                            <span id="gstSpinner" style="position:absolute;right:10px;top:50%;transform:translateY(-50%);color:var(--primary);font-size:12px;">
                                <?php if (!empty($vendor['gstin'])): ?><i class="fas fa-check-circle"></i><?php endif; ?>
                            </span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>State Code</label>
                        <input type="text" name="state_code" id="state_code" maxlength="2"
                               value="<?= htmlspecialchars($vendor['state_code'] ?? '') ?>">
                    </div>
                </div>
                <div class="form-group" style="max-width:200px;">
                    <label>Opening Balance (&#8377;)</label>
                    <input type="number" step="0.01" name="opening_balance" value="<?= htmlspecialchars($vendor['opening_balance'] ?? 0) ?>">
                </div>
            </div>
        </div>
    </div>

    <!-- Right Column -->
    <div>
        <div class="panel" style="margin-bottom:16px;">
            <div class="panel-header">
                <span class="panel-title"><i class="fas fa-user" style="color:var(--success);margin-right:7px;"></i>Contact Person</span>
            </div>
            <div class="panel-body">
                <div class="form-row">
                    <div class="form-group">
                        <label>Contact Person Name</label>
                        <input type="text" name="contact_person" value="<?= htmlspecialchars($vendor['contact_person'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label>Mobile</label>
                        <input type="text" name="mobile" value="<?= htmlspecialchars($vendor['mobile'] ?? '') ?>">
                    </div>
                </div>
            </div>
        </div>

        <div class="panel">
            <div class="panel-header">
                <span class="panel-title"><i class="fas fa-map-marker-alt" style="color:var(--danger);margin-right:7px;"></i>Address</span>
            </div>
            <div class="panel-body">
                <div class="form-group">
                    <label>Full Address</label>
                    <textarea name="address" rows="2"><?= htmlspecialchars($vendor['address'] ?? '') ?></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group" style="max-width:160px;">
                        <label>Pincode</label>
                        <input type="text" name="pincode" id="pincode" maxlength="6"
                               value="<?= htmlspecialchars($vendor['pincode'] ?? '') ?>"
                               oninput="if(this.value.length===6) lookupPincode(this.value);">
                    </div>
                    <div class="form-group">
                        <label>City</label>
                        <input type="text" name="city" id="city" value="<?= htmlspecialchars($vendor['city'] ?? '') ?>">
                    </div>
                </div>
                <div class="form-group">
                    <label>State</label>
                    <input type="text" name="state" id="state" value="<?= htmlspecialchars($vendor['state'] ?? '') ?>">
                </div>
            </div>
        </div>
    </div>

</div>

<div style="max-width:960px;margin-top:4px;display:flex;gap:10px;">
    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Update Vendor</button>
    <a href="index.php" class="btn btn-secondary">Cancel</a>
</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 autoFillGstState() {
    const gstin = document.getElementById('gstin').value.trim();
    const sc = gstin.substring(0, 2);
    if (gstin.length >= 2 && GST_STATES[sc]) {
        document.getElementById('state_code').value = sc;
        document.getElementById('state').value = GST_STATES[sc];
        document.getElementById('gstSpinner').innerHTML = '<i class="fas fa-check-circle"></i>';
    } else {
        document.getElementById('gstSpinner').innerHTML = '';
        if (gstin.length < 2) document.getElementById('state_code').value = '';
    }
}

function lookupPincode(pincode) {
    fetch('https://api.postalpincode.in/pincode/' + pincode)
    .then(r => r.json())
    .then(data => {
        if (data && data[0] && data[0].Status === 'Success') {
            const po = data[0].PostOffice[0];
            document.getElementById('city').value  = po.District;
            document.getElementById('state').value = po.State;
        }
    })
    .catch(() => {});
}
</script>

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