<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<?php init_head(); ?>
<div id="wrapper" class="customer_profile">
    <div class="content">
        <div class="md:tw-w-[calc(100%-theme(width.64)+theme(spacing.16))] [&_div:last-child]:tw-mb-6">
            <?php if (isset($client) && $client->registration_confirmed == 0 && is_admin()) { ?>
            <div class="alert alert-warning">
                <h4>
                    <?= _l('customer_requires_registration_confirmation'); ?>
                </h4>
                <a href="<?= admin_url('clients/confirm_registration/' . $client->userid); ?>"
                    class="alert-link">
                    <?= _l('confirm_registration'); ?>
                </a>
            </div>
            <?php } elseif (isset($client) && $client->active == 0 && $client->registration_confirmed == 1) { ?>
            <div class="alert alert-warning">
                <?= _l('customer_inactive_message'); ?>
                <br />
                <a href="<?= admin_url('clients/mark_as_active/' . $client->userid); ?>"
                    class="alert-link">
                    <?= _l('mark_as_active'); ?>
                </a>
            </div>
            <?php } ?>
            <?php if (isset($client) && (staff_cant('view', 'customers') && is_customer_admin($client->userid))) {?>
            <div class="alert alert-info">
                <?= e(_l('customer_admin_login_as_client_message', get_staff_full_name(get_staff_user_id()))); ?>
            </div>
            <?php } ?>
        </div>

        <?php if (isset($client) && $client->leadid != null) { ?>
        <small class="tw-block">
            <b><?= e(_l('customer_from_lead', _l('lead'))); ?></b>
            <a href="<?= admin_url('leads/index/' . $client->leadid); ?>"
                onclick="init_lead(<?= e($client->leadid); ?>); return false;">
                -
                <?= _l('view'); ?>
            </a>
        </small>
        <?php } ?>

        <div class="md:tw-max-w-64 tw-w-full">
            <?php if (isset($client)) { ?>
            <h4 class="tw-text-lg tw-font-bold tw-text-neutral-800 tw-mt-0">
                <div class="tw-space-x-3 tw-flex tw-items-center">
                    <span class="tw-truncate">
                        #<?= e($client->userid . ' ' . $title); ?>
                    </span>
                    <?php if (staff_can('delete', 'customers') || is_admin()) { ?>
                    <div class="btn-group">
                        <a href="#" class="dropdown-toggle btn-link" data-toggle="dropdown" aria-haspopup="true"
                            aria-expanded="false">
                            <span class="caret"></span>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-right">
                            <?php if (is_admin()) { ?>
                            <li>
                                <a href="<?= admin_url('clients/login_as_client/' . $client->userid); ?>"
                                    target="_blank">
                                    <i class="fa-regular fa-share-from-square"></i>
                                    <?= _l('login_as_client'); ?>
                                </a>
                            </li>
                            <?php } ?>
                            <?php if (staff_can('delete', 'customers')) { ?>
                            <li>
                                <a href="<?= admin_url('clients/delete/' . $client->userid); ?>"
                                    class="text-danger delete-text _delete"><i class="fa fa-remove"></i>
                                    <?= _l('delete'); ?>
                                </a>
                            </li>
                            <?php } ?>
                        </ul>
                    </div>
                    <?php } ?>
                </div>
            </h4>
            <?php } ?>
        </div>

        <?php if (isset($client)) { ?>
        <?php
            $novaris_student_contact = null;

            if (isset($contacts) && is_array($contacts) && count($contacts) > 0) {
                foreach ($contacts as $c) {
                    $tmp = is_array($c) ? (object) $c : $c;
                    if (isset($tmp->is_primary) && (int) $tmp->is_primary === 1) {
                        $novaris_student_contact = $tmp;
                        break;
                    }
                }

                if (!$novaris_student_contact) {
                    $novaris_student_contact = is_array($contacts[0]) ? (object) $contacts[0] : $contacts[0];
                }
            }

            $student_id      = $novaris_student_contact && isset($novaris_student_contact->student_id) ? $novaris_student_contact->student_id : '';
            $moodle_username = $novaris_student_contact && isset($novaris_student_contact->moodle_username) ? $novaris_student_contact->moodle_username : '';
            $moodle_password = $novaris_student_contact && isset($novaris_student_contact->moodle_password) ? $novaris_student_contact->moodle_password : '';
            $has_credentials = !empty($student_id) || !empty($moodle_username);

            $student_programs = [];
            $program_catalog = [];

            if ($this->db->table_exists(db_prefix() . 'student_programs')) {
                $this->db->where('client_id', $client->userid);
                $this->db->order_by('start_date', 'ASC');
                $student_programs = $this->db->get(db_prefix() . 'student_programs')->result_array();

                // Catálogo automático: toma todos los programas ya creados para poder reutilizarlos.
                $this->db->select('program_name');
                $this->db->from(db_prefix() . 'student_programs');
                $this->db->where('program_name IS NOT NULL', null, false);
                $this->db->where('program_name !=', '');
                $this->db->group_by('program_name');
                $this->db->order_by('program_name', 'ASC');
                $program_catalog = $this->db->get()->result_array();
            }
        ?>

        <style>
            .novaris-card {
                border: 0;
                border-radius: 18px;
                overflow: hidden;
                box-shadow: 0 10px 30px rgba(15, 23, 42, .08);
                margin-bottom: 22px;
            }
            .novaris-card-header {
                background: linear-gradient(135deg, #1028B5 0%, #0f766e 100%);
                color: #fff;
                padding: 24px 30px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                gap: 16px;
                flex-wrap: wrap;
            }
            .novaris-card-header h3 {
                margin: 0;
                color: #fff;
                font-weight: 800;
                letter-spacing: -.02em;
            }
            .novaris-card-header p {
                margin: 6px 0 0;
                color: rgba(255,255,255,.85);
            }
            .novaris-actions .btn {
                border-radius: 999px;
                font-weight: 700;
                margin-left: 6px;
            }
            .novaris-card-body {
                padding: 26px 30px 30px;
                background: #fff;
            }
            .novaris-grid {
                display: grid;
                grid-template-columns: repeat(3, minmax(0, 1fr));
                gap: 14px;
                margin-bottom: 16px;
            }
            .novaris-box {
                background: #f8fafc;
                border: 1px solid #e5e7eb;
                border-radius: 14px;
                padding: 16px;
                min-height: 96px;
            }
            .novaris-label {
                font-size: 12px;
                text-transform: uppercase;
                letter-spacing: .08em;
                color: #64748b;
                font-weight: 800;
                margin-bottom: 8px;
            }
            .novaris-value {
                font-size: 20px;
                color: #0f172a;
                font-weight: 800;
                word-break: break-word;
            }
            .novaris-password-box {
                background: #eff6ff;
                border: 1px solid #bfdbfe;
                border-left: 5px solid #1028B5;
                border-radius: 14px;
                padding: 16px 18px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                gap: 12px;
                flex-wrap: wrap;
            }
            .novaris-password-box strong {
                color: #1028B5;
            }
            .novaris-empty {
                background: #fff7ed;
                border: 1px solid #fed7aa;
                color: #9a3412;
                border-radius: 14px;
                padding: 16px 18px;
                margin: 0;
            }
            .novaris-program-table {
                width: 100%;
                border-collapse: collapse;
                margin-top: 12px;
            }
            .novaris-program-table th {
                background: #f8fafc;
                color: #475569;
                font-weight: 800;
                padding: 12px 14px;
                border-bottom: 1px solid #e5e7eb;
            }
            .novaris-program-table td {
                padding: 12px 14px;
                border-bottom: 1px solid #f1f5f9;
                color: #334155;
                vertical-align: middle;
            }
            .novaris-status {
                display: inline-block;
                padding: 5px 10px;
                border-radius: 999px;
                background: #ecfdf5;
                color: #047857;
                font-weight: 800;
                font-size: 12px;
            }
            .novaris-program-actions .btn {
                margin-left: 4px;
            }
            @media (max-width: 991px) {
                .novaris-grid {
                    grid-template-columns: repeat(2, minmax(0, 1fr));
                }
            }
            @media (max-width: 575px) {
                .novaris-grid {
                    grid-template-columns: 1fr;
                }
                .novaris-card-header,
                .novaris-card-body {
                    padding: 20px;
                }
            }
        </style>

        <datalist id="kaiteki_program_catalog">
            <?php foreach ($program_catalog as $pc) { ?>
                <option value="<?= e($pc['program_name']); ?>"></option>
            <?php } ?>
        </datalist>

        <!-- MOODLE CREDENTIALS -->
        <div class="panel_s novaris-card">
            <div class="novaris-card-header">
                <div>
                    <h3><i class="fa fa-key"></i> Campus Moodle Credentials</h3>
                    <p>Student ID, Moodle username and virtual campus password for campus.faculdadecta.com.</p>
                </div>

                <div class="novaris-actions">
                    <button type="button" class="btn btn-success" data-toggle="modal" data-target="#create_student_credentials_modal">
                        <i class="fa fa-key"></i> Create / Update Moodle
                    </button>

                    <?php if ($has_credentials) { ?>
                    <a href="<?= admin_url('clients/send_student_credentials_email/' . $client->userid); ?>"
                       class="btn btn-info"
                       onclick="return confirm('Send Moodle credentials by email?');">
                        <i class="fa fa-envelope"></i> Send Email
                    </a>
                    <?php } ?>
                </div>
            </div>

            <div class="novaris-card-body">
                <?php if ($has_credentials) { ?>
                    <div class="novaris-grid">
                        <div class="novaris-box">
                            <div class="novaris-label">Student ID</div>
                            <div class="novaris-value"><?= e($student_id); ?></div>
                        </div>

                        <div class="novaris-box">
                            <div class="novaris-label">Moodle Username</div>
                            <div class="novaris-value"><?= e($moodle_username); ?></div>
                        </div>

                        <div class="novaris-box">
                            <div class="novaris-label">Campus URL</div>
                            <div class="novaris-value" style="font-size:15px;">
                                https://campus.faculdadecta.com
                            </div>
                        </div>
                    </div>

                    <div class="novaris-password-box">
                        <div>
                            <strong>Moodle Password:</strong>
                            <span id="novaris_moodle_password_text"><?= e($moodle_password); ?></span>
                        </div>
                        <button type="button" class="btn btn-default btn-sm" onclick="copyNovarisPassword()">
                            <i class="fa fa-copy"></i> Copy Password
                        </button>
                    </div>
                <?php } else { ?>
                    <div class="novaris-empty">
                        <strong>No Moodle credentials generated yet.</strong>
                        Click <b>Create / Update Moodle</b> to generate Student ID and Moodle access.
                    </div>
                <?php } ?>
            </div>
        </div>

        <div class="modal fade" id="create_student_credentials_modal" tabindex="-1" role="dialog" aria-labelledby="createStudentCredentialsLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <?php echo form_open(admin_url('clients/create_student_credentials/' . $client->userid)); ?>
                    <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" id="createStudentCredentialsLabel">
                            Create / Update Campus Moodle Credentials
                        </h4>
                    </div>
                    <div class="modal-body">
                        <p class="text-muted">
                            This will generate or update the Student ID, Moodle username and Moodle password for the primary contact in campus.faculdadecta.com.
                        </p>

                        <?php echo render_input('program', 'Primary Program for Moodle custom field', '', 'text', [
                            'placeholder' => 'Podología Clínica y Estética',
                        ]); ?>

                        <p class="text-muted">
                            Academic programs, start dates and end dates are managed below in <b>Academic Programs</b>.
                        </p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">
                            <?php echo _l('close'); ?>
                        </button>
                        <button type="submit" class="btn btn-success">
                            <i class="fa fa-check"></i> Save Campus Moodle Credentials
                        </button>
                    </div>
                    <?php echo form_close(); ?>
                </div>
            </div>
        </div>

        <!-- ACADEMIC PROGRAMS -->
        <div class="panel_s novaris-card">
            <div class="novaris-card-header">
                <div>
                    <h3><i class="fa fa-graduation-cap"></i> Academic Programs</h3>
                    <p>Manage enrolled programs, start date, end date and academic status.</p>
                </div>

                <div class="novaris-actions">
                    <button type="button" class="btn btn-success" data-toggle="modal" data-target="#add_student_program_modal">
                        <i class="fa fa-plus"></i> Add Program
                    </button>
                </div>
            </div>

            <div class="novaris-card-body">
                <?php if (!empty($student_programs)) { ?>
                    <table class="novaris-program-table">
                        <thead>
                            <tr>
                                <th>Program</th>
                                <th>Level</th>
                                <th>Start Date</th>
                                <th>End Date</th>
                                <th>Status</th>
                                <th class="text-right">Options</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($student_programs as $sp) { ?>
                                <tr>
                                    <td><strong><?= e($sp['program_name']); ?></strong></td>
                                    <td><?= e($sp['credential_level']); ?></td>
                                    <td><?= !empty($sp['start_date']) ? e(_d($sp['start_date'])) : '-'; ?></td>
                                    <td><?= !empty($sp['end_date']) ? e(_d($sp['end_date'])) : '-'; ?></td>
                                    <td><span class="novaris-status"><?= e($sp['status']); ?></span></td>
                                    <td class="text-right novaris-program-actions">
                                        <button type="button"
                                                class="btn btn-info btn-xs"
                                                data-toggle="modal"
                                                data-target="#edit_student_program_modal_<?= e($sp['id']); ?>">
                                            <i class="fa fa-pencil"></i>
                                        </button>

                                        <a href="<?= admin_url('clients/delete_student_program/' . $client->userid . '/' . $sp['id']); ?>"
                                           class="btn btn-danger btn-xs _delete">
                                            <i class="fa fa-remove"></i>
                                        </a>
                                    </td>
                                </tr>

                                <div class="modal fade" id="edit_student_program_modal_<?= e($sp['id']); ?>" tabindex="-1" role="dialog" aria-labelledby="editStudentProgramLabel<?= e($sp['id']); ?>">
                                    <div class="modal-dialog" role="document">
                                        <div class="modal-content">
                                            <?php echo form_open(admin_url('clients/edit_student_program/' . $client->userid . '/' . $sp['id'])); ?>
                                            <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" id="editStudentProgramLabel<?= e($sp['id']); ?>">
                                                    Edit Academic Program
                                                </h4>
                                            </div>
                                            <div class="modal-body">
                                                <div class="form-group">
                                                    <label for="program_name_<?= e($sp['id']); ?>">Program Name</label>
                                                    <input type="text"
                                                           name="program_name"
                                                           id="program_name_<?= e($sp['id']); ?>"
                                                           class="form-control"
                                                           value="<?= e($sp['program_name']); ?>"
                                                           list="kaiteki_program_catalog"
                                                           placeholder="Escribe o selecciona un programa"
                                                           required>
                                                    <small class="text-muted">
                                                        Puedes seleccionar uno existente o escribir uno nuevo. Al guardar, quedará disponible en la lista.
                                                    </small>
                                                </div>

                                                <div class="form-group">

<label>
Credential Level
</label>

<select
name="credential_level"
id="credential_level_<?= $sp['id']; ?>"
class="form-control">

<option value="Curso"
<?= $sp['credential_level']=='Curso' ? 'selected':'' ?>>
Curso
</option>

<option value="Programa de Especialización"
<?= $sp['credential_level']=='Programa de Especialización' ? 'selected':'' ?>>
Programa de Especialización
</option>

<option value="Diplomado"
<?= $sp['credential_level']=='Diplomado' ? 'selected':'' ?>>
Diplomado
</option>

<option value="Programa Técnico"
<?= $sp['credential_level']=='Programa Técnico' ? 'selected':'' ?>>
Programa Técnico
</option>

<option value="Certificación Nacional"
<?= $sp['credential_level']=='Certificación Nacional' ? 'selected':'' ?>>
Certificación Nacional
</option>

<option value="Certificación Internacional"
<?= $sp['credential_level']=='Certificación Internacional' ? 'selected':'' ?>>
Certificación Internacional
</option>

<option value="Certificado Técnico Internacional"
<?= $sp['credential_level']=='Certificado Técnico Internacional' ? 'selected':'' ?>>
Certificado Técnico Internacional
</option>

</select>

</div>
                                                <?php echo render_input('start_date', 'Start Date', $sp['start_date'], 'date'); ?>
                                                <?php echo render_input('end_date', 'End Date', $sp['end_date'], 'date'); ?>

                                                <?php echo render_select('status', [
                                                    ['id' => 'Activo', 'name' => 'Activo'],
                                                    ['id' => 'Pendiente', 'name' => 'Pendiente'],
                                                    ['id' => 'Completado', 'name' => 'Completado'],
                                                    ['id' => 'Suspendido', 'name' => 'Suspendido'],
                                                    ['id' => 'Retirado', 'name' => 'Retirado'],
                                                ], ['id', 'name'], 'Status', $sp['status']); ?>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-default" data-dismiss="modal">
                                                    <?php echo _l('close'); ?>
                                                </button>
                                                <button type="submit" class="btn btn-success">
                                                    <i class="fa fa-check"></i> Update Program
                                                </button>
                                            </div>
                                            <?php echo form_close(); ?>
                                        </div>
                                    </div>
                                </div>
                            <?php } ?>
                        </tbody>
                    </table>
                <?php } else { ?>
                    <div class="novaris-empty">
                        <strong>No academic programs added yet.</strong>
                        Click <b>Add Program</b> to register the student's academic enrollment.
                    </div>
                <?php } ?>
            </div>
        </div>

        <div class="modal fade" id="add_student_program_modal" tabindex="-1" role="dialog" aria-labelledby="addStudentProgramLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <?php echo form_open(admin_url('clients/add_student_program/' . $client->userid)); ?>
                    <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" id="addStudentProgramLabel">
                            Add Academic Program
                        </h4>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="program_name_add">Program Name</label>
                            <input type="text"
                                   name="program_name"
                                   id="program_name_add"
                                   class="form-control"
                                   list="kaiteki_program_catalog"
                                   placeholder="Escribe o selecciona un programa"
                                   required>
                            <small class="text-muted">
                                Si el programa no figura, escríbelo aquí. Al guardar, quedará disponible para futuras selecciones.
                            </small>
                        </div>

                        <div class="form-group">
                            <label for="credential_level_add">Credential Level</label>
                            <select name="credential_level" id="credential_level_add" class="form-control">
                                <option value="">Seleccione un nivel</option>
                                <option value="Curso">Curso</option>
                                <option value="Programa de Especialización">Programa de Especialización</option>
                                <option value="Diplomado">Diplomado</option>
                                <option value="Programa Técnico">Programa Técnico</option>
                                <option value="Certificación Nacional">Certificación Nacional</option>
                                <option value="Certificación Internacional">Certificación Internacional</option>
                                <option value="Certificado Técnico Internacional">Certificado Técnico Internacional</option>
                            </select>
                        </div>

                        <?php echo render_input('start_date', 'Start Date', '', 'date'); ?>
                        <?php echo render_input('end_date', 'End Date', '', 'date'); ?>

                        <?php echo render_select('status', [
                            ['id' => 'Activo', 'name' => 'Activo'],
                            ['id' => 'Pendiente', 'name' => 'Pendiente'],
                            ['id' => 'Completado', 'name' => 'Completado'],
                            ['id' => 'Suspendido', 'name' => 'Suspendido'],
                            ['id' => 'Retirado', 'name' => 'Retirado'],
                        ], ['id', 'name'], 'Status', 'Activo'); ?>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">
                            <?php echo _l('close'); ?>
                        </button>
                        <button type="submit" class="btn btn-success">
                            <i class="fa fa-check"></i> Save Program
                        </button>
                    </div>
                    <?php echo form_close(); ?>
                </div>
            </div>
        </div>
        <?php } ?>

        <div class="md:tw-flex md:tw-gap-6">
            <?php if (isset($client)) { ?>
            <div class="md:tw-max-w-64 tw-w-full">
                <?php $this->load->view('admin/clients/tabs'); ?>
            </div>
            <?php } ?>
            <div
                class="tw-mt-12 md:tw-mt-0 tw-w-full <?= isset($client) ? 'tw-max-w-6xl' : 'tw-mx-auto tw-max-w-4xl'; ?>">

                <?php if (! isset($client)) {?>
                <h4 class="tw-mt-0 tw-font-bold tw-text-lg tw-text-neutral-700">
                    <?= $title ?>
                </h4>
                <?php } ?>

                <div class="panel_s">
                    <div class="panel-body">
                        <?php if (isset($client)) { ?>
                        <?= form_hidden('isedit'); ?>
                        <?= form_hidden('userid', $client->userid); ?>
                        <div class="clearfix"></div>
                        <?php } ?>
                        <div>
                            <div class="tab-content">
                                <?php $this->load->view((isset($tab) ? $tab['view'] : 'admin/clients/groups/profile')); ?>
                            </div>
                        </div>
                    </div>
                    <?php if ($group == 'profile') { ?>
                    <div class="panel-footer text-right tw-space-x-1" id="profile-save-section">
                        <?php if (! isset($client)) { ?>
                        <button class="btn btn-default save-and-add-contact customer-form-submiter">
                            <?= _l('save_customer_and_add_contact'); ?>
                        </button>
                        <?php } ?>
                        <button class="btn btn-primary only-save customer-form-submiter">
                            <?= _l('submit'); ?>
                        </button>
                    </div>
                    <?php } ?>
                </div>
            </div>
        </div>

    </div>
</div>
<?php init_tail(); ?>
<?php if (isset($client)) { ?>
<script>
    $(function() {
        init_rel_tasks_table( <?= e($client->userid); ?> ,
            'customer');
    });

    function copyNovarisPassword() {
        var el = document.getElementById('novaris_moodle_password_text');
        if (!el) {
            return;
        }

        var text = el.innerText || el.textContent;

        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text).then(function() {
                alert_float('success', 'Password copied');
            });
        } else {
            var temp = document.createElement('textarea');
            temp.value = text;
            document.body.appendChild(temp);
            temp.select();
            document.execCommand('copy');
            document.body.removeChild(temp);
            alert_float('success', 'Password copied');
        }
    }
</script>
<?php } ?>
<?php $this->load->view('admin/clients/client_js'); ?>
</body>

</html>