<?php
/**
 * Enterprise HRM ERP System - Leave Management List
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

$pageTitle = 'Leave Management';
$currentModule = 'leave';
$currentTab = 'leave_form';

$siteId = getCurrentSiteId();
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Filters
$search = sanitize($_GET['search'] ?? '');
$status = sanitize($_GET['status'] ?? '');

$db = getDB();

// Handle save "To" name POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_to_name'])) {
    try {
        $toName = trim($_POST['to_name'] ?? '');
        
        // Create table if not exists
        $db->exec("
            CREATE TABLE IF NOT EXISTS `leave_to_names` (
                `id` int(11) NOT NULL AUTO_INCREMENT,
                `site_id` int(11) NOT NULL,
                `to_name` varchar(255) DEFAULT NULL,
                `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
                `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (`id`),
                UNIQUE KEY `unique_site` (`site_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        
        // Check if record exists for this site
        $checkStmt = $db->prepare("SELECT id FROM leave_to_names WHERE site_id = ?");
        $checkStmt->execute([$siteId]);
        $existing = $checkStmt->fetch();
        
        if ($existing) {
            $updateStmt = $db->prepare("UPDATE leave_to_names SET to_name = ? WHERE site_id = ?");
            $updateStmt->execute([$toName, $siteId]);
        } else {
            $insertStmt = $db->prepare("INSERT INTO leave_to_names (site_id, to_name) VALUES (?, ?)");
            $insertStmt->execute([$siteId, $toName]);
        }
        
        $_SESSION['success_message'] = 'To Name saved successfully!';
        $redirectUrl = $_SERVER['PHP_SELF'] . '?to_saved=1';
        if (!empty($search)) $redirectUrl .= '&search=' . urlencode($search);
        if (!empty($status)) $redirectUrl .= '&status=' . urlencode($status);
        header('Location: ' . $redirectUrl);
        exit;
    } catch (Exception $e) {
        error_log("Error saving leave To Name: " . $e->getMessage());
        $_SESSION['error_message'] = 'Error saving To Name: ' . $e->getMessage();
    }
}

// Fetch current To name for this site
$currentToName = '';
try {
    // Create table if not exists
    $db->exec("
        CREATE TABLE IF NOT EXISTS `leave_to_names` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `site_id` int(11) NOT NULL,
            `to_name` varchar(255) DEFAULT NULL,
            `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
            `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            UNIQUE KEY `unique_site` (`site_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");
    
    $toNameStmt = $db->prepare("SELECT to_name FROM leave_to_names WHERE site_id = ?");
    $toNameStmt->execute([$siteId]);
    $toNameRecord = $toNameStmt->fetch();
    $currentToName = $toNameRecord ? $toNameRecord['to_name'] : '';
} catch (Exception $e) {
    error_log("Error fetching leave To Name: " . $e->getMessage());
}

// Handle Excel Export
if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    // Get "To" name for this site
    $exportToName = '';
    try {
        $toNameStmt = $db->prepare("SELECT to_name FROM leave_to_names WHERE site_id = ?");
        $toNameStmt->execute([$siteId]);
        $toNameRecord = $toNameStmt->fetch();
        $exportToName = $toNameRecord ? $toNameRecord['to_name'] : '';
    } catch (Exception $e) {
        // Table might not exist yet
    }
    
    // Build filename
    $exportFilename = 'Leave_Applications_' . date('Ymd_His');
    
    // Build query for export (no pagination)
    $exportWhere = ["la.site_id = ?"];
    $exportParams = [$siteId];
    
    if (!empty($search)) {
        $exportWhere[] = "(e.employee_code LIKE ? OR e.first_name LIKE ? OR e.last_name LIKE ?)";
        $searchParam = "%{$search}%";
        $exportParams = array_merge($exportParams, [$searchParam, $searchParam, $searchParam]);
    }
    
    if (!empty($status)) {
        $exportWhere[] = "la.application_status = ?";
        $exportParams[] = $status;
    }
    
    $exportWhereClause = implode(' AND ', $exportWhere);
    
    $exportSql = "
        SELECT 
            la.*,
            e.employee_code,
            CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as employee_name,
            d.designation_name,
            lt.leave_type_name
        FROM leave_applications la
        INNER JOIN employees e ON la.employee_id = e.employee_id
        LEFT JOIN designations d ON e.designation_id = d.designation_id
        LEFT JOIN leave_types lt ON la.leave_type_id = lt.leave_type_id
        WHERE {$exportWhereClause}
        ORDER BY la.applied_at DESC
    ";
    
    $exportStmt = $db->prepare($exportSql);
    $exportStmt->execute($exportParams);
    $exportLeaves = $exportStmt->fetchAll();
    
    // Get site name
    $siteStmt = $db->prepare("SELECT site_name FROM sites WHERE site_id = ?");
    $siteStmt->execute([$siteId]);
    $siteData = $siteStmt->fetch();
    $exportSiteName = $siteData['site_name'] ?? '';
    
    // Output Excel (HTML format)
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="' . $exportFilename . '.xls"');
    header('Cache-Control: max-age=0');
    
    echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">';
    echo '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
    echo '<style>
        table { border-collapse: collapse; width: 100%; font-family: Arial, sans-serif; font-size: 10pt; }
        th { background-color: #1e40af; color: white; font-weight: bold; padding: 8px; text-align: center; border: 1px solid #000; }
        td { padding: 5px; border: 1px solid #ccc; text-align: left; }
        .to-name { font-weight: bold; font-size: 12pt; padding: 10px; border: none; }
        .site-info { font-weight: bold; font-size: 11pt; padding: 5px; border: none; }
        .status-pending { background-color: #fef3c7 !important; color: #92400e; }
        .status-approved { background-color: #d1fae5 !important; color: #065f46; }
        .status-rejected { background-color: #fee2e2 !important; color: #991b1b; }
        .status-cancelled { background-color: #e5e7eb !important; color: #374151; }
        .sl-cell { text-align: center; font-weight: bold; }
    </style></head><body>';
    
    // Add "To" name row at top if exists
    if (!empty($exportToName)) {
        echo '<table style="margin-bottom: 10px; border: none;">';
        echo '<tr><td class="to-name" style="border: none;"><strong>To:</strong> ' . htmlspecialchars($exportToName) . '</td></tr>';
        echo '</table>';
    }
    
    // Add site info
    echo '<table style="margin-bottom: 10px; border: none;">';
    echo '<tr><td class="site-info" style="border: none;">Site: ' . htmlspecialchars($exportSiteName) . ' | Export Date: ' . date('d-m-Y H:i') . '</td></tr>';
    echo '</table>';
    
    echo '<table>';
    
    // Header Row
    echo '<tr>';
    echo '<th>Sl No</th>';
    echo '<th>Emp Code</th>';
    echo '<th>Employee Name</th>';
    echo '<th>Designation</th>';
    echo '<th>Leave Type</th>';
    echo '<th>Start Date</th>';
    echo '<th>End Date</th>';
    echo '<th>Total Days</th>';
    echo '<th>Reason</th>';
    echo '<th>Status</th>';
    echo '<th>Applied Date</th>';
    echo '<th>Approved By</th>';
    echo '<th>Remarks</th>';
    echo '</tr>';
    
    // Data rows
    $slNo = 1;
    foreach ($exportLeaves as $leave) {
        $statusClass = 'status-' . ($leave['application_status'] ?? 'pending');
        
        echo '<tr>';
        echo '<td class="sl-cell">' . $slNo++ . '</td>';
        echo '<td>' . htmlspecialchars($leave['employee_code'] ?? '') . '</td>';
        echo '<td>' . htmlspecialchars($leave['employee_name'] ?? '') . '</td>';
        echo '<td>' . htmlspecialchars($leave['designation_name'] ?? '') . '</td>';
        echo '<td>' . htmlspecialchars($leave['leave_type_name'] ?? 'N/A') . '</td>';
        echo '<td>' . ($leave['start_date'] ? date('d-m-Y', strtotime($leave['start_date'])) : '') . '</td>';
        echo '<td>' . ($leave['end_date'] ? date('d-m-Y', strtotime($leave['end_date'])) : '') . '</td>';
        echo '<td style="text-align: center;">' . number_format($leave['total_days'] ?? 0, 1) . '</td>';
        echo '<td>' . htmlspecialchars($leave['reason'] ?? '') . '</td>';
        echo '<td class="' . $statusClass . '">' . ucfirst($leave['application_status'] ?? 'pending') . '</td>';
        echo '<td>' . ($leave['applied_at'] ? date('d-m-Y H:i', strtotime($leave['applied_at'])) : '') . '</td>';
        echo '<td>' . htmlspecialchars($leave['approved_by_name'] ?? '') . '</td>';
        echo '<td>' . htmlspecialchars($leave['approval_remarks'] ?? '') . '</td>';
        echo '</tr>';
    }
    
    // Summary row
    $pendingCount = 0;
    $approvedCount = 0;
    $rejectedCount = 0;
    $cancelledCount = 0;
    foreach ($exportLeaves as $leave) {
        switch ($leave['application_status'] ?? 'pending') {
            case 'pending': $pendingCount++; break;
            case 'approved': $approvedCount++; break;
            case 'rejected': $rejectedCount++; break;
            case 'cancelled': $cancelledCount++; break;
        }
    }
    
    echo '<tr style="font-weight: bold; background-color: #e5e7eb;">';
    echo '<td colspan="9" style="text-align: right;">Total: ' . count($exportLeaves) . ' applications</td>';
    echo '<td colspan="4">Pending: ' . $pendingCount . ' | Approved: ' . $approvedCount . ' | Rejected: ' . $rejectedCount . ' | Cancelled: ' . $cancelledCount . '</td>';
    echo '</tr>';
    
    echo '</table></body></html>';
    exit;
}

// Build query
$where = ["la.site_id = ?"];
$params = [$siteId];

if (!empty($search)) {
    $where[] = "(e.employee_code LIKE ? OR e.first_name LIKE ? OR e.last_name LIKE ?)";
    $searchParam = "%{$search}%";
    $params = array_merge($params, [$searchParam, $searchParam, $searchParam]);
}

if (!empty($status)) {
    $where[] = "la.application_status = ?";
    $params[] = $status;
}

$whereClause = implode(' AND ', $where);

try {
    // Get total count
    $countSql = "
        SELECT COUNT(*) 
        FROM leave_applications la
        INNER JOIN employees e ON la.employee_id = e.employee_id
        WHERE {$whereClause}
    ";
    $stmt = $db->prepare($countSql);
    $stmt->execute($params);
    $totalRecords = $stmt->fetchColumn();
    $totalPages = ceil($totalRecords / $perPage);
    
    // Get leave applications
    $sql = "
        SELECT 
            la.*,
            e.employee_code,
            CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as employee_name,
            lt.leave_type_name
        FROM leave_applications la
        INNER JOIN employees e ON la.employee_id = e.employee_id
        LEFT JOIN leave_types lt ON la.leave_type_id = lt.leave_type_id
        WHERE {$whereClause}
        ORDER BY la.applied_at DESC
        LIMIT ? OFFSET ?
    ";
    $params[] = $perPage;
    $params[] = $offset;
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $leaves = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Leave list error: " . $e->getMessage());
    $leaves = [];
    $totalRecords = 0;
    $totalPages = 0;
}

include __DIR__ . '/../../includes/header.php';
include __DIR__ . '/../payroll/_navigation.php';
?>

<div class="table-container">
    <div class="table-header">
        <h2 class="table-title">Leave Applications</h2>
        <div class="table-actions" style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
            <!-- To Name Input Field -->
            <form method="POST" style="display: inline-flex; align-items: center; gap: 4px; background: #1e3a5f; padding: 4px 8px; border-radius: 4px;">
                <label style="font-size: 11px; color: #fff; font-weight: 500;">To:</label>
                <input type="text" name="to_name" value="<?php echo htmlspecialchars($currentToName); ?>" 
                       placeholder="Name" 
                       style="padding: 4px 6px; border: 1px solid #ccc; border-radius: 3px; font-size: 11px; width: 100px; background: white; color: #333;">
                <button type="submit" name="save_to_name" 
                        style="padding: 4px 6px; font-size: 10px; background: #28a745; border: none; color: white; border-radius: 3px; cursor: pointer;" 
                        title="Save To Name">
                    ✓
                </button>
            </form>
            
            <button type="button" class="btn-export" onclick="exportToExcel()" title="Export to Excel" style="background: #28a745; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 12px; font-weight: 500; display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;">
                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
                Export
            </button>
            
            <a href="<?php echo BASE_URL; ?>/modules/leave/create.php" class="btn btn-primary">Apply for Leave</a>
        </div>
    </div>
    
    <div class="table-filters">
        <div class="filter-group">
            <label>Search Employee</label>
            <input type="text" name="search" class="form-control" placeholder="Employee Code or Name..." 
                   value="<?php echo htmlspecialchars($search); ?>" 
                   onkeypress="if(event.key==='Enter') filterTable()">
        </div>
        <div class="filter-group">
            <label>Status</label>
            <select name="status" class="form-control" onchange="filterTable()">
                <option value="">All Status</option>
                <option value="pending" <?php echo $status === 'pending' ? 'selected' : ''; ?>>Pending</option>
                <option value="approved" <?php echo $status === 'approved' ? 'selected' : ''; ?>>Approved</option>
                <option value="rejected" <?php echo $status === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                <option value="cancelled" <?php echo $status === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
            </select>
        </div>
        <div class="filter-group">
            <button type="button" class="btn btn-secondary" onclick="resetFilters()">Reset</button>
        </div>
    </div>
    
    <?php if (count($leaves) > 0): ?>
    
    <!-- Scroll Buttons -->
    <div class="table-scroll-controls">
        <button type="button" class="scroll-btn scroll-left" onclick="scrollTableLeft()" title="Scroll Left">
            ◀
        </button>
        <span class="scroll-hint">← Swipe or use buttons to scroll →</span>
        <button type="button" class="scroll-btn scroll-right" onclick="scrollTableRight()" title="Scroll Right">
            ▶
        </button>
    </div>
    
    <!-- Scrollable Table Wrapper -->
    <div class="table-scroll-wrapper" id="tableScrollWrapper">
        <table class="data-table">
            <thead>
                <tr>
                    <th class="sortable">Employee</th>
                    <th class="sortable">Leave Type</th>
                    <th class="sortable">Start Date</th>
                    <th class="sortable">End Date</th>
                    <th class="sortable">Total Days</th>
                    <th class="sortable">Status</th>
                    <th class="sortable">Applied Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($leaves as $leave): ?>
                <tr>
                    <td>
                        <strong><?php echo htmlspecialchars($leave['employee_code']); ?></strong><br>
                        <small><?php echo htmlspecialchars($leave['employee_name']); ?></small>
                    </td>
                    <td><?php echo htmlspecialchars($leave['leave_type_name'] ?? 'N/A'); ?></td>
                    <td><?php echo formatDate($leave['start_date']); ?></td>
                    <td><?php echo formatDate($leave['end_date']); ?></td>
                    <td><?php echo number_format($leave['total_days'], 1); ?> days</td>
                    <td>
                        <span class="status-badge status-<?php echo htmlspecialchars($leave['application_status']); ?>">
                            <?php echo ucfirst($leave['application_status']); ?>
                        </span>
                    </td>
                    <td><?php echo formatDateTime($leave['applied_at']); ?></td>
                    <td class="table-actions-cell">
                        <a href="<?php echo BASE_URL; ?>/modules/leave/view.php?id=<?php echo $leave['leave_application_id']; ?>" 
                           class="btn btn-sm btn-secondary">View</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    
    <div class="table-footer">
        <div class="table-info">
            Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $perPage, $totalRecords); ?> of <?php echo number_format($totalRecords); ?> applications
        </div>
        <div class="pagination">
            <?php if ($page > 1): ?>
            <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>" 
               class="btn btn-sm">Previous</a>
            <?php endif; ?>
            <span class="pagination-info">Page <?php echo $page; ?> of <?php echo $totalPages; ?></span>
            <?php if ($page < $totalPages): ?>
            <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>" 
               class="btn btn-sm">Next</a>
            <?php endif; ?>
        </div>
    </div>
    <?php else: ?>
    <div class="table-empty">
        <div class="table-empty-icon">📅</div>
        <div class="table-empty-message">No leave applications found</div>
        <div class="table-empty-submessage">
            <a href="<?php echo BASE_URL; ?>/modules/leave/create.php" class="btn btn-primary">Apply for Leave</a>
        </div>
    </div>
    <?php endif; ?>
</div>

<style>
/* Status Badges */
.status-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 11px;
    font-weight: 500;
    text-transform: uppercase;
}

.status-pending {
    background-color: #fef3c7;
    color: #92400e;
}

.status-approved {
    background-color: #d1fae5;
    color: #065f46;
}

.status-rejected {
    background-color: #fee2e2;
    color: #991b1b;
}

.status-cancelled {
    background-color: #e5e7eb;
    color: #374151;
}

/* Export Button */
.btn-export {
    background: #28a745;
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    white-space: nowrap;
}

.btn-export:hover {
    background: #218838;
}

.btn-export:disabled {
    background: #6c757d;
    cursor: not-allowed;
    opacity: 0.6;
}

/* ========== Table Horizontal Scroll Styles ========== */

/* Scroll Controls */
.table-scroll-controls {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 15px;
    padding: 10px 0;
    margin-bottom: 5px;
    background: linear-gradient(90deg, #f0f9ff 0%, #e0f2fe 50%, #f0f9ff 100%);
    border-radius: 8px;
}

.scroll-btn {
    width: 36px;
    height: 36px;
    border: 2px solid #1e40af;
    background: white;
    color: #1e40af;
    border-radius: 50%;
    cursor: pointer;
    font-size: 14px;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.scroll-btn:hover {
    background: #1e40af;
    color: white;
    transform: scale(1.1);
}

.scroll-btn:active {
    transform: scale(0.95);
}

.scroll-hint {
    font-size: 12px;
    color: #64748b;
    font-style: italic;
}

/* Scrollable Table Wrapper */
.table-scroll-wrapper {
    overflow-x: auto;
    overflow-y: visible;
    -webkit-overflow-scrolling: touch; /* Smooth scrolling on iOS */
    scroll-behavior: smooth;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    background: white;
    position: relative;
}

/* Custom Scrollbar */
.table-scroll-wrapper::-webkit-scrollbar {
    height: 10px;
}

.table-scroll-wrapper::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 5px;
}

.table-scroll-wrapper::-webkit-scrollbar-thumb {
    background: linear-gradient(90deg, #1e40af, #3b82f6);
    border-radius: 5px;
    border: 2px solid #f1f5f9;
}

.table-scroll-wrapper::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(90deg, #1e3a8a, #2563eb);
}

/* Firefox scrollbar */
.table-scroll-wrapper {
    scrollbar-width: thin;
    scrollbar-color: #1e40af #f1f5f9;
}

/* Ensure table doesn't shrink */
.table-scroll-wrapper .data-table {
    min-width: 900px; /* Minimum width to enable scroll */
    width: 100%;
    margin: 0;
    border: none;
}

/* Scroll shadow indicators */
.table-scroll-wrapper::before,
.table-scroll-wrapper::after {
    content: '';
    position: absolute;
    top: 0;
    bottom: 10px;
    width: 30px;
    pointer-events: none;
    z-index: 10;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.table-scroll-wrapper::before {
    left: 0;
    background: linear-gradient(to right, rgba(0,0,0,0.1), transparent);
}

.table-scroll-wrapper::after {
    right: 0;
    background: linear-gradient(to left, rgba(0,0,0,0.1), transparent);
}

.table-scroll-wrapper.scroll-left::before,
.table-scroll-wrapper.scroll-right::after {
    opacity: 1;
}

/* Mobile Responsive */
@media (max-width: 768px) {
    .table-scroll-controls {
        padding: 8px 10px;
        gap: 10px;
    }
    
    .scroll-btn {
        width: 32px;
        height: 32px;
        font-size: 12px;
    }
    
    .scroll-hint {
        font-size: 11px;
    }
    
    .table-scroll-wrapper .data-table {
        min-width: 800px;
    }
    
    .table-scroll-wrapper::-webkit-scrollbar {
        height: 8px;
    }
}

@media (max-width: 480px) {
    .scroll-hint {
        display: none;
    }
    
    .table-scroll-controls {
        justify-content: space-between;
        padding: 8px 15px;
    }
    
    .scroll-btn {
        width: 40px;
        height: 40px;
        font-size: 16px;
    }
}
</style>

<script>
function filterTable() {
    const search = document.querySelector('[name="search"]').value;
    const status = document.querySelector('[name="status"]').value;
    
    const params = new URLSearchParams();
    if (search) params.append('search', search);
    if (status) params.append('status', status);
    
    window.location.href = '?' + params.toString();
}

function resetFilters() {
    window.location.href = '<?php echo BASE_URL; ?>/modules/leave/list.php';
}

function exportToExcel() {
    const btn = document.querySelector('.btn-export');
    if (!btn) return;
    
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg> Exporting...';
    
    // Get current filter values
    const search = document.querySelector('[name="search"]').value;
    const status = document.querySelector('[name="status"]').value;
    
    // Build export URL with current filters
    let exportUrl = window.location.pathname + '?export=excel';
    if (search) {
        exportUrl += '&search=' + encodeURIComponent(search);
    }
    if (status) {
        exportUrl += '&status=' + encodeURIComponent(status);
    }
    
    // Trigger download
    window.location.href = exportUrl;
    
    // Reset button after a short delay
    setTimeout(function() {
        btn.disabled = false;
        btn.innerHTML = originalText;
    }, 2000);
}

// ========== Table Scroll Functions ==========

const scrollAmount = 200; // Pixels to scroll per click

function scrollTableLeft() {
    const wrapper = document.getElementById('tableScrollWrapper');
    if (wrapper) {
        wrapper.scrollBy({
            left: -scrollAmount,
            behavior: 'smooth'
        });
    }
}

function scrollTableRight() {
    const wrapper = document.getElementById('tableScrollWrapper');
    if (wrapper) {
        wrapper.scrollBy({
            left: scrollAmount,
            behavior: 'smooth'
        });
    }
}

// Update scroll indicators
function updateScrollIndicators() {
    const wrapper = document.getElementById('tableScrollWrapper');
    if (!wrapper) return;
    
    const scrollLeft = wrapper.scrollLeft;
    const maxScroll = wrapper.scrollWidth - wrapper.clientWidth;
    
    // Add/remove classes based on scroll position
    if (scrollLeft > 5) {
        wrapper.classList.add('scroll-left');
    } else {
        wrapper.classList.remove('scroll-left');
    }
    
    if (scrollLeft < maxScroll - 5) {
        wrapper.classList.add('scroll-right');
    } else {
        wrapper.classList.remove('scroll-right');
    }
    
    // Update button states
    const leftBtn = document.querySelector('.scroll-left');
    const rightBtn = document.querySelector('.scroll-right');
    
    if (leftBtn) {
        leftBtn.style.opacity = scrollLeft <= 0 ? '0.5' : '1';
    }
    if (rightBtn) {
        rightBtn.style.opacity = scrollLeft >= maxScroll ? '0.5' : '1';
    }
}

// Initialize scroll indicators on page load
document.addEventListener('DOMContentLoaded', function() {
    const wrapper = document.getElementById('tableScrollWrapper');
    if (wrapper) {
        // Initial check
        updateScrollIndicators();
        
        // Update on scroll
        wrapper.addEventListener('scroll', updateScrollIndicators);
        
        // Update on window resize
        window.addEventListener('resize', updateScrollIndicators);
        
        // Keyboard navigation
        wrapper.setAttribute('tabindex', '0');
        wrapper.addEventListener('keydown', function(e) {
            if (e.key === 'ArrowLeft') {
                scrollTableLeft();
                e.preventDefault();
            } else if (e.key === 'ArrowRight') {
                scrollTableRight();
                e.preventDefault();
            }
        });
    }
});
</script>

<?php include __DIR__ . '/../../includes/footer.php'; ?>

