<?php include 'header.php'; ?>

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/remixicon/fonts/remixicon.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/tom-select/dist/css/tom-select.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/tom-select/dist/js/tom-select.complete.min.js"></script>
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>tailwind.config = { theme: { extend: {} } }</script>

    <style>
        /* ── Tom Select ── */
        .ts-wrapper{width:100%;position:relative;}
        .ts-control{min-height:56px !important;height:56px !important;border:1px solid #d1d5db !important;border-radius:16px !important;padding:0 16px !important;background:#fff !important;box-shadow:none !important;display:flex !important;align-items:center !important;overflow:hidden !important;}
        .ts-control input{font-size:14px !important;}
        .ts-wrapper.focus .ts-control{border-color:#8b5cf6 !important;box-shadow:0 0 0 4px rgba(139,92,246,0.10) !important;}
        .ts-dropdown{margin-top:8px !important;border-radius:16px !important;border:1px solid #e5e7eb !important;overflow:hidden !important;background:#fff !important;box-shadow:0 10px 30px rgba(0,0,0,0.10) !important;z-index:9999 !important;}
        .ts-dropdown-content{max-height:220px !important;overflow-y:auto !important;overflow-x:hidden !important;}
        .ts-dropdown .option{padding:14px 16px !important;font-size:14px !important;cursor:pointer;}
        .ts-dropdown .active{background:#f3e8ff !important;color:#7c3aed !important;}

        /* ── Floating Input ── */
        .fi{position:relative;}
        .fi input,.fi textarea{width:100%;height:56px;border:1px solid #d1d5db;border-radius:16px;padding:0 16px;outline:none;font-size:15px;background:#fff;transition:0.25s;}
        .fi textarea{height:100px;resize:none;padding-top:16px;}
        .fi input:focus,.fi textarea:focus{border-color:#8b5cf6;box-shadow:0 0 0 4px rgba(139,92,246,0.10);}
        .fi label{position:absolute;left:14px;top:50%;transform:translateY(-50%);background:#fff;padding:0 6px;font-size:14px;color:#6b7280;pointer-events:none;transition:0.2s;z-index:2;}
        .fi textarea+label{top:22px;transform:none;}
        .fi input:focus+label,.fi input:not(:placeholder-shown)+label{top:0;transform:translateY(-50%);font-size:11px;color:#8b5cf6;}
        .fi textarea:focus+label,.fi textarea:not(:placeholder-shown)+label{top:-8px;transform:none;font-size:11px;color:#8b5cf6;}

        /* ── Error state ── */
        .fi.error input,.fi.error textarea{border-color:#ef4444 !important;box-shadow:0 0 0 4px rgba(239,68,68,0.10) !important;}
        .fi.error input:focus+label,.fi.error input:not(:placeholder-shown)+label,
        .fi.error textarea:focus+label,.fi.error textarea:not(:placeholder-shown)+label{color:#ef4444;}
        .field-error{display:none;font-size:11px;color:#ef4444;margin-top:4px;padding-left:6px;}
        .fi.error .field-error{display:block;}

        /* ── Select Input ── */
        .si{position:relative;}
        .si select{width:100%;height:56px;border:1px solid #d1d5db;border-radius:16px;padding:0 42px 0 16px;outline:none;font-size:15px;background:#fff;appearance:none;transition:0.25s;}
        .si select:focus{border-color:#8b5cf6;box-shadow:0 0 0 4px rgba(139,92,246,0.10);}
        .si::after{content:'\ea4e';font-family:'remixicon';position:absolute;right:16px;top:50%;transform:translateY(-50%);color:#6b7280;pointer-events:none;}

        /* ── Steps ── */
        .form-step{display:none;}
        .form-step.active{display:block;}

        /* ── GST Switch ── */
        .switch-track{width:52px;height:28px;border-radius:999px;background:#d1d5db;position:relative;cursor:pointer;transition:background 0.25s;flex-shrink:0;}
        .switch-track.on{background:#8b5cf6;}
        .switch-thumb{width:22px;height:22px;border-radius:50%;background:#fff;position:absolute;top:3px;left:3px;transition:left 0.25s;box-shadow:0 1px 4px rgba(0,0,0,0.18);}
        .switch-track.on .switch-thumb{left:27px;}

        /* ── Contact Dynamic Rows ── */
        .contact-row{
            display:grid;
            grid-template-columns:1fr 1fr auto;
            gap:10px;
            align-items:start;
        }
        @media(max-width:540px){
            .contact-row{grid-template-columns:1fr auto;grid-template-rows:auto auto;}
            .contact-row .fi:last-of-type{grid-column:1;}
            .contact-row .row-actions{grid-column:2;grid-row:1/3;align-self:center;}
        }
        .row-actions{display:flex;flex-direction:column;gap:6px;padding-top:2px;}
        .row-btn{width:36px;height:36px;border-radius:10px;border:none;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:16px;font-weight:700;flex-shrink:0;transition:all 0.18s;}
        .row-btn.add{background:#ede9fe;color:#7c3aed;}
        .row-btn.add:hover{background:#ddd6fe;}
        .row-btn.rem{background:#fee2e2;color:#ef4444;}
        .row-btn.rem:hover{background:#fecaca;}
        .row-btn:disabled{opacity:0.35;cursor:not-allowed;}

        /* SweetAlert custom */
        .swal-custom-popup{border-radius:24px !important;padding:2rem 2rem 1.5rem !important;}
        .swal-custom-confirm{border-radius:12px !important;padding:0.6rem 2rem !important;font-weight:600 !important;}
    </style>

</head>

<body class="bg-gray-100 min-h-screen">

    <div class="max-w-7xl mx-auto px-2 sm:px-4 lg:px-8 pt-6 sm:pt-8 pb-5 sm:pb-6">
        <div class="flex items-start justify-between">
            <h1 class="text-3xl font-bold text-gray-900">Add Client</h1>
            <a href="uturn_client.php"
               class="inline-flex items-center gap-2 h-11 px-5 rounded-xl border border-gray-200 bg-white hover:bg-gray-50 text-gray-700 text-sm font-semibold transition-all shadow-sm">
                <i class="ri-arrow-left-line"></i> Back
            </a>
        </div>
    </div>

    <div class="max-w-7xl mx-auto px-2 sm:px-4 lg:px-8 pb-6 sm:pb-10">
        <div class="w-full bg-white rounded-2xl sm:rounded-3xl shadow-xl border border-gray-100 p-3 sm:p-6 md:p-8 lg:p-12 overflow-visible">
            <div class="flex flex-col lg:flex-row gap-6 lg:gap-14">

                <!-- ═══ SIDEBAR ═══ -->
                <div class="w-full lg:w-64 xl:w-72 flex-shrink-0">
                    <div class="hidden lg:flex flex-col gap-0">
                        <?php
                        $steps = [
                            ['01','Company Info',    'Company Information'],
                            ['02','Contact Person',  'Contact Person Details'],
                            ['03','Address Details', 'Company Address'],
                            ['04','Financial Info',  'Financial Information'],
                            ['05','Other Info',      'Other Information'],
                            ['06','Review & Save',   'Review All Details'],
                        ];
                        foreach ($steps as $i => $s): ?>
                        <div class="flex gap-4 items-start">
                            <div class="flex flex-col items-center">
                                <div id="sd<?= $i ?>"
                                     class="w-7 h-7 rounded-full <?= $i==0?'border-[3px] border-violet-500':'border-2 border-violet-200' ?> bg-white flex items-center justify-center transition-all duration-300"></div>
                                <?php if ($i!=5): ?><div class="w-0.5 h-10 bg-violet-200 mt-1"></div><?php endif; ?>
                            </div>
                            <div class="pt-0.5">
                                <div class="text-[11px] font-semibold text-gray-400"><?= $s[0] ?></div>
                                <div id="st<?= $i ?>" class="text-[15px] font-bold <?= $i==0?'text-gray-900':'text-gray-400' ?>"><?= $s[1] ?></div>
                                <div class="text-xs text-gray-400"><?= $s[2] ?></div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- ═══ FORM ═══ -->
                <div class="flex-1 min-w-0 lg:border-l lg:border-gray-100 lg:pl-10 xl:pl-12">


                    <!-- ══ STEP 1 : Company Info ══ -->
                    <div class="form-step active" id="fs0">
                        <div class="mb-8">
                            <p class="text-xs text-gray-400 mb-1">Step 1 of 6</p>
                            <h1 class="text-3xl font-bold text-gray-900">Company Information</h1>
                        </div>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">

                            <div class="fi" id="fi_client_name">
                                <input type="text" id="client_name" placeholder=" ">
                                <label>Client Name </label>
                                <span class="field-error">Client name is required.</span>
                            </div>

                            <div class="fi">
                                <input type="text" id="pan_number" placeholder=" " maxlength="10"
                                       oninput="this.value=this.value.toUpperCase()">
                                <label>PAN Number</label>
                            </div>

                            <div class="fi" id="fi_email">
                                <input type="email" id="email" placeholder=" "
                                       onblur="validateEmail('email','fi_email','err_email')">
                                <label>Email</label>
                                <span class="field-error" id="err_email">Please enter a valid email address.</span>
                            </div>

                            <div class="fi" id="fi_phone">
                                <input type="text" id="phone" placeholder=" " maxlength="10"
                                       oninput="this.value=this.value.replace(/\D/g,'')"
                                       onblur="validatePhone()">
                                <label>Phone Number</label>
                                <span class="field-error" id="err_phone">Phone number must be exactly 10 digits.</span>
                            </div>

                            <div class="fi">
                                <input type="text" id="website" placeholder=" ">
                                <label>Website</label>
                            </div>

                            <div class="si">
                                <select id="businessType">
                                    <option value="" disabled selected>Business Type</option>
                                    <option>Proprietorship</option>
                                    <option>Partnership</option>
                                    <option>Private Limited</option>
                                    <option>LLP</option>
                                </select>
                            </div>

                            <div class="si">
                                <select id="industryType">
                                    <option value="" disabled selected>Industry Type</option>
                                    <option>IT</option>
                                    <option>Finance</option>
                                    <option>Manufacturing</option>
                                    <option>Retail</option>
                                </select>
                            </div>

                        </div>
                    </div>


                    <!-- ══ STEP 2 : Contact Person ══ -->
                    <div class="form-step" id="fs1">
                        <div class="mb-8">
                            <p class="text-xs text-gray-400 mb-1">Step 2 of 6</p>
                            <h1 class="text-3xl font-bold text-gray-900">Contact Person</h1>
                        </div>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">

                            <div class="fi">
                                <input type="text" id="contact_name" placeholder=" ">
                                <label>Contact Name</label>
                            </div>

                            <div class="fi">
                                <input type="text" id="designation" placeholder=" ">
                                <label>Designation</label>
                            </div>

                        </div>

                        <!-- Contact rows: mobile + email side-by-side -->
                        <div class="mt-5">

                            <!-- Header -->
                            <div class="grid mb-2" style="grid-template-columns:1fr 1fr auto;">
                                <span class="text-sm font-semibold text-gray-500 pl-1">Mobile Number</span>
                                <span class="text-sm font-semibold text-gray-500 pl-1">Email Address</span>
                                <div class="flex justify-end pr-1">
                                    <button type="button" class="row-btn add" id="addContactRowBtn"
                                            onclick="addContactRow()" title="Add row">
                                        <i class="ri-add-line"></i>
                                    </button>
                                </div>
                            </div>

                            <!-- Rows container -->
                            <div id="contactRows" class="flex flex-col gap-3"></div>

                        </div>
                    </div>


                    <!-- ══ STEP 3 : Address ══ -->
                    <div class="form-step" id="fs2">
                        <div class="mb-8">
                            <p class="text-xs text-gray-400 mb-1">Step 3 of 6</p>
                            <h1 class="text-3xl font-bold text-gray-900">Address Details</h1>
                        </div>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">

                            <div class="fi">
                                <textarea id="address1" placeholder=" "></textarea>
                                <label>Address Line 1</label>
                            </div>

                            <div class="fi">
                                <textarea id="address2" placeholder=" "></textarea>
                                <label>Address Line 2</label>
                            </div>

                            <div class="si">
                                <select id="city">
                                    <option value="" disabled selected>City</option>
                                    <option>Surat</option>
                                    <option>Mumbai</option>
                                    <option>Delhi</option>
                                </select>
                            </div>

                            <div class="si">
                                <select id="state">
                                    <option value="" disabled selected>State</option>
                                    <option>Gujarat</option>
                                    <option>Maharashtra</option>
                                    <option>Rajasthan</option>
                                </select>
                            </div>

                            <div class="fi">
                                <input type="text" id="pincode" placeholder=" " maxlength="6"
                                       oninput="this.value=this.value.replace(/\D/g,'')">
                                <label>Pincode</label>
                            </div>

                            <div class="si">
                                <select id="country">
                                    <option value="" disabled selected>Country</option>
                                    <option>India</option>
                                    <option>United States</option>
                                    <option>United Kingdom</option>
                                </select>
                            </div>

                        </div>
                    </div>


                    <!-- ══ STEP 4 : Financial Info ══ -->
                    <div class="form-step" id="fs3">
                        <div class="mb-8">
                            <p class="text-xs text-gray-400 mb-1">Step 4 of 6</p>
                            <h1 class="text-3xl font-bold text-gray-900">Financial Information</h1>
                        </div>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">

                            <!-- GST Switch -->
                            <div class="sm:col-span-2 flex items-center justify-between h-14 px-4 border border-gray-200 rounded-2xl bg-gray-50">
                                <div>
                                    <p class="text-sm font-semibold text-gray-700">GST Registered</p>
                                    <p class="text-xs text-gray-400">Toggle on if the client has a GST</p>
                                </div>
                                <div class="switch-track" id="gstSwitch" onclick="toggleGst()">
                                    <div class="switch-thumb"></div>
                                </div>
                            </div>

                            <!-- GSTIN -->
                            <div class="fi sm:col-span-2" id="gstinWrapper" style="display:none;">
                                <input type="text" id="gstin" placeholder=" " maxlength="15"
                                       oninput="this.value=this.value.toUpperCase()">
                                <label>GSTIN</label>
                            </div>

                            <div class="fi">
                                <input type="text" id="credit_limit" placeholder=" ">
                                <label>Credit Limit</label>
                            </div>

                            <div class="si">
                                <select id="paymentTerms">
                                    <option value="" disabled selected>Payment Terms</option>
                                    <option>Immediate</option>
                                    <option>15 Days</option>
                                    <option>30 Days</option>
                                    <option>45 Days</option>
                                </select>
                            </div>

                            <div class="fi">
                                <input type="text" id="opening_balance" placeholder=" ">
                                <label>Opening Balance</label>
                            </div>

                            <div class="si">
                                <select id="currency">
                                    <option value="" disabled selected>Currency</option>
                                    <option>INR</option>
                                    <option>USD</option>
                                    <option>EUR</option>
                                </select>
                            </div>

                            <div class="si">
                                <select id="gstType">
                                    <option value="" disabled selected>GST Type</option>
                                    <option>Regular</option>
                                    <option>Composition</option>
                                    <option>Unregistered</option>
                                </select>
                            </div>

                            <div>
                                <label class="text-sm text-gray-500 block mb-3">TDS Applicable</label>
                                <div class="flex items-center gap-6 h-[56px] px-4 border border-gray-300 rounded-2xl">
                                    <label class="flex items-center gap-2 text-sm text-gray-700">
                                        <input type="radio" value="Yes" name="tds"> Yes
                                    </label>
                                    <label class="flex items-center gap-2 text-sm text-gray-700">
                                        <input type="radio" value="No" name="tds"> No
                                    </label>
                                </div>
                            </div>

                            <div class="si">
                                <select id="salesPerson">
                                    <option value="" disabled selected>Default Sales Person</option>
                                    <option>Sales Person 1</option>
                                    <option>Sales Person 2</option>
                                </select>
                            </div>

                        </div>
                    </div>


                    <!-- ══ STEP 5 : Other Info ══ -->
                    <div class="form-step" id="fs4">
                        <div class="mb-8">
                            <p class="text-xs text-gray-400 mb-1">Step 5 of 6</p>
                            <h1 class="text-3xl font-bold text-gray-900">Other Information</h1>
                        </div>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">

                            <div class="fi">
                                <textarea id="notes" placeholder=""></textarea>
                                <label>Client Related Remarks</label>
                            </div>


                        </div>
                    </div>


                    <!-- ══ STEP 6 : Review & Save ══ -->
                    <div class="form-step" id="fs5">
                        <div class="mb-8">
                            <p class="text-xs text-gray-400 mb-1">Step 6 of 6</p>
                            <h1 class="text-xl sm:text-2xl lg:text-3xl font-bold text-gray-900">Review & Save</h1>
                            <p class="text-sm text-gray-500 mt-1.5">Confirm all Client details before saving.</p>
                        </div>
                        <div id="reviewContent"
                             class="rounded-xl border border-gray-100 divide-y divide-gray-100 overflow-y-auto max-h-[55vh] sm:max-h-[500px] pr-1 bg-white">
                        </div>
                    </div>


                    <!-- ══ NAV BUTTONS ══ -->
                    <div id="btnRow"
                         class="flex flex-col-reverse sm:flex-row gap-3 sm:gap-0 items-stretch sm:items-center justify-between mt-8 sm:mt-10 pt-6 border-t border-gray-100">

                        <button id="prevBtn" onclick="goStep(-1)"
                                class="w-full sm:w-auto inline-flex justify-center items-center gap-2 h-12 px-7 rounded-xl border border-gray-200 bg-white text-black text-sm font-semibold opacity-40 cursor-not-allowed transition-all">
                            <i class="ri-arrow-left-line"></i> Previous
                        </button>

                        <button id="nextBtn" onclick="goStep(1)"
                                class="w-full sm:w-auto inline-flex justify-center items-center gap-2 h-12 px-9 rounded-xl bg-violet-500 hover:bg-violet-600 text-white text-sm font-semibold transition-all shadow-lg shadow-violet-200">
                            Next <i class="ri-arrow-right-line"></i>
                        </button>

                    </div>

                </div><!-- /form -->
            </div>
        </div>
    </div>

    <script>
    /* ═══════════════════════════════════════════════════════
       TOM SELECT
    ═══════════════════════════════════════════════════════ */
    let cur = 0;
    const total = 6;

    ['#businessType','#industryType','#paymentTerms','#currency','#gstType','#salesPerson','#city','#state','#country'].forEach(id => {
        if (document.querySelector(id)) {
            new TomSelect(id, { create:false, allowEmptyOption:true, placeholder:'Search...', closeAfterSelect:true });
        }
    });

    /* ═══════════════════════════════════════════════════════
       GST SWITCH
    ═══════════════════════════════════════════════════════ */
    let gstOn = false;

    function toggleGst() {
        gstOn = !gstOn;
        const track = document.getElementById('gstSwitch');
        const wrap  = document.getElementById('gstinWrapper');
        gstOn ? track.classList.add('on') : track.classList.remove('on');
        wrap.style.display = gstOn ? '' : 'none';
        if (!gstOn) document.getElementById('gstin').value = '';
    }

    /* ═══════════════════════════════════════════════════════
       CONTACT ROWS  – mobile + email side by side
    ═══════════════════════════════════════════════════════ */
    let rowIdx = 0;

    function addContactRow() {
        rowIdx++;
        const container = document.getElementById('contactRows');
        const n = container.children.length; // rows already present before adding

        const row = document.createElement('div');
        row.className = 'contact-row';
        row.id = 'crow_' + rowIdx;

        row.innerHTML = `
            <!-- Mobile -->
            <div class="fi" id="fi_mob_${rowIdx}">
                <input type="text" id="mob_${rowIdx}" placeholder=" " maxlength="10"
                       oninput="this.value=this.value.replace(/\\D/g,'')"
                       onblur="validateDynPhone('mob_${rowIdx}','fi_mob_${rowIdx}')">
                <label>Mobile Number</label>
                <span class="field-error">Must be exactly 10 digits.</span>
            </div>

            <!-- Email -->
            <div class="fi" id="fi_eml_${rowIdx}">
                <input type="email" id="eml_${rowIdx}" placeholder=" "
                       onblur="validateDynEmail('eml_${rowIdx}','fi_eml_${rowIdx}')">
                <label>Email Address</label>
                <span class="field-error">Enter a valid email address.</span>
            </div>

            <!-- Actions -->
            <div class="row-actions">
                <button type="button" class="row-btn rem" id="remBtn_${rowIdx}"
                        onclick="removeContactRow('crow_${rowIdx}')" title="Remove row">
                    <i class="ri-subtract-line"></i>
                </button>
            </div>`;

        container.appendChild(row);
        syncRemoveButtons();
        document.getElementById('mob_' + rowIdx).focus();
    }

    function removeContactRow(rowId) {
        const container = document.getElementById('contactRows');
        if (container.children.length <= 1) return; // keep at least 1 row
        const row = document.getElementById(rowId);
        if (row) {
            row.style.opacity = '0';
            row.style.transform = 'translateY(-4px)';
            row.style.transition = 'opacity 0.18s, transform 0.18s';
            setTimeout(() => { row.remove(); syncRemoveButtons(); }, 180);
        }
    }

    /* disable the remove btn when only 1 row remains */
    function syncRemoveButtons() {
        const container = document.getElementById('contactRows');
        const btns = container.querySelectorAll('.row-btn.rem');
        btns.forEach(btn => {
            btn.disabled = container.children.length <= 1;
        });
    }

    /* ═══════════════════════════════════════════════════════
       VALIDATION
    ═══════════════════════════════════════════════════════ */
    function validateEmail(inputId, wrapId) {
        const inp = document.getElementById(inputId);
        const wrap = document.getElementById(wrapId);
        const val = inp.value.trim();
        if (val === '') { wrap.classList.remove('error'); return true; }
        const ok = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(val);
        ok ? wrap.classList.remove('error') : wrap.classList.add('error');
        return ok;
    }

    function validatePhone() {
        const inp  = document.getElementById('phone');
        const wrap = document.getElementById('fi_phone');
        const val  = inp.value.trim();
        if (val === '') { wrap.classList.remove('error'); return true; }
        const ok = /^\d{10}$/.test(val);
        ok ? wrap.classList.remove('error') : wrap.classList.add('error');
        return ok;
    }

    function validateDynPhone(inputId, wrapId) {
        const inp  = document.getElementById(inputId);
        const wrap = document.getElementById(wrapId);
        const val  = inp.value.trim();
        if (val === '') { wrap.classList.remove('error'); return true; }
        const ok = /^\d{10}$/.test(val);
        ok ? wrap.classList.remove('error') : wrap.classList.add('error');
        return ok;
    }

    function validateDynEmail(inputId, wrapId) {
        const inp  = document.getElementById(inputId);
        const wrap = document.getElementById(wrapId);
        const val  = inp.value.trim();
        if (val === '') { wrap.classList.remove('error'); return true; }
        const ok = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(val);
        ok ? wrap.classList.remove('error') : wrap.classList.add('error');
        return ok;
    }

    function validateStep(step) {
        let ok = true;

        if (step === 0) {
            const cn   = document.getElementById('client_name');
            const cnWr = document.getElementById('fi_client_name');
            if (!cn.value.trim()) { cnWr.classList.add('error'); ok = false; }
            else cnWr.classList.remove('error');
            if (!validatePhone()) ok = false;
            if (!validateEmail('email','fi_email')) ok = false;
        }

        if (step === 1) {
            document.querySelectorAll('#contactRows [id^="mob_"]').forEach(inp => {
                if (!validateDynPhone(inp.id, 'fi_' + inp.id)) ok = false;
            });
            document.querySelectorAll('#contactRows [id^="eml_"]').forEach(inp => {
                if (!validateDynEmail(inp.id, 'fi_' + inp.id)) ok = false;
            });
        }

        return ok;
    }

    /* ═══════════════════════════════════════════════════════
       REVIEW BUILD
    ═══════════════════════════════════════════════════════ */
    function buildReview() {
        const tds     = document.querySelector('input[name="tds"]:checked');
        const mobiles = [...document.querySelectorAll('#contactRows [id^="mob_"]')].map(i => i.value).filter(Boolean);
        const emails  = [...document.querySelectorAll('#contactRows [id^="eml_"]')].map(i => i.value).filter(Boolean);

        const rows = [
            ['Client Name',          document.getElementById('client_name').value     || '-'],
            ['PAN Number',           document.getElementById('pan_number').value      || '-'],
            ['Email',                document.getElementById('email').value           || '-'],
            ['Phone Number',         document.getElementById('phone').value           || '-'],
            ['Website',              document.getElementById('website').value         || '-'],
            ['Business Type',        document.getElementById('businessType').value    || '-'],
            ['Industry Type',        document.getElementById('industryType').value    || '-'],
            ['Contact Name',         document.getElementById('contact_name').value    || '-'],
            ['Designation',          document.getElementById('designation').value     || '-'],
            ['Mobile Number(s)',      mobiles.join(', ')                              || '-'],
            ['Contact Email(s)',      emails.join(', ')                               || '-'],
            ['Address Line 1',       document.getElementById('address1').value        || '-'],
            ['Address Line 2',       document.getElementById('address2').value        || '-'],
            ['City',                 document.getElementById('city').value            || '-'],
            ['State',                document.getElementById('state').value           || '-'],
            ['Pincode',              document.getElementById('pincode').value         || '-'],
            ['Country',              document.getElementById('country').value         || '-'],
            ['GST Registered',       gstOn ? 'Yes' : 'No'],
            ['GSTIN',                gstOn ? (document.getElementById('gstin').value || '-') : 'N/A'],
            ['Credit Limit',         document.getElementById('credit_limit').value    || '-'],
            ['Payment Terms',        document.getElementById('paymentTerms').value    || '-'],
            ['Opening Balance',      document.getElementById('opening_balance').value || '-'],
            ['Currency',             document.getElementById('currency').value        || '-'],
            ['GST Type',             document.getElementById('gstType').value         || '-'],
            ['TDS Applicable',       tds ? tds.value : '-'],
            ['Default Sales Person', document.getElementById('salesPerson').value     || '-'],
            ['Notes',                document.getElementById('notes').value           || '-'],
        ];

        document.getElementById('reviewContent').innerHTML = rows.map(([k, v]) => `
            <div class="flex flex-col sm:flex-row sm:items-baseline gap-1 sm:gap-4 px-4 sm:px-5 py-3.5 bg-white hover:bg-gray-50 transition-colors">
                <span class="text-xs text-gray-500 sm:min-w-[170px] flex-shrink-0 font-semibold">${k}</span>
                <span class="text-sm text-gray-800 break-all whitespace-pre-wrap flex-1 min-w-0">${v}</span>
            </div>`).join('');
    }

    /* ═══════════════════════════════════════════════════════
       SIDEBAR DOTS
    ═══════════════════════════════════════════════════════ */
    function updateSidebar() {
        for (let i = 0; i < 6; i++) {
            const dot   = document.getElementById('sd' + i);
            const title = document.getElementById('st' + i);
            if (i < cur) {
                dot.className   = 'w-7 h-7 rounded-full bg-violet-500 border-2 border-violet-500 flex items-center justify-center transition-all duration-300';
                dot.innerHTML   = '<i class="ri-check-line text-white text-xs"></i>';
                title.className = 'text-[15px] font-bold text-gray-400';
            } else if (i === cur) {
                dot.className   = 'w-7 h-7 rounded-full border-[3px] border-violet-500 bg-white flex items-center justify-center transition-all duration-300';
                dot.innerHTML   = '';
                title.className = 'text-[15px] font-bold text-gray-900';
            } else {
                dot.className   = 'w-7 h-7 rounded-full border-2 border-violet-200 bg-white flex items-center justify-center transition-all duration-300';
                dot.innerHTML   = '';
                title.className = 'text-[15px] font-bold text-gray-400';
            }
        }
    }

    /* ═══════════════════════════════════════════════════════
       STEP NAVIGATION
    ═══════════════════════════════════════════════════════ */
    function goStep(dir) {

        /* ── Save / Submit on last step ── */
        if (cur === 5 && dir === 1) {
            Swal.fire({
                icon: 'success',
                title: 'Client Added!',
                text: 'The client has been saved successfully.',
                confirmButtonText: 'OK',
                confirmButtonColor: '#8b5cf6',
                customClass: {
                    popup:          'swal-custom-popup',
                    confirmButton:  'swal-custom-confirm'
                },
                timer: 3000,
                timerProgressBar: true,
                willClose: () => { window.location.href = 'account_client.php'; }
            }).then((result) => {
                window.location.href = 'account_client.php';
            });
            return;
        }

        /* ── Validate before advancing ── */
        if (dir === 1 && !validateStep(cur)) return;

        const nxt = cur + dir;
        if (nxt < 0 || nxt >= total) return;

        document.getElementById('fs' + cur).classList.remove('active');
        cur = nxt;
        if (cur === 5) buildReview();
        document.getElementById('fs' + cur).classList.add('active');
        updateSidebar();

        const pb = document.getElementById('prevBtn');
        const nb = document.getElementById('nextBtn');

        cur === 0
            ? pb.classList.add('opacity-40', 'cursor-not-allowed')
            : pb.classList.remove('opacity-40', 'cursor-not-allowed');

        if (cur === 5) {
            nb.innerHTML = '<i class="ri-check-line"></i> Save Client';
            nb.classList.remove('bg-violet-500','hover:bg-violet-600');
            nb.classList.add('bg-green-600','hover:bg-green-700');
        } else {
            nb.innerHTML = 'Next <i class="ri-arrow-right-line"></i>';
            nb.classList.remove('bg-green-600','hover:bg-green-700');
            nb.classList.add('bg-violet-500','hover:bg-violet-600');
        }
    }

    /* ═══════════════════════════════════════════════════════
       INIT – seed first contact row
    ═══════════════════════════════════════════════════════ */
    addContactRow();
    </script>

</body>
</html>

<?php include 'footer.php'; ?>
