<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>

<?php if (isset($client)) { ?>
<h4 class="customer-profile-group-heading">
    <?= _l('client_add_edit_profile'); ?>
</h4>
<?php } ?>

<div class="row">
    <?= form_open($this->uri->uri_string(), ['class' => 'client-form', 'autocomplete' => 'off', 'enctype' => 'multipart/form-data']); ?>
    <?= form_hidden('client_type', (isset($client) ? $client->client_type : 'corporate')); ?>
    <div class="additional"></div>
    <div class="col-md-12">
        <div class="horizontal-scrollable-tabs panel-full-width-tabs">
            <div class="scroller arrow-left"><i class="fa fa-angle-left"></i></div>
            <div class="scroller arrow-right"><i class="fa fa-angle-right"></i></div>
            <div class="horizontal-tabs">
                <ul class="nav nav-tabs customer-profile-tabs nav-tabs-horizontal" role="tablist">
                    <li role="presentation"
                        class="<?= ! $this->input->get('tab') ? 'active' : ''; ?>">
                        <a href="#contact_info" aria-controls="contact_info" role="tab" data-toggle="tab">
                            <?= _l('customer_profile_details'); ?>
                        </a>
                    </li>
                    <?php
                  $customer_custom_fields = false;
if (total_rows(db_prefix() . 'customfields', ['fieldto' => 'customers', 'active' => 1]) > 0) {
    $customer_custom_fields = true; ?>
                    <li role="presentation"
                        class="<?= $this->input->get('tab') == 'custom_fields' ? 'active' : ''; ?>">
                        <a href="#custom_fields" aria-controls="custom_fields" role="tab" data-toggle="tab">
                            <?= hooks()->apply_filters('customer_profile_tab_custom_fields_text', _l('custom_fields')); ?>
                        </a>
                    </li>
                    <?php } ?>
                    <?php hooks()->do_action('after_customer_billing_and_shipping_tab', $client ?? false); ?>
                    <?php if (isset($client)) { ?>
                    <li role="presentation">
                        <a href="#customer_admins" aria-controls="customer_admins" role="tab" data-toggle="tab">
                            <?= _l('customer_admins'); ?>
                            <?php if (count($customer_admins) > 0) { ?>
                            <span
                                class="badge bg-default"><?= count($customer_admins) ?></span>
                            <?php } ?>
                        </a>
                    </li>
                    <?php hooks()->do_action('after_customer_admins_tab', $client); ?>
                    <?php } ?>
                </ul>
            </div>
        </div>
        <div class="tab-content mtop15">
            <?php hooks()->do_action('after_custom_profile_tab_content', $client ?? false); ?>
            <?php if ($customer_custom_fields) { ?>
            <div role="tabpanel"
                class="tab-pane<?= $this->input->get('tab') == 'custom_fields' ? ' active' : ''; ?>"
                id="custom_fields">
                <div class="row">
                    <div class="col-md-8">
                        <?php $rel_id = (isset($client) ? $client->userid : false); ?>
                        <?= render_custom_fields('customers', $rel_id); ?>
                    </div>
                </div>
            </div>
            <?php } ?>
            <div role="tabpanel"
                class="tab-pane<?= ! $this->input->get('tab') ? ' active' : ''; ?>"
                id="contact_info">
                <div class="row">
                    <div class="col-md-12<?= isset($client) && (! is_empty_customer_company($client->userid) && total_rows(db_prefix() . 'contacts', ['userid' => $client->userid, 'is_primary' => 1]) > 0) ? '' : ' hide'; ?>"
                        id="client-show-primary-contact-wrapper">
                        <div class="checkbox checkbox-info mbot20 no-mtop">
                            <input type="checkbox" name="show_primary_contact"
                                <?= isset($client) && $client->show_primary_contact == 1 ? 'checked' : ''; ?>
                            value="1" id="show_primary_contact">
                            <label
                                for="show_primary_contact"><?= _l('show_primary_contact', _l('invoices') . ', ' . _l('estimates') . ', ' . _l('payments') . ', ' . _l('credit_notes')); ?></label>
                        </div>
                    </div>
                    <div
                        class="col-md-<?= ! isset($client) ? 12 : 8; ?>">
                        <?php hooks()->do_action('before_customer_profile_company_field', $client ?? null); ?>
                        <?php $value = (isset($client) ? $client->company : ''); ?>
                        <?php $attrs = (isset($client) ? [] : ['autofocus' => true]); ?>
                        <?= render_input('company', 'client_company', $value, 'text', $attrs); ?>
                        <div id="company_exists_info" class="hide"></div>
                        <?php hooks()->do_action('after_customer_profile_company_field', $client ?? null); ?>
                        <?php // Contact personal fields ?>
                        <div class="row">
                            <div class="col-md-3">
                                <?php $value = (isset($contact) ? $contact->name_prefix : ''); ?>
                                <?= render_select('name_prefix', $prefixes, ['id', 'name'], 'client_name_prefix', $value, ['data-none-selected-text' => '-']); ?>
                            </div>
                            <div class="col-md-3">
                                <?php $value = (isset($contact) ? $contact->firstname : ''); ?>
                                <?= render_input('firstname', 'client_firstname', $value); ?>
                            </div>
                            <div class="col-md-3">
                                <?php $value = (isset($contact) ? $contact->middlename : ''); ?>
                                <?= render_input('middlename', 'client_middlename', $value); ?>
                            </div>
                            <div class="col-md-3">
                                <?php $value = (isset($contact) ? $contact->lastname : ''); ?>
                                <?= render_input('lastname', 'client_lastname', $value); ?>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-3">
                                <?php $value = (isset($contact) ? $contact->age : ''); ?>
                                <?= render_select('age', $ages, ['id', 'name'], 'client_age', $value, ['data-none-selected-text' => '-']); ?>
                            </div>
                            <div class="col-md-3">
                                <?php $value = (isset($contact) ? $contact->sex : ''); ?>
                                <?= render_select('sex', $sexes, ['id', 'name'], 'client_sex', $value, ['data-none-selected-text' => '-']); ?>
                            </div>
                            <div class="col-md-6">
                                <?php $value = (isset($client) ? $client->gst_number : ''); ?>
                                <?= render_input('gst_number', 'client_gst_number', $value); ?>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <?php $value = (isset($contact) ? $contact->pan_number : ''); ?>
                                <?= render_input('pan_number', 'client_pan_number', $value); ?>
                            </div>
                            <div class="col-md-6">
                                <?php $value = (isset($contact) ? $contact->aadhar_number : ''); ?>
                                <?= render_input('aadhar_number', 'client_aadhar_number', $value); ?>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <?php $dob = (isset($contact) ? $contact->date_of_birth : ''); ?>
                                    <?= render_date_input('date_of_birth', 'client_date_of_birth', $dob); ?>
                                    <span id="dob_age_display" style="margin-top:-10px;display:block;padding-bottom:10px;color:#888;font-size:12px;"></span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <?php $wad = (isset($contact) ? $contact->wedding_anniversary_date : ''); ?>
                                    <?= render_date_input('wedding_anniversary_date', 'client_wedding_anniversary_date', $wad); ?>
                                    <span id="wad_age_display" style="margin-top:-10px;display:block;padding-bottom:10px;color:#888;font-size:12px;"></span>
                                </div>
                            </div>
                        </div>
                        <?php hooks()->do_action('before_customer_profile_phone_field', $client ?? null); ?>
                        <div class="row">
                            <div class="col-md-2">
                                <?php
                                $isd_val = (isset($contact) ? $contact->isd_code : '');
                                $isd_display = array_map(function($c) {
                                    $c['name'] = explode(' ', $c['name'])[0];
                                    return $c;
                                }, $isd_codes);
                                ?>
                                <?= render_select('isd_code', $isd_display, ['id', 'name'], 'ISD Code', $isd_val, ['data-none-selected-text' => 'ISD']); ?>
                            </div>
                            <div class="col-md-10">
                        <?php $value = (isset($client) ? $client->phonenumber : ''); ?>
                        <?= render_input('phonenumber', 'client_phonenumber', $value); ?>
                            </div>
                        </div>
                        <?php hooks()->do_action('after_customer_profile_company_phone', $client ?? null); ?>
                        <?php if ((isset($client) && empty($client->website)) || ! isset($client)) {
                            $value = (isset($client) ? $client->website : '');
                            echo render_input('website', 'client_website', $value);
                        } else { ?>
                        <div class="form-group">
                            <label
                                for="website"><?= _l('client_website'); ?></label>
                            <div class="input-group">
                                <input type="text" name="website" id="website"
                                    value="<?= e($client->website); ?>"
                                    class="form-control">
                                <span class="input-group-btn">
                                    <a href="<?= e(maybe_add_http($client->website)); ?>"
                                        class="btn btn-default" target="_blank" tabindex="-1">
                                        <i class="fa fa-globe"></i></a>
                                </span>

                            </div>
                        </div>
                        <?php }
                        $selected = [];
if (isset($customer_groups)) {
    foreach ($customer_groups as $group) {
        array_push($selected, $group['groupid']);
    }
}
if (is_admin() || get_option('staff_members_create_inline_customer_groups') == '1') {
    echo render_select_with_input_group('groups_in[]', $groups, ['id', 'name'], 'customer_groups', $selected, '<div class="input-group-btn"><a href="#" class="btn btn-default" data-toggle="modal" data-target="#customer_group_modal"><i class="fa fa-plus"></i></a></div>', ['multiple' => true, 'data-actions-box' => true], [], '', '', false);
} else {
    echo render_select('groups_in[]', $groups, ['id', 'name'], 'customer_groups', $selected, ['multiple' => true, 'data-actions-box' => true], [], '', '', false);
}
?>
                        <div class="row">
                            <div
                                class="col-md-<?= ! is_language_disabled() ? 6 : 12; ?>">
                                <i class="fa-regular fa-circle-question pull-left tw-mt-0.5 tw-mr-1"
                                    data-toggle="tooltip"
                                    data-title="<?= _l('customer_currency_change_notice'); ?>"></i>
                                <?php
$s_attrs  = ['data-none-selected-text' => _l('system_default_string')];
$selected = '';
if (isset($client) && client_have_transactions($client->userid)) {
    $s_attrs['disabled'] = true;
}

foreach ($currencies as $currency) {
    if (isset($client)) {
        if ($currency['id'] == $client->default_currency) {
            $selected = $currency['id'];
        }
    }
}
// Do not remove the currency field from the customer profile!
echo render_select('default_currency', $currencies, ['id', 'name', 'symbol'], 'invoice_add_edit_currency', $selected, $s_attrs);
?>
                            </div>
                            <?php if (! is_language_disabled()) { ?>
                            <div class="col-md-6">
                                <div class="form-group select-placeholder">
                                    <label for="default_language"
                                        class="control-label"><?= _l('localization_default_language'); ?>
                                    </label>
                                    <select name="default_language" id="default_language"
                                        class="form-control selectpicker"
                                        data-none-selected-text="<?= _l('dropdown_non_selected_tex'); ?>">
                                        <option value="">
                                            <?= _l('system_default_string'); ?>
                                        </option>
                                        <?php foreach ($this->app->get_available_languages() as $availableLanguage) {
                                            $selected = '';
                                            if (isset($client)) {
                                                if ($client->default_language == $availableLanguage) {
                                                    $selected = 'selected';
                                                }
                                            } ?>
                                        <option
                                            value="<?= e($availableLanguage); ?>"
                                            <?= e($selected); ?>>
                                            <?= e(ucfirst($availableLanguage)); ?>
                                        </option>
                                        <?php } ?>
                                    </select>
                                </div>
                            </div>
                            <?php } ?>
                        </div>

                        <hr />

                        <?php $value = (isset($client) ? $client->address : ''); ?>
                        <?= render_textarea('address', 'client_address', $value); ?>
                        <?php $value = (isset($client) && isset($client->address_1) ? $client->address_1 : ''); ?>
                        <?= render_input('address_1', 'client_address_1', $value); ?>
                        <?php $value = (isset($client) && isset($client->address_2) ? $client->address_2 : ''); ?>
                        <?= render_input('address_2', 'client_address_2', $value); ?>
                        <?php $value = (isset($client) && isset($client->address_3) ? $client->address_3 : ''); ?>
                        <?= render_input('address_3', 'client_address_3', $value); ?>
                        <?php $value = (isset($client) && isset($client->location) ? $client->location : ''); ?>
                        <?= render_input('location', 'client_location', $value); ?>
                        <?php $value = (isset($client) && isset($client->area) ? $client->area : ''); ?>
                        <?= render_input('area', 'client_area', $value); ?>
                        <div class="row"><?= ls_ui_fields([
                            'fields' => ['country', 'state', 'district', 'city', 'pincode'],
                            'names'  => ['country' => 'country', 'state' => 'state', 'district' => 'district', 'city' => 'city', 'pincode' => 'zip'],
                            'value'  => [
                                'country'  => (isset($client->country) ? $client->country : ''),
                                'state'    => (isset($client->state) ? $client->state : ''),
                                'district' => (isset($client->district) ? $client->district : ''),
                                'city'     => (isset($client->city) ? $client->city : ''),
                                'pincode'  => (isset($client->zip) ? $client->zip : ''),
                            ],
                        ]); ?></div>
                    </div>
                </div>
            </div>
            <?php if (isset($client)) { ?>
            <div role="tabpanel" class="tab-pane" id="customer_admins">
                <?php if (staff_can('create', 'customers') || staff_can('edit', 'customers')) { ?>
                <a href="#" data-toggle="modal" data-target="#customer_admins_assign"
                    class="btn btn-primary mbot30"><?= _l('assign_admin'); ?></a>
                <?php } ?>
                <table class="table dt-table">
                    <thead>
                        <tr>
                            <th><?= _l('staff_member'); ?>
                            </th>
                            <th><?= _l('customer_admin_date_assigned'); ?>
                            </th>
                            <?php if (staff_can('create', 'customers') || staff_can('edit', 'customers')) { ?>
                            <th class="options">
                                <?= _l('options'); ?>
                            </th>
                            <?php } ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($customer_admins as $c_admin) { ?>
                        <tr>
                            <td><a
                                    href="<?= admin_url('profile/' . $c_admin['staff_id']); ?>">
                                    <?= staff_profile_image($c_admin['staff_id'], [
                                        'staff-profile-image-small',
                                        'mright5',
                                    ]);
                            echo e(get_staff_full_name($c_admin['staff_id'])); ?></a>
                            </td>
                            <td
                                data-order="<?= e($c_admin['date_assigned']); ?>">
                                <?= e(_dt($c_admin['date_assigned'])); ?>
                            </td>
                            <?php if (staff_can('create', 'customers') || staff_can('edit', 'customers')) { ?>
                            <td>
                                <a href="<?= admin_url('clients/delete_customer_admin/' . $client->userid . '/' . $c_admin['staff_id']); ?>"
                                    class="tw-text-neutral-500 hover:tw-text-neutral-700 focus:tw-text-neutral-700 _delete">
                                    <i class="fa-regular fa-trash-can fa-lg"></i>
                                </a>
                            </td>
                            <?php } ?>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
            <?php } ?>
        </div>
    </div>
    <?= form_close(); ?>
</div>
<?php if (isset($client)) { ?>
<?php if (staff_can('create', 'customers') || staff_can('edit', 'customers')) { ?>
<div class="modal fade" id="customer_admins_assign" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <?= form_open(admin_url('clients/assign_admins/' . $client->userid)); ?>
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">
                    <?= _l('assign_admin'); ?>
                </h4>
            </div>
            <div class="modal-body">
                <?php
               $selected = [];

    foreach ($customer_admins as $c_admin) {
        array_push($selected, $c_admin['staff_id']);
    }
    echo render_select('customer_admins[]', $staff, ['staffid', ['firstname', 'lastname']], '', $selected, ['multiple' => true], [], '', '', false); ?>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default"
                    data-dismiss="modal"><?= _l('close'); ?></button>
                <button type="submit"
                    class="btn btn-primary"><?= _l('submit'); ?></button>
            </div>
        </div>
        <!-- /.modal-content -->
        <?= form_close(); ?>
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<?php } ?>
<?php } ?>
<?php $this->load->view('admin/clients/client_group'); ?>
<script>
// GST validation: 22AAAAA0000A1Z5
(function() {
    var gstInput = document.querySelector('input[name="gst_number"]');
    if (!gstInput) return;
    var gstError = document.createElement('span');
    gstError.style.cssText = 'color:#e74c3c;font-size:12px;display:none;';
    gstError.textContent = 'Invalid GST. Format: 22AAAAA0000A1Z5';
    gstInput.parentNode.appendChild(gstError);
    gstInput.addEventListener('input', function() {
        this.value = this.value.toUpperCase();
    });
    gstInput.addEventListener('blur', function() {
        var val = this.value.trim();
        if (val && !/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/.test(val)) {
            gstError.style.display = 'block';
            this.style.borderColor = '#e74c3c';
        } else {
            gstError.style.display = 'none';
            this.style.borderColor = '';
        }
    });
})();

// PAN validation: AAAAA9999A
(function() {
    var panInput = document.querySelector('input[name="pan_number"]');
    var panError = document.createElement('span');
    panError.style.cssText = 'color:#e74c3c;font-size:12px;display:none;';
    panError.textContent = 'Invalid PAN. Format: AAAAA9999A';
    if (panInput) {
        panInput.parentNode.appendChild(panError);
        panInput.addEventListener('input', function() {
            this.value = this.value.toUpperCase();
        });
        panInput.addEventListener('blur', function() {
            var val = this.value.trim();
            if (val && !/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/.test(val)) {
                panError.style.display = 'block';
                this.style.borderColor = '#e74c3c';
            } else {
                panError.style.display = 'none';
                this.style.borderColor = '';
            }
        });
    }
})();

// Aadhaar: display as "1234 1234 1234", save without spaces
(function() {
    var aadharInput = document.querySelector('input[name="aadhar_number"]');
    if (!aadharInput) return;

    var aadharError = document.createElement('span');
    aadharError.style.cssText = 'color:#e74c3c;font-size:12px;display:none;';
    aadharError.textContent = 'Invalid Aadhaar. Must be 12 digits.';
    aadharInput.parentNode.appendChild(aadharError);

    aadharInput.addEventListener('input', function() {
        var digits = this.value.replace(/\D/g, '').slice(0, 12);
        this.value = digits.replace(/(\d{4})(?=\d)/g, '$1 ');
    });

    aadharInput.addEventListener('blur', function() {
        var digits = this.value.replace(/\s/g, '');
        if (digits && digits.length !== 12) {
            aadharError.style.display = 'block';
            this.style.borderColor = '#e74c3c';
        } else {
            aadharError.style.display = 'none';
            this.style.borderColor = '';
        }
    });

    // Strip spaces before submit
    var form = aadharInput.closest('form');
    if (form) {
        form.addEventListener('submit', function() {
            aadharInput.value = aadharInput.value.replace(/\s/g, '');
        });
    }
})();

function calculateAge(inputId, targetId) {
    var val = document.getElementById(inputId) ? document.getElementById(inputId).value : '';
    if (!val) { document.getElementById(targetId).innerText = ''; return; }
    var dob = new Date(val);
    var now = new Date();
    var diff = now - dob;
    if (isNaN(diff) || diff < 0) { document.getElementById(targetId).innerText = ''; return; }
    var days = Math.floor(diff / (1000 * 60 * 60 * 24));
    var months = Math.floor(days / 30.44);
    var years = Math.floor(months / 12);
    document.getElementById(targetId).innerText = years + 'y ' + (months % 12) + 'm ' + (days % 30) + 'd';
}
document.addEventListener('DOMContentLoaded', function() {
    var today = new Date().toISOString().split('T')[0];
    ['date_of_birth', 'wedding_anniversary_date'].forEach(function(name) {
        var el = document.querySelector('input[name="' + name + '"]');
        if (el) { $(el).datepicker('option', 'maxDate', today); }
    });

    var dobInput = document.querySelector('input[name="date_of_birth"]');
    var wadInput = document.querySelector('input[name="wedding_anniversary_date"]');
    if (dobInput) { dobInput.addEventListener('change', function() { calculateAge(this.id || 'date_of_birth', 'dob_age_display'); }); }
    if (wadInput) { wadInput.addEventListener('change', function() { calculateAge(this.id || 'wedding_anniversary_date', 'wad_age_display'); }); }
});
</script>