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

$sameAsBilling = (
    ($client['ship_address'] ?? '') === ($client['address'] ?? '') &&
    ($client['ship_city']    ?? '') === ($client['city']    ?? '') &&
    ($client['ship_state']   ?? '') === ($client['state']   ?? '') &&
    ($client['ship_pincode'] ?? '') === ($client['pincode'] ?? '')
);

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

<div class="page-header">
    <h2><i class="fas fa-user-edit" style="color:var(--primary);margin-right:8px;"></i>Edit Client</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-user" style="color:var(--primary);margin-right:7px;"></i>Client Details</span>
            </div>
            <div class="panel-body">
                <div class="form-group">
                    <label>Client Name <span style="color:var(--danger)">*</span></label>
                    <input type="text" name="name" required value="<?= htmlspecialchars($client['name']) ?>">
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Phone</label>
                        <input type="text" name="phone" value="<?= htmlspecialchars($client['phone'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="email" name="email" value="<?= htmlspecialchars($client['email'] ?? '') ?>">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Customer Type <span style="color:var(--danger)">*</span></label>
                        <select name="customer_type" id="customer_type" onchange="toggleGST()" required>
                            <option value="B2C" <?= $client['customer_type']=='B2C'?'selected':'' ?>>B2C (Individual)</option>
                            <option value="B2B" <?= $client['customer_type']=='B2B'?'selected':'' ?>>B2B (Business)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Opening Balance (&#8377;)</label>
                        <input type="number" step="0.01" name="opening_balance" value="<?= htmlspecialchars($client['opening_balance'] ?? 0) ?>">
                    </div>
                </div>

                <div id="gst_block">
                    <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($client['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($client['gstin'])): ?><i class="fas fa-check-circle"></i><?php endif; ?>
                                </span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>State Code <span style="font-size:11px;color:var(--text-muted);font-weight:400;">(auto from GSTIN)</span></label>
                            <input type="text" name="state_code" id="state_code" maxlength="2"
                                   value="<?= htmlspecialchars($client['state_code'] ?? '') ?>">
                        </div>
                    </div>
                </div>
                <div id="no_gst_block" style="display:none;">
                    <input type="hidden" name="gstin" value="">
                    <input type="hidden" name="state_code" value="">
                </div>
            </div>
        </div>
    </div>

    <!-- Right Column -->
    <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>Billing Address</span>
            </div>
            <div class="panel-body">
                <div class="form-group">
                    <label>Full Address</label>
                    <textarea name="address" id="bill_address" rows="2"><?= htmlspecialchars($client['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($client['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($client['city'] ?? '') ?>">
                    </div>
                </div>
                <div class="form-group">
                    <label>State</label>
                    <input type="text" name="state" id="state" value="<?= htmlspecialchars($client['state'] ?? '') ?>">
                </div>
            </div>
        </div>
    </div>

</div>

<!-- Shipping Address -->
<div style="max-width:960px;margin-top:16px;">
    <div class="panel">
        <div class="panel-header" style="display:flex;align-items:center;justify-content:space-between;">
            <span class="panel-title"><i class="fas fa-truck" style="color:var(--info);margin-right:7px;"></i>Shipping Address</span>
            <label style="font-size:13px;font-weight:400;cursor:pointer;display:flex;align-items:center;gap:6px;">
                <input type="checkbox" name="same_as_billing" id="same_as_billing" value="1"
                       onchange="toggleShipping(this)"
                       <?= $sameAsBilling ? 'checked' : '' ?>>
                Same as Billing Address
            </label>
        </div>
        <div class="panel-body" id="ship_fields" style="<?= $sameAsBilling ? 'display:none;' : '' ?>">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                <div>
                    <div class="form-group">
                        <label>Full Address</label>
                        <textarea name="ship_address" id="ship_address" rows="2"><?= htmlspecialchars($client['ship_address'] ?? '') ?></textarea>
                    </div>
                    <div class="form-group">
                        <label>State</label>
                        <input type="text" name="ship_state" id="ship_state" value="<?= htmlspecialchars($client['ship_state'] ?? '') ?>">
                    </div>
                </div>
                <div>
                    <div class="form-row">
                        <div class="form-group" style="max-width:160px;">
                            <label>Pincode</label>
                            <input type="text" name="ship_pincode" id="ship_pincode" maxlength="6"
                                   value="<?= htmlspecialchars($client['ship_pincode'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label>City</label>
                            <input type="text" name="ship_city" id="ship_city" value="<?= htmlspecialchars($client['ship_city'] ?? '') ?>">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="panel-body" id="ship_same_msg" style="color:var(--text-muted);font-size:13px;<?= $sameAsBilling ? '' : 'display:none;' ?>">
            <i class="fas fa-info-circle"></i> Shipping address will be same as billing address.
        </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 Client</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 toggleGST() {
    const type = document.getElementById('customer_type').value;
    const isB2B = (type === 'B2B');
    document.getElementById('gst_block').style.display    = isB2B ? 'block' : 'none';
    document.getElementById('no_gst_block').style.display = isB2B ? 'none'  : 'block';
}
toggleGST();

function toggleShipping(cb) {
    document.getElementById('ship_fields').style.display   = cb.checked ? 'none' : 'block';
    document.getElementById('ship_same_msg').style.display = cb.checked ? 'block' : 'none';
}

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'; ?>
