<?php
require_once '../includes/auth.php';
requirePermission('clients', 'create');
require_once '../db.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name            = trim($_POST['name']);
    $phone           = trim($_POST['phone'] ?? '');
    $email           = trim($_POST['email'] ?? '');
    $customer_type   = $_POST['customer_type'];
    $gstin           = ($customer_type === 'B2B') ? strtoupper(trim($_POST['gstin'] ?? '')) : '';
    $state_code      = ($customer_type === 'B2B') ? 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'] ?? '');
    if ($name) {
        $stmt = $conn->prepare("
            INSERT INTO clients
            (name, phone, email, customer_type, gstin, state_code, address, pincode, city, state, opening_balance, company_id, ship_address, ship_city, ship_state, ship_pincode)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        ");
        $stmt->bind_param("ssssssssssdissss",
            $name, $phone, $email, $customer_type, $gstin, $state_code,
            $address, $pincode, $city, $state, $opening_balance, $cid,
            $ship_address, $ship_city, $ship_state, $ship_pincode
        );
        $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-user-plus" style="color:var(--primary);margin-right:8px;"></i>Add 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 placeholder="Client or company name">
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Phone</label>
                        <input type="text" name="phone" placeholder="Phone number">
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="email" name="email" placeholder="Email address">
                    </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">B2C (Individual)</option>
                            <option value="B2B">B2B (Business)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Opening Balance (&#8377;)</label>
                        <input type="number" step="0.01" name="opening_balance" value="0">
                    </div>
                </div>

                <div id="gst_block" style="display:none;">
                    <div class="form-row">
                        <div class="form-group">
                            <label>GSTIN</label>
                            <div style="position:relative;">
                                <input type="text" name="gstin" id="gstin" maxlength="15"
                                       placeholder="15-digit GSTIN" style="text-transform:uppercase;padding-right:36px;"
                                       oninput="this.value=this.value.toUpperCase(); autoFillGstState();">
                                <span id="gstSpinner" style="display:none;position:absolute;right:10px;top:50%;transform:translateY(-50%);color:var(--primary);font-size:12px;">
                                    <i class="fas fa-check-circle"></i>
                                </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" placeholder="e.g. 29" maxlength="2">
                        </div>
                    </div>
                </div>
                <div id="no_gst_block"></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" placeholder="Street, Building, Area..."></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group" style="max-width:160px;">
                        <label>Pincode <span style="font-size:11px;color:var(--text-muted);font-weight:400;">(auto-fill city/state)</span></label>
                        <input type="text" name="pincode" id="pincode" maxlength="6" placeholder="6-digit 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" placeholder="City / District">
                    </div>
                </div>
                <div class="form-group">
                    <label>State <span style="font-size:11px;color:var(--text-muted);font-weight:400;">(auto from GSTIN or Pincode)</span></label>
                    <input type="text" name="state" id="state" placeholder="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)" checked>
                Same as Billing Address
            </label>
        </div>
        <div class="panel-body" id="ship_fields" style="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" placeholder="Street, Building, Area..."></textarea>
                    </div>
                    <div class="form-group">
                        <label>State</label>
                        <input type="text" name="ship_state" id="ship_state" placeholder="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" placeholder="6-digit pincode">
                        </div>
                        <div class="form-group">
                            <label>City</label>
                            <input type="text" name="ship_city" id="ship_city" placeholder="City / District">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="panel-body" id="ship_same_msg" style="color:var(--text-muted);font-size:13px;">
            <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> Save 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').style.display = 'inline';
    } else {
        document.getElementById('gstSpinner').style.display = 'none';
        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'; ?>
