<?php
/**
 * Enterprise HRM ERP System - Employee Overtime Sheet
 * Month-wise and year-wise overtime tracking with grid view
 */

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

$pageTitle = 'Employee Overtime Sheet';
$currentModule = 'overtime';
$currentTab = 'overtime';

$siteId = getCurrentSiteId();

// Get site name
$db = getDB();
$stmt = $db->prepare("SELECT site_name FROM sites WHERE site_id = ?");
$stmt->execute([$siteId]);
$site = $stmt->fetch();
$siteName = $site ? $site['site_name'] : 'Base Office';

// Get filter parameters
$selectedMonth = isset($_GET['month']) ? sanitize($_GET['month']) : date('m');
$selectedYear = isset($_GET['year']) ? sanitize($_GET['year']) : date('Y');
$statusFilter = isset($_GET['status']) ? sanitize($_GET['status']) : 'active'; // Default to active
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';

// Validate inputs
$selectedMonth = (int)$selectedMonth;
$selectedYear = (int)$selectedYear;
if ($selectedMonth < 1 || $selectedMonth > 12) $selectedMonth = (int)date('m');
if ($selectedYear < 2000 || $selectedYear > 2100) $selectedYear = (int)date('Y');

// Format month name for display
$monthName = date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear));
$attendanceMonth = date('M-y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); // Format: Jan-26

// Get number of days in selected month
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $selectedMonth, $selectedYear);

// Auto-create overtime_monthly_grid table if it doesn't exist
try {
    $checkTable = $db->query("SHOW TABLES LIKE 'overtime_monthly_grid'");
    if ($checkTable->rowCount() == 0) {
        // Create the table
        $createTableSQL = "
        CREATE TABLE IF NOT EXISTS `overtime_monthly_grid` (
          `overtime_grid_id` int(11) NOT NULL AUTO_INCREMENT,
          `site_id` int(11) NOT NULL,
          `employee_id` int(11) NOT NULL,
          `attendance_month` varchar(20) NOT NULL COMMENT 'Format: Jan-26',
          `emp_id` varchar(50),
          `designation` varchar(255),
          `day_1` decimal(5,2) DEFAULT 0.00,
          `day_2` decimal(5,2) DEFAULT 0.00,
          `day_3` decimal(5,2) DEFAULT 0.00,
          `day_4` decimal(5,2) DEFAULT 0.00,
          `day_5` decimal(5,2) DEFAULT 0.00,
          `day_6` decimal(5,2) DEFAULT 0.00,
          `day_7` decimal(5,2) DEFAULT 0.00,
          `day_8` decimal(5,2) DEFAULT 0.00,
          `day_9` decimal(5,2) DEFAULT 0.00,
          `day_10` decimal(5,2) DEFAULT 0.00,
          `day_11` decimal(5,2) DEFAULT 0.00,
          `day_12` decimal(5,2) DEFAULT 0.00,
          `day_13` decimal(5,2) DEFAULT 0.00,
          `day_14` decimal(5,2) DEFAULT 0.00,
          `day_15` decimal(5,2) DEFAULT 0.00,
          `day_16` decimal(5,2) DEFAULT 0.00,
          `day_17` decimal(5,2) DEFAULT 0.00,
          `day_18` decimal(5,2) DEFAULT 0.00,
          `day_19` decimal(5,2) DEFAULT 0.00,
          `day_20` decimal(5,2) DEFAULT 0.00,
          `day_21` decimal(5,2) DEFAULT 0.00,
          `day_22` decimal(5,2) DEFAULT 0.00,
          `day_23` decimal(5,2) DEFAULT 0.00,
          `day_24` decimal(5,2) DEFAULT 0.00,
          `day_25` decimal(5,2) DEFAULT 0.00,
          `day_26` decimal(5,2) DEFAULT 0.00,
          `day_27` decimal(5,2) DEFAULT 0.00,
          `day_28` decimal(5,2) DEFAULT 0.00,
          `day_29` decimal(5,2) DEFAULT 0.00,
          `day_30` decimal(5,2) DEFAULT 0.00,
          `day_31` decimal(5,2) DEFAULT 0.00,
          `overtime_rate` decimal(10,2) DEFAULT 0.00,
          `earn_amount` decimal(15,2) DEFAULT 0.00,
          `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
          `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          PRIMARY KEY (`overtime_grid_id`),
          UNIQUE KEY `unique_emp_ot_month` (`employee_id`,`attendance_month`),
          KEY `fk_omg_site` (`site_id`),
          KEY `fk_omg_emp` (`employee_id`),
          CONSTRAINT `fk_omg_site` FOREIGN KEY (`site_id`) REFERENCES `sites` (`site_id`) ON DELETE RESTRICT,
          CONSTRAINT `fk_omg_emp` FOREIGN KEY (`employee_id`) REFERENCES `employees` (`employee_id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
        ";
        
        $db->exec($createTableSQL);
        error_log("Overtime monthly grid table created automatically");
    }
} catch (Exception $e) {
    error_log("Error creating overtime_monthly_grid table: " . $e->getMessage());
}

// 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 `overtime_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 overtime_to_names WHERE site_id = ?");
        $checkStmt->execute([$siteId]);
        $existing = $checkStmt->fetch();
        
        if ($existing) {
            $updateStmt = $db->prepare("UPDATE overtime_to_names SET to_name = ? WHERE site_id = ?");
            $updateStmt->execute([$toName, $siteId]);
        } else {
            $insertStmt = $db->prepare("INSERT INTO overtime_to_names (site_id, to_name) VALUES (?, ?)");
            $insertStmt->execute([$siteId, $toName]);
        }
        
        $_SESSION['success_message'] = 'To Name saved successfully!';
        header('Location: ' . $_SERVER['PHP_SELF'] . '?month=' . $selectedMonth . '&year=' . $selectedYear . '&status=' . $statusFilter . '&to_saved=1');
        exit;
    } catch (Exception $e) {
        error_log("Error saving overtime 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 `overtime_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 overtime_to_names WHERE site_id = ?");
    $toNameStmt->execute([$siteId]);
    $toNameRecord = $toNameStmt->fetch();
    $currentToName = $toNameRecord ? $toNameRecord['to_name'] : '';
} catch (Exception $e) {
    error_log("Error fetching overtime 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 overtime_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 = 'Overtime_' . date('M_Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)) . '_' . date('Ymd_His');
    
    // Get employees with overtime data for export
    $whereConditions = ["e.site_id = ?"];
    $queryParams = [$siteId];
    
    if ($statusFilter === 'active') {
        $whereConditions[] = "e.employment_status = 'active'";
    } elseif ($statusFilter === 'inactive') {
        $whereConditions[] = "e.employment_status = 'inactive'";
    }
    
    if (!empty($search)) {
        $whereConditions[] = "(e.employee_code LIKE ? OR e.first_name LIKE ? OR e.last_name LIKE ? OR CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) LIKE ?)";
        $searchParam = "%{$search}%";
        $queryParams = array_merge($queryParams, [$searchParam, $searchParam, $searchParam, $searchParam]);
    }
    
    $whereClause = implode(' AND ', $whereConditions);
    
    $exportStmt = $db->prepare("
        SELECT 
            e.employee_id,
            e.employee_code,
            e.first_name,
            e.last_name,
            e.middle_name,
            d.designation_name
        FROM employees e
        LEFT JOIN designations d ON e.designation_id = d.designation_id
        WHERE {$whereClause}
        ORDER BY e.employee_code ASC
    ");
    $exportStmt->execute($queryParams);
    $exportEmployees = $exportStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get overtime data for each employee
    foreach ($exportEmployees as &$emp) {
        $otStmt = $db->prepare("SELECT * FROM overtime_monthly_grid WHERE employee_id = ? AND attendance_month = ?");
        $otStmt->execute([$emp['employee_id'], $attendanceMonth]);
        $otData = $otStmt->fetch(PDO::FETCH_ASSOC);
        
        if ($otData) {
            for ($day = 1; $day <= 31; $day++) {
                $emp['day_' . $day] = (float)($otData['day_' . $day] ?? 0);
            }
            $emp['overtime_rate'] = (float)($otData['overtime_rate'] ?? 0);
            $emp['earn_amount'] = (float)($otData['earn_amount'] ?? 0);
        } else {
            for ($day = 1; $day <= 31; $day++) {
                $emp['day_' . $day] = 0;
            }
            $emp['overtime_rate'] = 0;
            $emp['earn_amount'] = 0;
        }
    }
    unset($emp);
    
    // 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: #1e3a5f; color: white; font-weight: bold; padding: 8px; text-align: center; border: 1px solid #000; }
        td { padding: 5px; border: 1px solid #ccc; text-align: center; }
        .day-header { background-color: #1e293b !important; color: white !important; }
        .rate-header { background-color: #f59e0b !important; color: white !important; }
        .earn-header { background-color: #10b981 !important; color: white !important; }
        .name-cell { text-align: left; background-color: #f9fafb !important; }
        .emp-id-cell { background-color: #f9fafb !important; font-weight: bold; }
        .earn-amount { background-color: #d1fae5 !important; font-weight: bold; color: #065f46; }
        .to-name { font-weight: bold; font-size: 12pt; padding: 10px; border: none; }
        .sl-cell { background-color: #fef3c7 !important; 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 month info
    echo '<table style="margin-bottom: 10px; border: none;">';
    echo '<tr><td style="border: none; font-weight: bold; font-size: 11pt;">Overtime Sheet - ' . htmlspecialchars($monthName) . '</td></tr>';
    echo '</table>';
    
    echo '<table>';
    
    // Header Row
    echo '<tr>';
    echo '<th style="background-color: #f59e0b;">Sl. No</th>';
    echo '<th style="background-color: #f59e0b;">Emp ID</th>';
    echo '<th style="background-color: #f59e0b;">Name</th>';
    echo '<th style="background-color: #f59e0b;">Designation</th>';
    for ($day = 1; $day <= 31; $day++) {
        echo '<th class="day-header">' . $day . '</th>';
    }
    echo '<th class="rate-header">OT Rate</th>';
    echo '<th class="earn-header">Earn Amount</th>';
    echo '</tr>';
    
    // Data rows
    $slNo = 1;
    foreach ($exportEmployees as $emp) {
        $fullName = trim(($emp['first_name'] ?? '') . ' ' . ($emp['middle_name'] ?? '') . ' ' . ($emp['last_name'] ?? ''));
        
        echo '<tr>';
        echo '<td class="sl-cell">' . $slNo++ . '</td>';
        echo '<td class="emp-id-cell">' . htmlspecialchars($emp['employee_code'] ?? '') . '</td>';
        echo '<td class="name-cell">' . htmlspecialchars($fullName) . '</td>';
        echo '<td>' . htmlspecialchars($emp['designation_name'] ?? 'N/A') . '</td>';
        
        $totalHours = 0;
        for ($day = 1; $day <= 31; $day++) {
            $hours = (float)($emp['day_' . $day] ?? 0);
            $totalHours += $hours;
            $bgColor = $hours > 0 ? '#fef3c7' : '';
            echo '<td style="' . ($bgColor ? 'background-color: ' . $bgColor . ';' : '') . '">' . ($hours > 0 ? $hours : '-') . '</td>';
        }
        
        echo '<td style="background-color: #fef3c7; font-weight: bold;">' . number_format($emp['overtime_rate'], 2) . '</td>';
        echo '<td class="earn-amount">' . number_format($emp['earn_amount'], 2) . '</td>';
        echo '</tr>';
    }
    
    // Total row
    echo '<tr style="font-weight: bold; background-color: #e5e7eb;">';
    echo '<td colspan="4" style="text-align: right;">Total:</td>';
    $grandTotalHours = 0;
    $grandTotalEarn = 0;
    for ($day = 1; $day <= 31; $day++) {
        $dayTotal = 0;
        foreach ($exportEmployees as $emp) {
            $dayTotal += (float)($emp['day_' . $day] ?? 0);
        }
        $grandTotalHours += $dayTotal;
        echo '<td>' . ($dayTotal > 0 ? $dayTotal : '-') . '</td>';
    }
    echo '<td>-</td>';
    foreach ($exportEmployees as $emp) {
        $grandTotalEarn += (float)($emp['earn_amount'] ?? 0);
    }
    echo '<td class="earn-amount">' . number_format($grandTotalEarn, 2) . '</td>';
    echo '</tr>';
    
    echo '</table></body></html>';
    exit;
}

// Handle form submission - Save overtime data
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_overtime'])) {
    try {
        $employeeId = (int)($_POST['employee_id'] ?? 0);
        $overtimeRate = (float)($_POST['overtime_rate'] ?? 0);
        
        if ($employeeId <= 0) {
            throw new Exception('Invalid employee ID');
        }
        
        $userId = getCurrentUserId();
    
        // Get employee details
        $empStmt = $db->prepare("SELECT employee_code, first_name, last_name FROM employees WHERE employee_id = ? AND site_id = ?");
        $empStmt->execute([$employeeId, $siteId]);
        $employee = $empStmt->fetch();
        
        if (!$employee) {
            throw new Exception('Employee not found');
        }
        
        // Get designation name if available
        $designationName = '';
        $desigStmt = $db->prepare("SELECT d.designation_name FROM employees e LEFT JOIN designations d ON e.designation_id = d.designation_id WHERE e.employee_id = ?");
        $desigStmt->execute([$employeeId]);
        $desig = $desigStmt->fetch();
        if ($desig) {
            $designationName = $desig['designation_name'];
        }
        
        // Collect day values (day_1 to day_31)
        $dayValues = [];
        $totalHours = 0;
        for ($day = 1; $day <= 31; $day++) {
            $dayKey = 'day_' . $day;
            $hours = isset($_POST[$dayKey]) ? (float)$_POST[$dayKey] : 0;
            $dayValues[$dayKey] = $hours;
            $totalHours += $hours;
        }
        
        // Calculate earn amount
        $earnAmount = round($totalHours * $overtimeRate, 2);
        
        // Check if record exists
        $checkStmt = $db->prepare("SELECT overtime_grid_id FROM overtime_monthly_grid WHERE employee_id = ? AND attendance_month = ?");
        $checkStmt->execute([$employeeId, $attendanceMonth]);
        $existing = $checkStmt->fetch();
        
        if ($existing) {
            // Update existing record
            $updateFields = [];
            $updateValues = [];
            
            foreach ($dayValues as $dayKey => $hours) {
                $updateFields[] = "`{$dayKey}` = ?";
                $updateValues[] = $hours;
            }
            
            $updateFields[] = "`overtime_rate` = ?";
            $updateValues[] = $overtimeRate;
            
            $updateFields[] = "`earn_amount` = ?";
            $updateValues[] = $earnAmount;
            
            $updateFields[] = "`updated_at` = NOW()";
            
            $updateValues[] = $employeeId;
            $updateValues[] = $attendanceMonth;
            
            $sql = "UPDATE overtime_monthly_grid SET " . implode(', ', $updateFields) . 
                   " WHERE employee_id = ? AND attendance_month = ?";
            
            $updateStmt = $db->prepare($sql);
            $updateStmt->execute($updateValues);
            
            $action = 'updated';
        } else {
            // Insert new record
            $dayColumns = [];
            $dayPlaceholders = [];
            $insertValues = [];
            
            foreach ($dayValues as $dayKey => $hours) {
                $dayColumns[] = "`{$dayKey}`";
                $dayPlaceholders[] = "?";
                $insertValues[] = $hours;
            }
            
            $sql = "INSERT INTO overtime_monthly_grid 
                    (site_id, employee_id, attendance_month, emp_id, designation, " . 
                    implode(', ', $dayColumns) . ", overtime_rate, earn_amount, created_at, updated_at) 
                    VALUES (?, ?, ?, ?, ?, " . implode(', ', $dayPlaceholders) . ", ?, ?, NOW(), NOW())";
            
            $insertValues = array_merge(
                [$siteId, $employeeId, $attendanceMonth, $employee['employee_code'], $designationName],
                $insertValues,
                [$overtimeRate, $earnAmount]
            );
            
            $insertStmt = $db->prepare($sql);
            $insertStmt->execute($insertValues);
            
            $action = 'created';
        }
        
        $_SESSION['success_message'] = "Overtime data {$action} successfully for {$employee['first_name']} {$employee['last_name']}!";
        header('Location: ' . $_SERVER['PHP_SELF'] . '?month=' . $selectedMonth . '&year=' . $selectedYear . '&saved=' . $employeeId);
        exit;
        
    } catch (Exception $e) {
        error_log("Overtime save error: " . $e->getMessage());
        $_SESSION['error_message'] = 'Error saving overtime data: ' . htmlspecialchars($e->getMessage());
        header('Location: ' . $_SERVER['PHP_SELF'] . '?month=' . $selectedMonth . '&year=' . $selectedYear);
        exit;
    }
}

// Get all active employees for the selected month/year
try {
    $whereConditions = ["e.site_id = ?"];
    $queryParams = [$siteId];
    
    // Status filter
    if ($statusFilter === 'active') {
        $whereConditions[] = "e.employment_status = 'active'";
    } elseif ($statusFilter === 'inactive') {
        $whereConditions[] = "e.employment_status = 'inactive'";
    }
    // If 'all', no status filter
    
    // Search filter
    if (!empty($search)) {
        $whereConditions[] = "(e.employee_code LIKE ? OR e.first_name LIKE ? OR e.last_name LIKE ? OR e.email LIKE ? OR CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) LIKE ?)";
        $searchParam = "%{$search}%";
        $queryParams = array_merge($queryParams, [$searchParam, $searchParam, $searchParam, $searchParam, $searchParam]);
    }
    
    $whereClause = implode(' AND ', $whereConditions);
    
    $sql = "SELECT 
                e.employee_id,
                e.employee_code,
                e.first_name,
                e.last_name,
                e.middle_name,
                e.designation_id,
                d.designation_name,
                e.employment_status
            FROM employees e
            LEFT JOIN designations d ON e.designation_id = d.designation_id
            WHERE {$whereClause}
            ORDER BY e.employee_code ASC";
    
    $stmt = $db->prepare($sql);
    $stmt->execute($queryParams);
    $employees = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get default overtime rate from overtime_default_rates table
    $defaultRate = 0;
    try {
        $stmt = $db->prepare("SELECT overtime_rate FROM overtime_default_rates WHERE site_id = ? AND is_active = 1");
        $stmt->execute([$siteId]);
        $defaultRateData = $stmt->fetch();
        if ($defaultRateData) {
            $defaultRate = (float)$defaultRateData['overtime_rate'];
        }
    } catch (Exception $e) {
        error_log("Error loading default rate: " . $e->getMessage());
    }
    
    // Get designation-based overtime rates
    $designationRates = [];
    try {
        $rateStmt = $db->prepare("
            SELECT designation_id, overtime_rate 
            FROM overtime_designation_rates 
            WHERE site_id = ? AND is_active = 1
        ");
        $rateStmt->execute([$siteId]);
        $rates = $rateStmt->fetchAll(PDO::FETCH_KEY_PAIR);
        $designationRates = $rates;
    } catch (Exception $e) {
        error_log("Error loading designation rates: " . $e->getMessage());
    }
    
    // Get overtime data for each employee
    foreach ($employees as &$emp) {
        $otStmt = $db->prepare("
            SELECT * FROM overtime_monthly_grid 
            WHERE employee_id = ? AND attendance_month = ?
    ");
        $otStmt->execute([$emp['employee_id'], $attendanceMonth]);
        $otData = $otStmt->fetch(PDO::FETCH_ASSOC);
        
        if ($otData) {
            // Get day values
            for ($day = 1; $day <= 31; $day++) {
                $dayKey = 'day_' . $day;
                $emp[$dayKey] = (float)($otData[$dayKey] ?? 0);
            }
            $emp['overtime_rate'] = (float)($otData['overtime_rate'] ?? 0);
            $emp['earn_amount'] = (float)($otData['earn_amount'] ?? 0);
        } else {
            // Default values
            for ($day = 1; $day <= 31; $day++) {
                $dayKey = 'day_' . $day;
                $emp[$dayKey] = 0;
            }
            // Auto-apply rate from designation if available
            $designationId = (int)($emp['designation_id'] ?? 0);
            if ($designationId > 0 && isset($designationRates[$designationId])) {
                $emp['overtime_rate'] = (float)$designationRates[$designationId];
            } else {
                $emp['overtime_rate'] = 0;
            }
            $emp['earn_amount'] = 0;
        }
        
        // If rate is 0, try to apply from designation, then default
        if ($emp['overtime_rate'] == 0) {
            $designationId = (int)($emp['designation_id'] ?? 0);
            if ($designationId > 0 && isset($designationRates[$designationId])) {
                // Apply designation-specific rate
                $emp['overtime_rate'] = (float)$designationRates[$designationId];
            } elseif ($defaultRate > 0) {
                // Apply default rate if no designation-specific rate
                $emp['overtime_rate'] = $defaultRate;
            }
        }
    }
    unset($emp);
    
} catch (Exception $e) {
    error_log("Error fetching overtime data: " . $e->getMessage());
    $employees = [];
    $_SESSION['error_message'] = 'Error loading overtime data: ' . $e->getMessage();
}

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

<style>
.overtime-container {
    padding: 20px;
    background: #f5f5f5;
}

.header-box {
    background: #1e3a5f;
    color: white;
    padding: 15px;
    border-radius: 5px;
    margin-bottom: 20px;
    overflow: hidden;
}

.header-box .row {
    display: flex;
    gap: 15px;
    align-items: center;
    flex-wrap: wrap;
    width: 100%;
}

.header-box .field {
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-box .field label {
    color: white;
    font-weight: 500;
    white-space: nowrap;
    margin: 0;
}

.header-box .field select,
.header-box .field input {
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 13px;
}

.table-container {
    background: white;
    border-radius: 5px;
    overflow-x: auto;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.table-container table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
    min-width: 2500px;
}

.table-container th {
    background: #1e3a5f;
    color: white;
    padding: 8px 4px;
    text-align: center;
    border: 1px solid #ddd;
    font-weight: 600;
    position: sticky;
    top: 0;
    z-index: 10;
}

.table-container th.day-header {
    background: #1e293b;
    color: white;
    min-width: 50px;
    width: 50px;
}

.table-container th.rate-header {
    background: #f59e0b;
    color: white;
    min-width: 100px;
}

.table-container th.earn-header {
    background: #10b981;
    color: white;
    min-width: 100px;
}

.table-container td {
    padding: 4px;
    border: 1px solid #ddd;
    text-align: center;
    vertical-align: middle;
}

.table-container td.name-cell {
    text-align: left;
    padding-left: 8px;
    font-weight: 500;
    background: #f9fafb;
    min-width: 150px;
}

.table-container td.emp-id-cell {
    background: #f9fafb;
    min-width: 100px;
    font-weight: 500;
}

.table-container td.designation-cell {
    background: #f9fafb;
    min-width: 120px;
}

.table-container select.day-select {
    width: 100%;
    padding: 4px;
    border: 1px solid #ccc;
    border-radius: 3px;
    font-size: 11px;
    text-align: center;
    background: white;
    cursor: pointer;
}

.table-container select.day-select:hover {
    background: #f0f9ff;
    border-color: #1e293b;
}

.table-container input.rate-input {
    width: 100%;
    padding: 4px;
    border: 1px solid #f59e0b;
    border-radius: 3px;
    font-size: 11px;
    text-align: center;
    background: #fef3c7;
    font-weight: 500;
}

.table-container input.rate-input:focus {
    outline: none;
    border-color: #d97706;
    background: #fde68a;
}

.table-container td.earn-amount {
    background: #d1fae5;
    font-weight: bold;
    color: #065f46;
    font-size: 13px;
}

.btn-save {
    background: #28a745;
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    font-weight: 500;
}

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

.btn-refresh {
    background: #007bff;
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 13px;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    white-space: nowrap;
}

.btn-refresh:hover {
    background: #0056b3;
}

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

.btn-save-all:hover {
    background: #218838;
}

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

.btn-export {
    background: #28a745;
    color: white;
    border: none;
    padding: 4px 8px;
    border-radius: 3px;
    cursor: pointer;
    font-size: 11px;
    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;
}

.btn-refresh .refresh-icon {
    display: inline-block;
    width: 14px;
    height: 14px;
    border: 2px solid white;
    border-top-color: transparent;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    flex-shrink: 0;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.info-box {
    background: #d1ecf1;
    border-left: 4px solid #17a2b8;
    padding: 10px;
    margin-bottom: 15px;
    border-radius: 4px;
    font-size: 12px;
}

.info-box strong {
    color: #0c5460;
}
</style>

<div class="overtime-container">
    <div class="header-box">
        <div class="row" style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
            <div class="field">
                <label style="font-size: 11px;">Month:</label>
                <select name="month" id="filter_month" class="form-control" onchange="applyFilter()" style="width: 100px; padding: 4px; border: 1px solid #ccc; border-radius: 4px; font-size: 11px;">
                    <option value="1" <?php echo $selectedMonth == 1 ? 'selected' : ''; ?>>January</option>
                    <option value="2" <?php echo $selectedMonth == 2 ? 'selected' : ''; ?>>February</option>
                    <option value="3" <?php echo $selectedMonth == 3 ? 'selected' : ''; ?>>March</option>
                    <option value="4" <?php echo $selectedMonth == 4 ? 'selected' : ''; ?>>April</option>
                    <option value="5" <?php echo $selectedMonth == 5 ? 'selected' : ''; ?>>May</option>
                    <option value="6" <?php echo $selectedMonth == 6 ? 'selected' : ''; ?>>June</option>
                    <option value="7" <?php echo $selectedMonth == 7 ? 'selected' : ''; ?>>July</option>
                    <option value="8" <?php echo $selectedMonth == 8 ? 'selected' : ''; ?>>August</option>
                    <option value="9" <?php echo $selectedMonth == 9 ? 'selected' : ''; ?>>September</option>
                    <option value="10" <?php echo $selectedMonth == 10 ? 'selected' : ''; ?>>October</option>
                    <option value="11" <?php echo $selectedMonth == 11 ? 'selected' : ''; ?>>November</option>
                    <option value="12" <?php echo $selectedMonth == 12 ? 'selected' : ''; ?>>December</option>
            </select>
            </div>
            <div class="field">
                <label style="font-size: 11px;">Year:</label>
                <input type="number" name="year" id="filter_year" class="form-control" 
                       value="<?php echo htmlspecialchars($selectedYear); ?>" 
                       min="2000" max="2100" 
                       placeholder="Year"
                       onchange="applyFilter()" 
                       onkeypress="if(event.key==='Enter') applyFilter()"
                       style="width: 70px; padding: 4px; border: 1px solid #ccc; border-radius: 4px; font-size: 11px;">
            </div>
            <div class="field">
                <label style="font-size: 11px;">Status:</label>
                <select name="status" id="filter_status" class="form-control" onchange="applyFilter()" style="width: 80px; padding: 4px; border: 1px solid #ccc; border-radius: 4px; font-size: 11px;">
                    <option value="all" <?php echo $statusFilter == 'all' ? 'selected' : ''; ?>>All</option>
                    <option value="active" <?php echo $statusFilter == 'active' ? 'selected' : ''; ?>>Active</option>
                    <option value="inactive" <?php echo $statusFilter == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
            </select>
            </div>
            <div class="field">
                <label style="font-size: 11px;">Search:</label>
                <input type="text" name="search" id="search_input" class="form-control" 
                       value="<?php echo htmlspecialchars($search); ?>" 
                       placeholder="Name/ID"
                       onkeypress="if(event.key==='Enter') applyFilter()"
                       style="width: 100px; padding: 4px; border: 1px solid #ccc; border-radius: 4px; font-size: 11px;">
            </div>
            <button type="button" class="btn-refresh" onclick="location.reload()" title="Refresh data" style="background: #007bff; color: white; border: none; padding: 4px 8px; border-radius: 4px; cursor: pointer; font-size: 11px; font-weight: 500; display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;">
                ↻ Refresh
            </button>
            <?php if (hasAdminAccess() || hasPermission('OVERTIME_RATES_MANAGE')): ?>
            <a href="<?php echo BASE_URL; ?>/modules/overtime/rates_designation.php" class="btn-settings" title="Manage Overtime Rates by Designation" style="background: #6c757d; color: white; border: none; padding: 4px 8px; border-radius: 4px; cursor: pointer; font-size: 11px; font-weight: 500; text-decoration: none; display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;">
                ⚙ Settings
            </a>
            <?php endif; ?>
            <button type="button" class="btn-save-all" onclick="saveAllOvertime()" title="Save all overtime data" style="background: #28a745; color: white; border: none; padding: 4px 8px; border-radius: 4px; cursor: pointer; font-size: 11px; font-weight: 500; display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;">
                💾 Save All
            </button>
            
            <!-- To Name Input Field -->
            <form method="POST" class="field" style="display: inline-flex; align-items: center; gap: 4px; background: rgba(255,255,255,0.1); padding: 3px 6px; border-radius: 3px;">
                <label style="font-size: 11px; color: #fff;">To:</label>
                <input type="text" name="to_name" value="<?php echo htmlspecialchars($currentToName); ?>" 
                       placeholder="Name" 
                       style="padding: 3px 6px; border: 1px solid #ccc; border-radius: 3px; font-size: 11px; width: 80px; background: white; color: #333;">
                <button type="submit" name="save_to_name" 
                        style="padding: 3px 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: 4px 8px; border-radius: 3px; cursor: pointer; font-size: 11px; 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>
        </div>
    </div>
    
    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success" style="background: #d4edda; color: #155724; padding: 15px; border-radius: 4px; margin-bottom: 20px; border-left: 4px solid #28a745;">
            <strong>✓ Success:</strong> <?php echo htmlspecialchars($_SESSION['success_message']); unset($_SESSION['success_message']); ?>
    </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger" style="background: #f8d7da; color: #721c24; padding: 15px; border-radius: 4px; margin-bottom: 20px; border-left: 4px solid #dc3545;">
            <strong>✗ Error:</strong> <?php echo htmlspecialchars($_SESSION['error_message']); unset($_SESSION['error_message']); ?>
        </div>
    <?php endif; ?>
    
    <div class="info-box">
        <strong>Site Name:</strong> <?php echo htmlspecialchars($siteName); ?> | 
        <strong>Month:</strong> <?php echo htmlspecialchars($monthName); ?> | 
        <strong>Total Employees:</strong> <?php echo count($employees); ?>
    </div>
    
    <div class="table-container" style="overflow-x: auto;">
        <table>
                <thead>
                    <tr>
                    <th rowspan="2" style="background: #f59e0b; min-width: 50px;">Sl. no</th>
                    <th rowspan="2" style="background: #f59e0b; min-width: 100px;">Emp ID</th>
                    <th rowspan="2" style="background: #f59e0b; min-width: 150px;">Name</th>
                    <th rowspan="2" style="background: #f59e0b; min-width: 120px;">Designation</th>
                    <?php for ($day = 1; $day <= 31; $day++): ?>
                        <th class="day-header"><?php echo $day; ?></th>
                    <?php endfor; ?>
                    <th class="rate-header">Overtime Rate</th>
                    <th class="earn-header">Earn Amount</th>
                    <th rowspan="2" style="background: #1e3a5f; min-width: 80px;">Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($employees)): ?>
                    <tr>
                        <td colspan="36" style="text-align: center; padding: 20px;">
                            No employees found. 
                            <a href="<?php echo BASE_URL; ?>/modules/employee/create.php">Add Employee</a>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($employees as $index => $emp): 
                        $fullName = trim(($emp['first_name'] ?? '') . ' ' . ($emp['middle_name'] ?? '') . ' ' . ($emp['last_name'] ?? ''));
                        $overtimeRate = (float)($emp['overtime_rate'] ?? 0);
                        $earnAmount = (float)($emp['earn_amount'] ?? 0);
                    ?>
                    <tr>
                        <td style="background: #fef3c7; font-weight: 500;"><?php echo $index + 1; ?></td>
                        <td class="emp-id-cell"><?php echo htmlspecialchars($emp['employee_code'] ?? ''); ?></td>
                        <td class="name-cell"><?php echo htmlspecialchars($fullName); ?></td>
                        <td class="designation-cell"><?php echo htmlspecialchars($emp['designation_name'] ?? 'N/A'); ?></td>
                        <?php for ($day = 1; $day <= 31; $day++): 
                            $dayKey = 'day_' . $day;
                            $hours = (float)($emp[$dayKey] ?? 0);
                            // Hide days beyond the month
                            $isVisible = $day <= $daysInMonth;
                        ?>
                            <td style="<?php echo !$isVisible ? 'background: #f3f4f6; opacity: 0.5;' : ''; ?>">
                                <?php if ($isVisible): ?>
                                    <select name="<?php echo $dayKey; ?>" 
                                            form="form_<?php echo $emp['employee_id']; ?>" 
                                            class="day-select"
                                            onchange="calculateEarnAmount(<?php echo $emp['employee_id']; ?>)">
                                        <?php for ($h = 0; $h <= 10; $h++): ?>
                                            <option value="<?php echo $h; ?>" <?php echo $hours == $h ? 'selected' : ''; ?>>
                                                <?php echo $h; ?>
                                            </option>
                                        <?php endfor; ?>
                                    </select>
                            <?php else: ?>
                                    <span style="color: #9ca3af;">-</span>
                            <?php endif; ?>
                            </td>
                        <?php endfor; ?>
                        <td>
                            <input type="number" 
                                   name="overtime_rate" 
                                   form="form_<?php echo $emp['employee_id']; ?>" 
                                   class="rate-input"
                                   value="<?php echo number_format($overtimeRate, 2, '.', ''); ?>"
                                   step="0.01"
                                   min="0"
                                   onchange="calculateEarnAmount(<?php echo $emp['employee_id']; ?>)"
                                   placeholder="0.00">
                        </td>
                        <td class="earn-amount" id="earn_<?php echo $emp['employee_id']; ?>">
                            <?php echo number_format($earnAmount, 2); ?>
                        </td>
                        <td>
                            <form id="form_<?php echo $emp['employee_id']; ?>" method="POST" style="display: inline;">
                                <input type="hidden" name="employee_id" value="<?php echo $emp['employee_id']; ?>">
                                <button type="submit" name="save_overtime" class="btn-save">Save</button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
    </div>
</div>

<script>
function applyFilter() {
    const month = document.getElementById('filter_month').value;
    const year = document.getElementById('filter_year').value.trim();
    const status = document.getElementById('filter_status').value;
    const search = document.getElementById('search_input').value.trim();
    
    // Validate year
    if (year && (isNaN(year) || year < 2000 || year > 2100)) {
        alert('Please enter a valid year between 2000 and 2100');
        document.getElementById('filter_year').focus();
        return;
    }
    
    // Build URL
    const url = new URL(window.location.href);
    url.searchParams.set('month', month);
    if (year) {
        url.searchParams.set('year', year);
    } else {
        url.searchParams.delete('year');
    }
    if (status && status !== 'all') {
        url.searchParams.set('status', status);
    } else {
        url.searchParams.delete('status');
    }
    if (search) {
        url.searchParams.set('search', search);
    } else {
        url.searchParams.delete('search');
    }
    
    window.location.href = url.toString();
}

function calculateEarnAmount(employeeId) {
    const formId = 'form_' + employeeId;
    const form = document.getElementById(formId);
    if (!form) return;
    
    // Get overtime rate - element has form attribute pointing to this form
    const rateInput = document.querySelector('input[name="overtime_rate"][form="' + formId + '"]');
    const rate = parseFloat(rateInput ? rateInput.value : 0) || 0;
    
    // Calculate total hours
    let totalHours = 0;
    for (let day = 1; day <= 31; day++) {
        const daySelect = document.querySelector('select[name="day_' + day + '"][form="' + formId + '"]');
        if (daySelect) {
            totalHours += parseFloat(daySelect.value) || 0;
        }
    }
    
    // Calculate earn amount
    const earnAmount = totalHours * rate;
    
    // Update display
    const earnCell = document.getElementById('earn_' + employeeId);
    if (earnCell) {
        earnCell.textContent = earnAmount.toFixed(2);
    }
}

// Auto-calculate on page load for all employees
document.addEventListener('DOMContentLoaded', function() {
    const forms = document.querySelectorAll('form[id^="form_"]');
    forms.forEach(form => {
        const employeeId = form.id.replace('form_', '');
        calculateEarnAmount(employeeId);
    });
});

// Save all overtime data
function saveAllOvertime() {
    const btn = document.querySelector('.btn-save-all');
    if (!btn) return;
    
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '💾 Saving...';
    
    // Collect all employee data
    const forms = document.querySelectorAll('form[id^="form_"]');
    const employeesData = [];
    
    forms.forEach(form => {
        const formId = form.id;
        const employeeId = parseInt(formId.replace('form_', ''), 10);
        if (isNaN(employeeId) || employeeId <= 0) return;
        
        // Get all day values - elements have form attribute pointing to this form
        const dayValues = {};
        for (let day = 1; day <= 31; day++) {
            // Find select by form attribute (elements are outside form but linked via form attribute)
            const daySelect = document.querySelector('select[name="day_' + day + '"][form="' + formId + '"]');
            if (daySelect) {
                dayValues['day_' + day] = parseFloat(daySelect.value) || 0;
            } else {
                dayValues['day_' + day] = 0;
            }
        }
        
        // Get overtime rate - also linked via form attribute
        const rateInput = document.querySelector('input[name="overtime_rate"][form="' + formId + '"]');
        const overtimeRate = parseFloat(rateInput ? rateInput.value : 0) || 0;
        
        // Calculate total hours
        let totalHours = 0;
        for (let day = 1; day <= 31; day++) {
            totalHours += dayValues['day_' + day] || 0;
        }
        
        // Calculate earn amount
        const earnAmount = totalHours * overtimeRate;
        
        employeesData.push({
            employee_id: employeeId,
            day_values: dayValues,
            overtime_rate: overtimeRate,
            earn_amount: earnAmount
        });
    });
    
    if (employeesData.length === 0) {
        alert('No data to save.');
        btn.disabled = false;
        btn.innerHTML = originalText;
        return;
    }
    
    console.log('Sending overtime data:', employeesData.length, 'employees');
    
    // Send to API
    fetch('<?php echo BASE_URL; ?>/api/save_overtime_bulk.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            month: <?php echo $selectedMonth; ?>,
            year: <?php echo $selectedYear; ?>,
            employees: employeesData
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Server error: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log('API Response:', data);
        if (data.success) {
            showSuccessMessage('✓ All overtime data saved successfully! (' + data.saved_count + ' employees)');
            // Reload page after 1 second
            setTimeout(() => {
                window.location.reload();
            }, 1000);
        } else {
            showErrorMessage('Error: ' + (data.message || 'Failed to save data'));
            btn.disabled = false;
            btn.innerHTML = originalText;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showErrorMessage('Error saving data: ' + error.message);
        btn.disabled = false;
        btn.innerHTML = originalText;
    });
}

function showSuccessMessage(message) {
    const msg = document.createElement('div');
    msg.style.cssText = 'position: fixed; top: 20px; right: 20px; background: #28a745; color: white; padding: 15px 20px; border-radius: 5px; z-index: 9999; box-shadow: 0 4px 6px rgba(0,0,0,0.1); font-weight: bold;';
    msg.innerHTML = message;
    document.body.appendChild(msg);
    
    setTimeout(function() {
        msg.style.transition = 'opacity 0.5s';
        msg.style.opacity = '0';
        setTimeout(function() {
            msg.remove();
        }, 500);
    }, 3000);
}

function showErrorMessage(message) {
    const msg = document.createElement('div');
    msg.style.cssText = 'position: fixed; top: 20px; right: 20px; background: #dc3545; color: white; padding: 15px 20px; border-radius: 5px; z-index: 9999; box-shadow: 0 4px 6px rgba(0,0,0,0.1); font-weight: bold;';
    msg.innerHTML = message;
    document.body.appendChild(msg);
    
    setTimeout(function() {
        msg.style.transition = 'opacity 0.5s';
        msg.style.opacity = '0';
        setTimeout(function() {
            msg.remove();
        }, 500);
    }, 3000);
}

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 month = document.getElementById('filter_month').value;
    const year = document.getElementById('filter_year').value.trim();
    const status = document.getElementById('filter_status').value;
    const search = document.getElementById('search_input').value.trim();
    
    // Build export URL with current filters
    let exportUrl = window.location.pathname + '?export=excel&month=' + month + '&year=' + year;
    if (status && status !== 'all') {
        exportUrl += '&status=' + status;
    }
    if (search) {
        exportUrl += '&search=' + encodeURIComponent(search);
    }
    
    // Trigger download
    window.location.href = exportUrl;
    
    // Reset button after a short delay
    setTimeout(function() {
        btn.disabled = false;
        btn.innerHTML = originalText;
    }, 2000);
}
</script>

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