<?php

defined('BASEPATH') OR exit('No direct script access allowed');

$cookie = $_COOKIE['user_data'] ?? '';
$json = urldecode($cookie);
$data = json_decode($json, true);
$privelegeId = $data['privelegeId'] ?? 0;

?>

<html>
<head>

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<!-- jQuery UI CSS -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">

<style>

label {
    font-weight: 600;
    font-size: 13px;
    color: #555;
    margin-bottom: 4px;
}
.panel-title {
    font-size: 14px;
}

.panel-info {
    border-color: #D9E3E3 !important;
}
.panel-heading .btn-primary.pull-right {
    padding: 4px 12px;
    font-size: 12px;
    border-radius: 4px;
}

.panel-info > .panel-heading {
    background-color: #D9E3E3 !important;
    border-color: #D9E3E3;
    color: #140606;
    font-weight: 600;
}

.table th {
    font-weight: 600;
    font-size: 12px;
    letter-spacing: 0.3px;
    color: #555;
}

#referralTable thead th,
#referralTable thead th a {
    color: #333 !important;
}

.table td {
    font-size: 13px;
    vertical-align: middle !important;
}
.table thead tr {
    background-color: #D9E3E3 !important;
}

.table > thead > tr.info > th,
.table > thead > tr.info > td {
    background-color: #D9E3E3 !important;
}

.dataTables_length select {
    border: 1px solid #aaa;
    border-radius: 3px;
    padding: 4px;
    background-color: transparent;
    color: inherit;
    height: 27px;
}

#referralTable .btn-primary.btn-xs,
#referralTable .btn-danger.btn-xs {
    width: 30px;
    padding: 4px 0;
    text-align: center;
    font-size: 13px;
}

#referralTable .btn-danger.btn-xs i {
    font-size: 11px;
}

.btn-primary {
    background-color: #428bca;
    border-color: #357ebd;
}

.form-group label {
    font-weight: 600;
    font-size: 13px;
    color: #555;
}

.form-control {
    height: 32px;
    font-size: 13px;
    border-radius: 3px;
}

.panel-body {
    padding: 15px;
}

.modal-header {
    background-color: #e6f4fb;
    border-bottom: 1px solid #bce8f1;
}

.modal-title {
    font-weight: 600;
    color: #31708f;
}

.modal {
    z-index: 1050;
}

.modal-backdrop {
    z-index: 1040;
}

.dataTables_filter {
    float: right !important;
    margin-bottom: 10px;
}

.custom-search-box {
    width: 240px;
    height: 34px;
    padding: 6px 12px;
    border-radius: 6px;
    font-size: 13px;
    border: 1px solid #ccc;
}

.custom-search-box:focus {
    border-color: #428bca;
    box-shadow: 0 0 4px rgba(66,139,202,.3);
}
#referralTable th:nth-child(2),
#referralTable td:nth-child(2) {
    width: 10px;
    white-space: nowrap;
}

.dataTables_info {
    font-size: 13px;
    color: #666;
    padding-top: 8px;
}

.dataTables_paginate {
    text-align: right;
    padding-top: 5px;
}

.dataTables_filter input.custom-search-box {
    border: 1px solid #aaa !important;
    border-radius: 3px !important;
    padding: 5px !important;
    background-color: transparent !important;
    color: inherit !important;
    margin-left: 3px !important;
    height: 18px !important;
    width: 120px !important;
    font-size: 13px !important;
    -webkit-appearance: none !important;
    -moz-appearance: none !important;
    appearance: none !important;
}

.dataTables_paginate .paginate_button {
    padding: 5px 12px;
    margin: 2px;
    border-radius: 4px;
    border: 1px solid #ddd;
    background-color: #fff;
    color: #333 !important;
    font-size: 13px;
}

.dataTables_paginate .paginate_button.current,
.dataTables_paginate .paginate_button.current:hover {
    background: #e6f2ff !important;
    color: #333 !important;
    border: 1px solid #dcdcdc !important;
    border-radius: 6px !important;
}

.dataTables_paginate .paginate_button:hover {
    background-color: #f5f5f5;
    border-color: #ccc;
}

table.dataTable thead th {
    border-bottom: 0px solid #111 !important;
}

table.dataTable tfoot td {
    border-top: 0px solid #111 !important;
}

.badge-completed,
.badge-pending {
    display: inline-block;
    width: 80px;
    text-align: center;
    padding: 5px 0;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
}

.badge-completed {
    background-color: #28a745;
    color: #fff;
}

.badge-pending {
    background-color: #ffc107;
    color: #212529;
}
#referralTable thead th:first-child {
    color: #337ab7 !important;
}

#referralTable thead th:hover {
    color: #337ab7 !important;
    cursor: pointer;
}

/* ===== Referral Modal ===== */

#referralModal .modal-content {
    border: none;
    border-radius: 14px;
    box-shadow: 0 10px 40px rgba(0,0,0,.15);
    overflow: hidden;
}

#referralModal .modal-dialog {
    margin-top: 20px;
    margin-bottom: 20px;
}

#referralModal .modal-header {
    background-color: #fff;
    border-bottom: 1px solid #eee;
    padding: 12px 24px 4px 24px;
}

#referralModal .modal-header .close {
    margin-top: -4px;
    opacity: .5;
}

#referralModal .modal-title {
    color: #428bca;
    font-size: 15px;
    font-weight: 700;
}

#referralModal .modal-subtitle {
    color: #888;
    font-size: 13px;
    margin: 2px 0 10px 0;
}

#referralModal .modal-body {
    padding: 4px 24px 0 24px;
}

#referralModal .form-group {
    margin-bottom: 14px;
}

#referralModal .form-group label {
    color: #000;
    font-weight: 600;
    font-size: 13px;
    margin-bottom: 5px;
    display: block;
}

#referralModal .form-group label .required-star {
    color: #e53935;
    margin-left: 2px;
}

#referralModal .form-control,
#referralModal select.form-control {
    height: 40px;
    border-radius: 8px;
    border: 1px solid #dde1e6;
    font-size: 14px;
    font-weight: normal;
    padding: 8px 13px;
    background-color: #fafbfc;
    box-shadow: none;
    transition: border-color .15s ease, box-shadow .15s ease;
}

#referralModal .form-control[disabled],
#referralModal select.form-control[disabled] {
    background-color: #fafbfc !important;
    color: #555 !important;
    -webkit-text-fill-color: #555;
    -webkit-appearance: none;
    opacity: 1 !important;
    cursor: not-allowed;
}

#referralModal textarea.form-control {
    height: auto;
    min-height: 48px;
    resize: vertical;
}

#referralModal .form-control::placeholder {
    color: #a8adb3;
    font-weight: normal;
}

#referralModal .form-control:focus {
    border-color: #e53935;
    box-shadow: 0 0 0 3px rgba(229,57,53,.12);
    background-color: #fff;
    outline: none;
}
#referralModal .arrived-radio-group {
    display: flex !important;
    flex-direction: row !important;
    align-items: center;
    gap: 20px;
}

#referralModal .radio-inline-custom {
    display: inline-flex !important;
    align-items: center;
    font-weight: normal;
    font-size: 14px;
    color: #333;
    margin: 0;
    cursor: pointer;
    white-space: nowrap;
}

#referralModal .radio-inline-custom input[type="radio"] {
    width: 16px;
    height: 16px;
    margin: 0 6px 0 0;
    accent-color: #e53935;
    cursor: pointer;
}

#referralModal .modal-footer {
    border-top: 1px solid #eee;
    padding: 10px 24px 14px 24px;
    background-color: #fff;
}
.input-icon-wrap {
    position: relative;
}

.input-icon-wrap .field-icon {
    position: absolute;
    left: 13px;
    top: 50%;
    transform: translateY(-50%);
    width: 14px;
    height: 14px;
    line-height: 14px;
    color: #a8adb3;
    font-size: 13px;
    text-align: center;
    pointer-events: none;
    z-index: 2;
}

.input-icon-wrap .form-control {
    padding-left: 40px !important;
}
#referralModal .btn-cancel {
    background-color: #428bca !important;
    border: 1px solid #357ebd !important;
    color: #fff !important;
    border-radius: 8px;
    padding: 6px 14px;
    font-size: 14px;
    font-weight: 550;
    background-image: none !important;
    text-shadow: none !important;
    box-shadow: none !important;
}

#referralModal .btn-cancel:hover,
#referralModal .btn-cancel:focus,
#referralModal .btn-cancel:active {
    background-color: #357ebd !important;
    border-color: #2e6da4 !important;
    color: #fff !important;
}

#referralModal .btn-submit {
    background-color: #e53935 !important;
    border: 1px solid #e53935 !important;
    color: #fff !important;
    border-radius: 8px;
    padding: 6px 14px;
    font-size: 14px;
    font-weight: 550;
    background-image: none !important;
    text-shadow: none !important;
    box-shadow: none !important;
}

#referralModal .btn-submit:hover,
#referralModal .btn-submit:focus,
#referralModal .btn-submit:active {
    background-color: #d32f2f !important;
    border-color: #d32f2f !important;
    color: #fff !important;
}

#referralModal #errorMsg {
    border-radius: 8px;
    font-size: 13px;
}

.table-responsive {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

#referralTable {
    min-width: 750px;
}

/* ===== Search Company Section ===== */
#companyFilterWrap {
    float: right;
    position: relative;
}

#companyFilterWrap .input-group {
    display: flex;
    align-items: center;
    gap: 6px;
}

#companyFilterWrap .form-control {
    height: 30px;
    width: 140px;
    font-size: 13px;
    border-radius: 4px !important;
    border: 1px solid #ccc;
    box-sizing: border-box;
    padding: 4px 8px;
}

/* Search Button Styling */
#companyFilterWrap .btn-blue {
    height: 30px;
    width: 32px;
    background-color: #4f92c2 !important;
    border: 1px solid #3f82b2 !important;
    border-radius: 4px !important;
    padding: 0;
    color: #fff !important;
    display: flex;
    align-items: center;
    justify-content: center;
    line-height: normal;
    font-size: 12px;
}

/* Company Autocomplete Dropdown */
.ui-autocomplete {
    overflow-y: auto;
    overflow-x: hidden;
    z-index: 99999 !important;
    border: 1px solid #ccc !important;
    border-radius: 6px !important;
    box-shadow: 0 4px 14px rgba(0,0,0,.15) !important;
    font-size: 13px !important;
    padding: 1px 0 !important;
}

.ui-autocomplete .ui-menu-item-wrapper {
    padding: 6px 12px !important;
}

.ui-autocomplete .ui-menu-item-wrapper.ui-state-active {
    background-color: #e6f2ff !important;
    border: none !important;
    color: #333 !important;
    margin: 0 !important;
}

/* ===== Header Date Filter Section ===== */
.header-date-filter {
    float: right;
    display: flex;
    align-items: center;
    gap: 6px;
    margin-right: 15px;
}

.header-date-filter .btn-search-date {
    height: 30px;
    width: 32px;
    background-color: #4f92c2 !important;
    border: 1px solid #3f82b2 !important;
    border-radius: 4px !important;
    padding: 0;
    color: #fff !important;
    display: flex;
    align-items: center;
    justify-content: center;
    line-height: normal;
    font-size: 11px;
}

/* Date input wrapper with calendar icon */
.header-date-filter .date-input-wrap {
    position: relative;
    display: inline-block;
}

.header-date-filter .date-input-wrap .date-icon {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    color: #777;
    font-size: 12px;
    pointer-events: auto;
    cursor: pointer;
    z-index: 2;
}

.header-date-filter input[type="text"] {
    height: 30px;
    font-size: 13px;
    padding: 2px 26px 2px 8px;
    width: 125px;
    border-radius: 4px;
    border: 1px solid #ccc;
    background-color: #ffffff !important;
    box-sizing: border-box;
    color: #333;
    outline: none;
}

.header-date-filter input[type="text"]:focus {
    border-color: #4f92c2;
}

/* ===== CHROME NATIVE DATEPICKER LOOK FOR JQUERY UI ===== */

#ui-datepicker-div {
    background: #ffffff !important;
    border: 1px solid #ccc !important;
    border-radius: 8px !important;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15) !important;
    padding: 12px !important;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif !important;
    width: 250px !important;
    z-index: 99999 !important;
}

#ui-datepicker-div .ui-datepicker-header {
    background: transparent !important;
    border: none !important;
    padding: 0 0 8px 0 !important;
    display: flex !important;
    align-items: center !important;
    justify-content: space-between !important;
}

#ui-datepicker-div .ui-datepicker-title {
    margin: 0 !important;
    display: flex !important;
    align-items: center !important;
    gap: 4px !important;
}

#ui-datepicker-div select.ui-datepicker-month,
#ui-datepicker-div select.ui-datepicker-year {
    border: none !important;
    font-size: 14px !important;
    font-weight: 600 !important;
    color: #222 !important;
    background: transparent !important;
    cursor: pointer !important;
    padding: 2px !important;
    outline: none !important;
}

#ui-datepicker-div .ui-datepicker-prev, 
#ui-datepicker-div .ui-datepicker-next {
    top: 8px !important;
    cursor: pointer !important;
    border: none !important;
    background: transparent !important;
}

#ui-datepicker-div .ui-datepicker-prev-hover, 
#ui-datepicker-div .ui-datepicker-next-hover {
    background: transparent !important;
    border: none !important;
    top: 8px !important;
}

#ui-datepicker-div .ui-datepicker-prev span {
    background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="%23333" stroke-width="2"><path d="M12 19V5M5 12l7-7 7 7"/></svg>') no-repeat center !important;
}

#ui-datepicker-div .ui-datepicker-next span {
    background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="%23333" stroke-width="2"><path d="M12 5v14M5 12l7 7 7-7"/></svg>') no-repeat center !important;
}

#ui-datepicker-div table {
    margin: 0 !important;
    width: 100% !important;
    border-collapse: collapse !important;
}

#ui-datepicker-div th {
    font-size: 12px !important;
    font-weight: 500 !important;
    color: #333 !important;
    padding: 6px 0 !important;
    text-align: center !important;
}

#ui-datepicker-div td {
    padding: 2px !important;
    text-align: center !important;
}

#ui-datepicker-div td a, 
#ui-datepicker-div td span {
    display: inline-block !important;
    width: 28px !important;
    height: 28px !important;
    line-height: 28px !important;
    text-align: center !important;
    padding: 0 !important;
    border: none !important;
    background: transparent !important;
    color: #222 !important;
    font-size: 13px !important;
    border-radius: 4px !important;
}

#ui-datepicker-div td.ui-datepicker-current-day a,
#ui-datepicker-div td a.ui-state-active {
    background-color: #0066ff !important;
    color: #ffffff !important;
    font-weight: bold !important;
    border-radius: 3px !important;
    box-shadow: 0 0 0 2px #000 !important;
}

#ui-datepicker-div td a:hover {
    background-color: #e8f0fe !important;
}

#ui-datepicker-div .ui-datepicker-other-month a,
#ui-datepicker-div .ui-datepicker-other-month span {
    color: #aaa !important;
}

#ui-datepicker-div .ui-datepicker-buttonpane {
    border-top: 1px solid #eee !important;
    margin: 8px 0 0 0 !important;
    padding: 8px 4px 0 4px !important;
    display: flex !important;
    justify-content: space-between !important;
    background: transparent !important;
}

#ui-datepicker-div .ui-datepicker-buttonpane button {
    background: transparent !important;
    border: none !important;
    color: #1a73e8 !important;
    font-size: 13px !important;
    font-weight: 500 !important;
    padding: 0 !important;
    cursor: pointer !important;
    opacity: 1 !important;
}

#ui-datepicker-div .ui-datepicker-buttonpane button:hover {
    text-decoration: underline !important;
}

/* ===== Mobile Responsive Styles ===== */
@media (max-width: 767px) {

    .panel-heading .panel-title {
        float: none !important;
        display: block;
        margin-bottom: 10px;
    }

    #companyFilterWrap {
        float: none !important;
        width: 100% !important;
        margin-top: 8px;
    }

    .header-date-filter {
        float: none !important;
        margin-right: 0;
        margin-top: 8px;
        flex-wrap: wrap;
    }
    
    .header-date-filter .date-input-wrap {
        width: 42%;
    }

    .header-date-filter input[type="text"] {
        width: 100%;
    }

    .dataTables_filter {
        float: none !important;
        width: 100%;
        text-align: left;
    }

    .custom-search-box {
        width: 100% !important;
    }

    .dataTables_info {
        text-align: center;
        padding-top: 4px;
    }

    .dataTables_paginate {
        text-align: center !important;
        padding-top: 8px;
    }

    .dataTables_paginate .paginate_button {
        padding: 4px 8px;
        margin: 1px;
        font-size: 12px;
    }

    .table th,
    .table td {
        font-size: 12px;
        padding: 6px 4px;
    }

    #referralTable .btn-primary.btn-xs,
    #referralTable .btn-danger.btn-xs {
        width: auto;
        min-width: 44px;
        padding: 4px 6px;
        font-size: 11px;
    }

    .panel-body {
        padding: 10px;
    }

    #referralModal .modal-dialog {
        margin: 10px;
        width: auto;
    }

    #referralModal .modal-header,
    #referralModal .modal-body,
    #referralModal .modal-footer {
        padding-left: 14px;
        padding-right: 14px;
    }

    #referralModal .row [class*="col-"] {
        width: 100%;
    }

    #referralModal .btn-cancel,
    #referralModal .btn-submit {
        width: 100%;
        margin-bottom: 8px;
    }

    #referralModal .modal-footer {
        display: flex;
        flex-direction: column-reverse;
    }
}

</style>

</head>

<body>

<div class="container-fluid">

<div class="panel panel-info">

<div class="panel-heading clearfix">

    <span class="panel-title pull-left" style="padding-top:6px;">
        REFERRAL LIST
    </span>
    
    <!-- Search Company Filter -->
    <div id="companyFilterWrap">
        <div class="input-group">
            <input type="text"
                   id="companyFilter"
                   class="form-control"
                   placeholder="Search company"
                   autocomplete="off">
            <span class="input-group-btn">
                <button type="button" class="btn btn-blue" id="companySearchBtn" title="Search Company">
                    <i class="glyphicon glyphicon-search"></i>
                </button>
            </span>
        </div>
    </div>

    <!-- Date Range Filter (Text Inputs with Calendar Icons) -->
    <div class="header-date-filter">
        <div class="date-input-wrap">
            <input type="text" id="fromDate" placeholder="dd-mm-yyyy" autocomplete="off" title="From Date">
            <i class="glyphicon glyphicon-calendar date-icon" onclick="$('#fromDate').focus();"></i>
        </div>
        <div class="date-input-wrap">
            <input type="text" id="toDate" placeholder="dd-mm-yyyy" autocomplete="off" title="To Date">
            <i class="glyphicon glyphicon-calendar date-icon" onclick="$('#toDate').focus();"></i>
        </div>
        <button type="button" id="filterDateBtn" class="btn btn-search-date" title="Search Date Range">
            <i class="glyphicon glyphicon-search"></i>
        </button>
    </div>

</div>

<div class="panel-body">

    <div class="table-responsive">

        <table class="table table-bordered table-striped table-hover" id="referralTable">

            <thead>

                <tr class="info">

                    <th>#</th>
                    <th>REFERRAL DATE</th>
                    <th>EMPLOYEE NAME</th>
                    <th>IQAMA / PASSPORT NO</th>
                    <th>MEDICAL TYPE</th>
                    <th>COMPANY</th>
                    <th class="hidden-company-col">COMPANY ID</th>
                    <th>STATUS</th>

                    <?php if($privelegeId == 1){ ?>

                    <th>EDIT</th>
                    <th>DELETE</th>

                    <?php } ?>

                </tr>

            </thead>

            <tbody>

            <?php if(!empty($referrals)){ $i = 1; ?>

                <?php foreach($referrals as $r){ ?>

                <tr>

                    <td><?= $i++; ?></td>

                    <td><?= date('d-m-Y', strtotime($r->referralDate)); ?></td>

                    <td><?= $r->referralName; ?></td>

                    <td><?= $r->referralquaNo; ?></td>

                    <td><?= $r->medicalType_display; ?></td>
                    <td><?= $r->companyName_display; ?></td>
                    <td class="hidden-company-col"><?= $r->companyName; ?></td>

                    <td class="text-center">
                        <?php if($r->referralStatus == 1){ ?>
                            <span class="badge badge-completed">Completed</span>
                        <?php } else { ?>
                            <span class="badge badge-pending">Pending</span>
                        <?php } ?>
                    </td>

                    <?php if($privelegeId == 1){ ?>

                    <td class="text-center">

                        <button type="button"
                                class="btn btn-success btn-xs edit-btn"
                                data-toggle="modal"
                                data-target="#referralModal"
                                onclick="editReferral(<?= $r->referralId ?>)">

                            <i class="fa fa-edit"></i>

                        </button>

                    </td>

                    <td class="text-center">

                        <a class="btn btn-danger btn-xs"
                           href="<?= base_url('Referrallist/Referrallist/deleteReferral/'.$r->referralId) ?>"
                           onclick="return confirm('Delete referral?')"
                           title="Delete">

                            <i class="glyphicon glyphicon-trash"></i>

                        </a>

                    </td>

                    <?php } ?>

                </tr>

                <?php } ?>

            <?php } ?>

            </tbody>

        </table>

    </div>

</div>

</div>

</div>

<!-- REFERRAL MODAL - EDIT ONLY -->

<div id="referralModal" class="modal fade" tabindex="-1" role="dialog">

<div class="modal-dialog modal-lg">

    <div class="modal-content">

        <div class="modal-header">

            <button type="button" class="close" data-dismiss="modal">&times;</button>

            <h4 class="modal-title" id="referralModalTitle">Update Status</h4>

            <p class="modal-subtitle">Update employee referral status.</p>

        </div>

        <div class="modal-body">

            <div id="errorMsg" class="alert alert-danger" style="display:none"></div>

            <form id="referralForm">

                <input type="hidden" name="referralId" id="referralId">

                <div class="row">

                    <div class="col-md-6 form-group">
                        <label>Employee Name</label>
                        <input type="text" name="referralName" class="form-control" disabled>
                    </div>

                    <div class="col-md-6 form-group">
                        <label>Iqama / Passport Number</label>
                        <input type="text" name="referralquaNo" class="form-control" disabled>
                    </div>

                    <div class="col-md-6 form-group">
                        <label>Referral Number</label>
                        <input type="text" name="referralNumber" class="form-control" disabled>
                    </div>

                    <div class="col-md-6 form-group">
                        <label>Mobile Number</label>
                        <div class="input-icon-wrap">
                            <i class="glyphicon glyphicon-phone field-icon"></i>
                            <input type="text" name="referralPhone1" class="form-control" maxlength="20" disabled>
                        </div>
                    </div>

                    <div class="col-md-6 form-group">
                        <label>Company</label>
                        <input type="text" name="companyName" class="form-control" disabled>
                    </div>

                    <div class="col-md-6 form-group">
                        <label>Referral Date</label>
                        <div class="input-icon-wrap">
                            <i class="glyphicon glyphicon-calendar field-icon"></i>
                            <input type="text" name="referralDate" class="form-control" disabled>
                        </div>
                    </div>

                    <div class="col-md-6 form-group">
                        <label>Medical Type</label>
                        <input type="text" name="medicalType" class="form-control" disabled>
                    </div>

                    <div class="col-md-6 form-group">
                        <label>Status <span class="required-star">*</span></label>
                        <select name="status" class="form-control" required>
                            <option value="">Select status</option>
                            <option value="Pending">Pending</option>
                            <option value="Completed">Completed</option>
                        </select>
                    </div>

                    <div class="col-md-6 form-group">
                        <label>Arrived <span class="required-star">*</span></label>
                        <div class="arrived-radio-group">
                            <label class="radio-inline-custom">
                                <input type="radio" name="arrived" value="1" id="arrivedRadioYes" required> Arrived
                            </label>
                            <label class="radio-inline-custom">
                                <input type="radio" name="arrived" value="0" id="arrivedRadioNo" required> Not Arrived
                            </label>
                        </div>
                    </div>

                    <div class="col-md-6 form-group">
                        <label>Additional Notes (Optional)</label>
                        <textarea name="notes" class="form-control" placeholder="Additional notes" disabled></textarea>
                    </div>

                </div>

            </form>

        </div>

        <div class="modal-footer">

            <button type="button" id="referralDismissBtn" class="btn btn-cancel" data-dismiss="modal">Cancel</button>

            <button type="button" class="btn btn-submit" onclick="saveReferral(event)">Submit</button>

        </div>

    </div>

</div>

</div>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- jQuery UI JS -->
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

<!-- DataTables JS -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

<script>
    // Companies from server, already filtered to status = 1 (and login_id, unless admin)
    var activeCompanies = <?= json_encode(array_map(function($c){ return ['id' => $c->companys_id, 'name' => $c->company_name]; }, $companies)); ?>;
</script>

<script>

jQuery(document).ready(function ($) {

    // ===== jQuery UI Datepicker Setup =====
    $("#fromDate, #toDate").datepicker({
        dateFormat: "dd-mm-yy",
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        closeText: "Clear",
        currentText: "Today",
        onSelect: function() {
            $(this).change();
        }
    });

    // Handle Today Button Action
    $.datepicker._gotoToday = function(id) {
        var target = $(id);
        var inst = this._getInst(target[0]);
        var date = new Date();
        this._setDate(inst, date);
        this._hideDatepicker();
        target.change();
    };

    // Handle Clear Button Action
    $(document).on("click", ".ui-datepicker-close", function() {
        $.datepicker._curInst.input.val('').change();
    });

    // Parse custom date (DD-MM-YYYY)
    function parseCustomDate(dateStr) {
        if (!dateStr) return null;
        var parts = dateStr.trim().split('-');
        if (parts.length === 3) {
            return new Date(parts[2], parts[1] - 1, parts[0]);
        }
        return null;
    }

    // ===== DataTables Date Range Search =====
    $.fn.dataTable.ext.search.push(
        function(settings, data, dataIndex) {
            var minVal = $('#fromDate').val();
            var maxVal = $('#toDate').val();
            
            var rowDateStr = data[1];

            if (!minVal && !maxVal) return true;
            if (!rowDateStr) return true;

            var rowDate = parseCustomDate(rowDateStr);
            var minDate = parseCustomDate(minVal);
            var maxDate = parseCustomDate(maxVal);

            if (minDate) minDate.setHours(0, 0, 0, 0);
            if (maxDate) maxDate.setHours(23, 59, 59, 999);

            if (rowDate) {
                if (minDate && rowDate < minDate) return false;
                if (maxDate && rowDate > maxDate) return false;
                return true;
            }

            return true;
        }
    );

 var referralDataTable = $("#referralTable").DataTable({

    dom: '<"toolbar1">frltip',

    autoWidth: false,

    order: [],

    columnDefs: [
        {
            orderable: false,
            targets: [0, -1, -2]
        },
        {
            visible: false,
            targets: [6]
        }
    ],

    initComplete: function () {
        $(".dataTables_filter input")
            .addClass("custom-search-box")
            .attr("placeholder", "Search...");
    },

    drawCallback: function(settings){
        var api = this.api();
        var start = api.page.info().start;

        api.rows({ page: 'current' }).every(function(rowIdx, tableLoop, rowLoop){
            var cell = api.cell(rowIdx, 0).node();
            $(cell).html(start + rowLoop + 1);
        });
    }

});

    // Trigger Search on Click
    $('#filterDateBtn').on('click', function() {
        // Clear company filter so it doesn't stack with the date search
        $('#companyFilter').val('');
        referralDataTable.column(companyIdCol).search('');
        referralDataTable.draw();
    });

    // Company Search (filters by hidden company id column, not the name)
    var companyIdCol = 6;

    var companyNameToId = {};
    activeCompanies.forEach(function(c){
        companyNameToId[c.name] = c.id;
    });

    function applyCompanyFilter(){
        var val = $('#companyFilter').val().trim();

        if(!val){
            referralDataTable.column(companyIdCol).search('').draw();
            return;
        }

        var id = companyNameToId[val];

        if(id === undefined){
            // Typed text doesn't match any known company - show no results
            referralDataTable.column(companyIdCol).search('^$', true, false).draw();
            return;
        }

        referralDataTable.column(companyIdCol).search('^' + id + '$', true, false).draw();
    }

    $('#companySearchBtn').on('click', function(){
        // Clear date filters so they don't stack with the company search
        $('#fromDate').val('');
        $('#toDate').val('');
        applyCompanyFilter();
    });

    $('#companyFilter').on('keypress', function(e){
        if(e.which === 13 || e.keyCode === 13){
            e.preventDefault();
            // Clear date filters so they don't stack with the company search
            $('#fromDate').val('');
            $('#toDate').val('');
            applyCompanyFilter();
        }
    });

    // ===== Company Autocomplete (status = 1 companies only) =====
    var companyList = activeCompanies.map(function(c){ return c.name; }).sort();

    // Force autocomplete dropdown to match input width exactly
    $.ui.autocomplete.prototype._resizeMenu = function() {
        var ul = this.menu.element;
        ul.outerWidth(this.element.outerWidth());
    };

    $('#companyFilter').autocomplete({
        source: companyList,
        minLength: 1,
        select: function(event, ui){
            $('#companyFilter').val(ui.item.value);
            return false;
        },
        open: function(){
            $('.ui-autocomplete').css('height', 'auto');
        }
    });

});

function resetReferralForm(){
    $('#referralForm')[0].reset();
    $('#referralId').val('');
    $('#referralModalTitle').text('Update Status');
}

function editReferral(id){

    $.post(
        "<?= base_url('Referrallist/Referrallist/getReferral') ?>",
        { id: id },

        function(res){

            var r = JSON.parse(res);

            resetReferralForm();

            for(var k in r){

                if(k === 'referralStatus') continue;
                if(k === 'arrived') continue;
                if(k === 'companyName') continue;
                if(k === 'companyName_display') continue;
                if(k === 'medicalType') continue;
                if(k === 'medicalType_display') continue;
                if(k === 'referralDate') continue;

                $('[name="'+k+'"]').val(r[k]);

            }

            $('[name="companyName"]').val(r.companyName_display);

            $('[name="medicalType"]').val(r.medicalType_display);

            if(r.referralDate){
                var d = new Date(r.referralDate);
                if(!isNaN(d)){
                    var dd = String(d.getDate()).padStart(2, '0');
                    var mm = String(d.getMonth() + 1).padStart(2, '0');
                    var yyyy = d.getFullYear();
                    $('[name="referralDate"]').val(dd + '-' + mm + '-' + yyyy);
                } else {
                    $('[name="referralDate"]').val(r.referralDate);
                }
            }

            // Status dropdown - set from referralStatus (independent field)
            var statusText = (parseInt(r.referralStatus) === 1) ? 'Completed' : 'Pending';
            $('[name="status"]').val(statusText);

            // Arrived radio - set from arrived (independent field, not tied to status)
            if(parseInt(r.arrived) === 1){
                $('#arrivedRadioYes').prop('checked', true);
            } else if(parseInt(r.arrived) === 0){
                $('#arrivedRadioNo').prop('checked', true);
            }
            // else: neither radio checked (arrived null/empty in DB)

            $('#referralId').val(r.referralId);

            $('#referralModalTitle').text('Update Status');

        }

    );

}

function saveReferral(e){

    if(e) e.preventDefault();

    if($('input[name="arrived"]:checked').length === 0){
        alert('Please select Arrived or Not Arrived');
        return;
    }

    $.post(

        "<?= base_url('Referrallist/Referrallist/saveReferral') ?>",

        $('#referralForm').serialize(),

        function(res){

            var r = JSON.parse(res);

            alert(r.message);

            if(r.status){
                $('#referralDismissBtn').trigger('click');
                location.reload();
            }

        }

    );

}

</script>

</body>

</html>