<style>
.holiday-card {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.08);
}
.holiday-table th {
    background: #f8fafc;
    font-weight: 600;
    color: #475569;
}
.holiday-table td {
    vertical-align: middle;
}
.btn-delete-holiday {
    padding: 0.25rem 0.5rem;
}
.upload-zone {
    border: 2px dashed #cbd5e1;
    border-radius: 12px;
    padding: 2rem;
    text-align: center;
    background: #f8fafc;
    transition: all 0.3s;
    cursor: pointer;
}
.upload-zone:hover {
    border-color: #3b82f6;
    background: #eff6ff;
}
.upload-zone.dragover {
    border-color: #3b82f6;
    background: #dbeafe;
}
/* Column Search Styles */
.column-search-row input {
    width: 100%;
    padding: 6px 10px;
    border: 1px solid #e2e8f0;
    border-radius: 4px;
    font-size: 0.8rem;
    background: #fff;
    transition: all 0.2s;
}
.column-search-row input:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}
.column-search-row input::placeholder {
    color: #94a3b8;
}
.column-search-row th {
    background: #f1f5f9 !important;
    padding: 8px 10px !important;
}

/* Smaller input height to match header */
.filters-row input.column-search {
  padding: 46px 6px;
  font-size: 13px;
  box-sizing: border-box;
}
#example thead th { white-space: nowrap; }

table thead tr:first-child th {
    background: linear-gradient(135deg, #1e3a5f 0%, #2d4a6f 100%);
    color: #fff;
    border: none;
}

table thead tr:first-child th a,
table thead tr:first-child th i {
    color: #fff; /* icons / links white */
}

</style>

<div class="content">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h4 class="mb-1"><i class="fa fa-calendar-alt text-primary me-2"></i> Holiday Management</h4>
                <p class="text-muted mb-0">
                    Manage holidays to adjust document due dates
                    <?php if (!empty($selected_country)): ?>
                        <span class="badge bg-primary ms-2"><i class="fa fa-globe"></i> <?= htmlspecialchars($selected_country) ?></span>
                    <?php endif; ?>
                </p>
            </div>
            <div class="d-flex gap-2">
                <select id="companyFilter" class="form-select" style="width: auto; min-width: 200px;">
                    <option value="">-- All Companies --</option>
                    <?php foreach ($companies as $company): ?>
                        <option value="<?= $company->id ?>" <?= $company->id == $selected_company_id ? 'selected' : '' ?>>
                            <?= htmlspecialchars($company->company_name) ?> (<?= $company->country ?: 'No Country' ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
                <select id="yearFilter" class="form-select" style="width: auto;">
                    <?php foreach ($years as $y): ?>
                        <option value="<?= $y ?>" <?= $y == $selected_year ? 'selected' : '' ?>><?= $y ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <div class="row">
            <!-- Left: Holiday List -->
            <div class="col-lg-8">
                <div class="holiday-card p-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">Holidays for <?= $selected_year ?></h5>
                        <div class="d-flex gap-2">
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="resetSearch()" title="Reset Search">
                                <i class="fa fa-undo"></i> Reset
                            </button>
                            <?php if (can_delete()): ?>
                            <button class="btn btn-danger btn-sm" id="btnClearYear" title="Clear all holidays for this year">
                                <i class="fa fa-trash me-1"></i> Clear All
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-hover holiday-table" id="holidayTable">
                            <thead>
                                <tr>
                                    <th width="50">#</th>
                                    <th>Date</th>
                                    <th>Day</th>
                                    <th>Holiday Name</th>
                                    <th width="80">Action</th>
                                </tr>
                                <tr class="column-search-row">
                                    <th></th>
                                    <th><input type="text" class="column-search" data-column="1" placeholder="Search..."></th>
                                    <th><input type="text" class="column-search" data-column="2" placeholder="Search..."></th>
                                    <th><input type="text" class="column-search" data-column="3" placeholder="Search..."></th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($holidays)): ?>
                                    <tr class="no-holidays">
                                        <td colspan="5" class="text-center text-muted py-4">
                                            <i class="fa fa-calendar-xmark fa-2x mb-2 d-block"></i>
                                            No holidays added for <?= $selected_year ?>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($holidays as $i => $h): ?>
                                        <tr data-id="<?= $h['id'] ?>">
                                            <td><?= $i + 1 ?></td>
                                            <td><?= date('d M Y', strtotime($h['holiday_date'])) ?></td>
                                            <td><?= date('l', strtotime($h['holiday_date'])) ?></td>
                                            <td><?= htmlspecialchars($h['holiday_name']) ?></td>
                                            <td>
                                                <?php if (can_delete()): ?>
                                                <button class="btn btn-outline-danger btn-sm btn-delete-holiday" data-id="<?= $h['id'] ?>">
                                                    <i class="fa fa-trash"></i>
                                                </button>
                                                <?php else: ?>
                                                <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Right: Add Holiday & Import -->
            <div class="col-lg-4">
                <?php if (can_edit()): ?>
                <!-- Add Single Holiday -->
                <div class="holiday-card p-4 mb-4">
                    <h5 class="mb-3"><i class="fa fa-plus-circle text-success me-2"></i>Add Holiday</h5>
                    <form id="addHolidayForm">
                        <div class="mb-3">
                            <label class="form-label">Date</label>
                            <input type="date" class="form-control" name="date" id="holidayDate" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Holiday Name</label>
                            <input type="text" class="form-control" name="name" id="holidayName" placeholder="e.g., Independence Day" required>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fa fa-plus me-1"></i> Add Holiday
                        </button>
                    </form>
                </div>

                <!-- Import Holidays -->
                <div class="holiday-card p-4">
                    <h5 class="mb-3"><i class="fa fa-file-import text-info me-2"></i>Import Holidays</h5>
                    <p class="text-muted small">Upload a CSV or Excel file with Date and Holiday Name columns.</p>
                    
                    <!-- Hidden file input OUTSIDE the upload zone -->
                    <input type="file" id="importFile" style="display:none !important; visibility:hidden; position:absolute; left:-9999px;" accept=".csv,.xlsx,.xls">
                    
                    <div class="upload-zone mb-3" id="uploadZone">
                        <i class="fa fa-cloud-upload-alt fa-2x text-muted mb-2 d-block"></i>
                        <p class="mb-1">Drag & drop file here</p>
                        <p class="small text-muted mb-0">or click to browse</p>
                    </div>
                    
                    <div class="d-flex justify-content-between">
                        <a href="<?= site_url('holiday/downloadTemplate') ?>" class="btn btn-outline-secondary btn-sm">
                            <i class="fa fa-download me-1"></i> Download Template
                        </a>
                        <button class="btn btn-info btn-sm" id="btnImport" disabled>
                            <i class="fa fa-upload me-1"></i> Import
                        </button>
                    </div>
                    <div id="importFileName" class="text-muted small mt-2"></div>
                </div>
                <?php else: ?>
                <!-- View Only Mode Message -->
                <div class="holiday-card p-4 mb-4 bg-light">
                    <h5 class="mb-3"><i class="fa fa-eye text-info me-2"></i>View Only Mode</h5>
                    <p class="text-muted mb-0">You have view-only access. Contact an administrator if you need to modify holidays.</p>
                </div>
                <?php endif; ?>

                <!-- Info Card -->
                <div class="holiday-card p-4 mt-4 bg-light">
                    <h6 class="mb-2"><i class="fa fa-info-circle text-primary me-2"></i>How it works</h6>
                    <ul class="small text-muted mb-0 ps-3">
                        <li>Due dates falling on holidays are moved to the previous working day</li>
                        <li>Due dates falling on Sunday are also adjusted</li>
                        <li>If a month has fewer days (e.g., Feb 30), it uses the last day</li>
                        <li>These adjustments apply to Dashboard, Upload, and View Documents</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
    console.log('Holiday page initialized');
    const selectedYear = <?= $selected_year ?>;
    console.log('Selected year:', selectedYear);
    
    // Column search functionality for holiday table
    $('#holidayTable .column-search').on('keyup change', function() {
        const columnIdx = $(this).data('column');
        const searchVal = $(this).val().toLowerCase().trim();
        
        $('#holidayTable tbody tr:not(.no-holidays)').each(function() {
            const $row = $(this);
            let show = true;
            
            $('#holidayTable .column-search').each(function() {
                const col = $(this).data('column');
                const val = $(this).val().toLowerCase().trim();
                
                if (val) {
                    const cellText = $row.find('td').eq(col).text().toLowerCase();
                    if (cellText.indexOf(val) === -1) {
                        show = false;
                        return false;
                    }
                }
            });
            
            $row.toggle(show);
        });
        
        // Update row numbers
        let visibleIndex = 1;
        $('#holidayTable tbody tr:not(.no-holidays):visible').each(function() {
            $(this).find('td').first().text(visibleIndex++);
        });
    });
    
    // Company filter change
    $('#companyFilter').on('change', function() {
        let companyId = $(this).val();
        let year = $('#yearFilter').val();
        let url = '<?= site_url('holiday') ?>?year=' + year;
        if (companyId) {
            url += '&company_id=' + companyId;
        }
        window.location.href = url;
    });
    
    // Year filter change
    $('#yearFilter').on('change', function() {
        let year = $(this).val();
        let companyId = $('#companyFilter').val();
        let url = '<?= site_url('holiday') ?>?year=' + year;
        if (companyId) {
            url += '&company_id=' + companyId;
        }
        window.location.href = url;
    });
    
    // Add Holiday Form
    $('#addHolidayForm').on('submit', function(e) {
        e.preventDefault();
        
        let companyId = $('#companyFilter').val();
        if (!companyId) {
            Swal.fire('Warning', 'Please select a company first to specify the country for this holiday.', 'warning');
            return;
        }
        
        $.post('<?= site_url('holiday/add') ?>', {
            date: $('#holidayDate').val(),
            name: $('#holidayName').val(),
            company_id: companyId
        }, function(res) {
            let response = JSON.parse(res);
            if (response.success) {
                Swal.fire({icon: 'success', title: 'Holiday Added!', timer: 1500, showConfirmButton: false});
                setTimeout(() => location.reload(), 1500);
            } else {
                Swal.fire('Error', response.message, 'error');
            }
        });
    });
    
    // Delete Holiday
    $(document).on('click', '.btn-delete-holiday', function() {
        let id = $(this).data('id');
        let row = $(this).closest('tr');
        
        Swal.fire({
            title: 'Delete Holiday?',
            text: 'Are you sure you want to delete this holiday?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            confirmButtonText: 'Yes, delete it'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('<?= site_url('holiday/delete') ?>', {id: id}, function(res) {
                    let response = JSON.parse(res);
                    if (response.success) {
                        row.fadeOut(300, function() { $(this).remove(); });
                        Swal.fire({icon: 'success', title: 'Deleted!', timer: 1000, showConfirmButton: false});
                    }
                });
            }
        });
    });
    
    // Clear all holidays for year
    $('#btnClearYear').on('click', function() {
        Swal.fire({
            title: 'Clear All Holidays?',
            text: `This will delete all holidays for ${selectedYear}. This cannot be undone.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            confirmButtonText: 'Yes, clear all'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('<?= site_url('holiday/clearYear') ?>', {year: selectedYear}, function(res) {
                    let response = JSON.parse(res);
                    if (response.success) {
                        Swal.fire({icon: 'success', title: 'Cleared!', text: response.message, timer: 1500, showConfirmButton: false});
                        setTimeout(() => location.reload(), 1500);
                    }
                });
            }
        });
    });
    
    // Upload zone
    let uploadZone = document.getElementById('uploadZone');
    let fileInput = document.getElementById('importFile');
    let selectedFile = null;
    
    // Click to browse - use native JS for reliability
    if (uploadZone && fileInput) {
        uploadZone.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            console.log('Upload zone clicked');
            fileInput.click();
        });
    }
    
    // Drag over - show visual feedback
    if (uploadZone) {
        uploadZone.addEventListener('dragover', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.add('dragover');
        });
        
        // Drag leave - remove visual feedback
        uploadZone.addEventListener('dragleave', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('dragover');
        });
        
        // Drop - handle file drop
        uploadZone.addEventListener('drop', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('dragover');
            
            let files = e.dataTransfer.files;
            if (files && files.length > 0) {
                selectedFile = files[0];
                console.log('File dropped:', selectedFile.name);
                $('#importFileName').text('Selected: ' + selectedFile.name);
                $('#btnImport').prop('disabled', false);
            }
        });
    }
    
    // File input change (for click-to-browse)
    if (fileInput) {
        fileInput.addEventListener('change', function() {
            if (this.files && this.files.length > 0) {
                selectedFile = this.files[0];
                console.log('File selected:', selectedFile.name);
                $('#importFileName').text('Selected: ' + selectedFile.name);
                $('#btnImport').prop('disabled', false);
            }
        });
    }
    
    // Import button
    $('#btnImport').on('click', function() {
        if (!selectedFile) {
            Swal.fire('Error', 'Please select a file first.', 'error');
            return;
        }
        
        let companyId = $('#companyFilter').val();
        if (!companyId) {
            Swal.fire('Warning', 'Please select a company first to specify the country for imported holidays.', 'warning');
            return;
        }
        
        // Validate file type
        let fileName = selectedFile.name.toLowerCase();
        if (!fileName.endsWith('.csv') && !fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
            Swal.fire('Error', 'Please upload a CSV or Excel file (.csv, .xlsx, .xls)', 'error');
            return;
        }
        
        let formData = new FormData();
        formData.append('file', selectedFile);
        formData.append('year', selectedYear);
        formData.append('company_id', $('#companyFilter').val());
        
        Swal.fire({
            title: 'Importing...',
            text: 'Please wait while holidays are being imported.',
            allowOutsideClick: false,
            didOpen: () => Swal.showLoading()
        });
        
        $.ajax({
            url: '<?= site_url('holiday/import') ?>',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(res) {
                console.log('Import response:', res);
                try {
                    let response = typeof res === 'object' ? res : JSON.parse(res);
                    Swal.fire({
                        icon: response.success ? 'success' : 'error',
                        title: response.success ? 'Import Complete' : 'Error',
                        text: response.message
                    }).then(() => {
                        if (response.success) location.reload();
                    });
                } catch(e) {
                    console.error('Parse error:', e, res);
                    Swal.fire('Error', 'Invalid response from server.', 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('Import error:', status, error, xhr.responseText);
                Swal.fire('Error', 'Import failed: ' + error, 'error');
            }
        });
    });
});

// Reset search function
function resetSearch() {
    $('#holidayTable .column-search').val('');
    $('#holidayTable tbody tr:not(.no-holidays)').show();
    
    // Reset row numbers
    let visibleIndex = 1;
    $('#holidayTable tbody tr:not(.no-holidays)').each(function() {
        $(this).find('td').first().text(visibleIndex++);
    });
}
</script>

