<?php
/**
 * Enterprise HRM ERP System - Resigned & Abscondee Entry
 * Month and Year wise data submission
 */

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

$pageTitle = 'Resigned & Abscondee Entry';
$currentModule = 'exit';

$siteId = getCurrentSiteId();
$selectedMonth = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$selectedYear = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');

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

$errors = [];
$success = false;

$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 `resigned_abscondee_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 resigned_abscondee_to_names WHERE site_id = ?");
        $checkStmt->execute([$siteId]);
        $existing = $checkStmt->fetch();
        
        if ($existing) {
            $updateStmt = $db->prepare("UPDATE resigned_abscondee_to_names SET to_name = ? WHERE site_id = ?");
            $updateStmt->execute([$toName, $siteId]);
        } else {
            $insertStmt = $db->prepare("INSERT INTO resigned_abscondee_to_names (site_id, to_name) VALUES (?, ?)");
            $insertStmt->execute([$siteId, $toName]);
        }
        
        $_SESSION['success'] = 'To Name saved successfully!';
        header('Location: ' . $_SERVER['PHP_SELF'] . '?month=' . $selectedMonth . '&year=' . $selectedYear . '&to_saved=1');
        exit;
    } catch (Exception $e) {
        error_log("Error saving resigned_abscondee To Name: " . $e->getMessage());
        $errors[] = '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 `resigned_abscondee_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 resigned_abscondee_to_names WHERE site_id = ?");
    $toNameStmt->execute([$siteId]);
    $toNameRecord = $toNameStmt->fetch();
    $currentToName = $toNameRecord ? $toNameRecord['to_name'] : '';
} catch (Exception $e) {
    error_log("Error fetching resigned_abscondee 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 resigned_abscondee_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
    $monthYear = date('M-Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear));
    $exportFilename = 'Resigned_Abscondee_' . str_replace('-', '_', $monthYear) . '_' . date('Ymd_His');
    
    // Get data for export
    $exportStmt = $db->prepare("
        SELECT * FROM resigned_abscondee 
        WHERE site_id = ? AND month = ?
        ORDER BY sl_no ASC, exit_id ASC
    ");
    $exportStmt->execute([$siteId, $monthYear]);
    $exportEntries = $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 { background-color: #d1fae5 !important; font-weight: bold; }
        .month-info { background-color: #fef3c7 !important; font-weight: bold; }
        .sl-cell { text-align: center; font-weight: bold; }
        .resigned { background-color: #fef3c7 !important; }
        .abscondee { background-color: #fee2e2 !important; }
    </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 and month info
    echo '<table style="margin-bottom: 10px; border: none;">';
    echo '<tr>';
    echo '<td class="site-info" style="border: none;">Site Name: ' . htmlspecialchars($exportSiteName) . '</td>';
    echo '<td class="month-info" style="border: none; margin-left: 20px;">Month: ' . htmlspecialchars($monthYear) . '</td>';
    echo '</tr>';
    echo '</table>';
    
    echo '<table>';
    
    // Header Row
    echo '<tr>';
    echo '<th>Sl No</th>';
    echo '<th>Emp ID</th>';
    echo '<th>Name</th>';
    echo '<th>Designation</th>';
    echo '<th>Category</th>';
    echo '<th>Resigned/Abscondee</th>';
    echo '<th>Site Name</th>';
    echo '<th>Location</th>';
    echo '<th>Last Date of Working</th>';
    echo '<th>Resignation Submitted</th>';
    echo '<th>Notice Period Served</th>';
    echo '<th>Remarks</th>';
    echo '</tr>';
    
    // Data rows
    if (!empty($exportEntries)) {
        foreach ($exportEntries as $entry) {
            $rowClass = ($entry['resigned_abscondee'] ?? 'Resigned') === 'Abscondee' ? 'abscondee' : 'resigned';
            
            echo '<tr>';
            echo '<td class="sl-cell">' . htmlspecialchars($entry['sl_no'] ?? '') . '</td>';
            echo '<td>' . htmlspecialchars($entry['emp_id'] ?? '') . '</td>';
            echo '<td>' . htmlspecialchars($entry['name'] ?? '') . '</td>';
            echo '<td>' . htmlspecialchars($entry['designation'] ?? '') . '</td>';
            echo '<td>' . htmlspecialchars($entry['category'] ?? '') . '</td>';
            echo '<td class="' . $rowClass . '">' . htmlspecialchars($entry['resigned_abscondee'] ?? 'Resigned') . '</td>';
            echo '<td>' . htmlspecialchars($entry['site_name'] ?? '') . '</td>';
            echo '<td>' . htmlspecialchars($entry['location'] ?? '') . '</td>';
            echo '<td>' . ($entry['last_date_of_working'] ? date('d-m-Y', strtotime($entry['last_date_of_working'])) : '') . '</td>';
            echo '<td>' . ($entry['resignation_submitted'] ? date('d-m-Y', strtotime($entry['resignation_submitted'])) : '') . '</td>';
            echo '<td>' . htmlspecialchars($entry['notice_period_served'] ?? '') . '</td>';
            echo '<td>' . htmlspecialchars($entry['remark'] ?? '') . '</td>';
            echo '</tr>';
        }
    } else {
        echo '<tr><td colspan="12" style="text-align: center;">No data found for this month.</td></tr>';
    }
    
    // Summary row
    $resignedCount = 0;
    $abscondeeCount = 0;
    foreach ($exportEntries as $entry) {
        if (($entry['resigned_abscondee'] ?? 'Resigned') === 'Resigned') {
            $resignedCount++;
        } else {
            $abscondeeCount++;
        }
    }
    
    echo '<tr style="font-weight: bold; background-color: #e5e7eb;">';
    echo '<td colspan="5" style="text-align: right;">Total:</td>';
    echo '<td>Resigned: ' . $resignedCount . ', Abscondee: ' . $abscondeeCount . '</td>';
    echo '<td colspan="6"></td>';
    echo '</tr>';
    
    echo '</table></body></html>';
    exit;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_data'])) {
    try {
        $db->beginTransaction();
        
        $monthYear = date('M-Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear));
        
        // Delete existing records for this month/year
        $stmt = $db->prepare("DELETE FROM resigned_abscondee WHERE site_id = ? AND month = ?");
        $stmt->execute([$siteId, $monthYear]);
        
        // Insert new records
        if (isset($_POST['entries']) && is_array($_POST['entries'])) {
            $slNo = 1;
            foreach ($_POST['entries'] as $row) {
                // Skip completely empty rows
                if (empty($row['emp_id']) && empty($row['name'])) continue;
                
                $empId = sanitize($row['emp_id'] ?? '');
                $name = sanitize($row['name'] ?? '');
                $designation = sanitize($row['designation'] ?? '');
                $category = sanitize($row['category'] ?? '');
                $resignedAbscondee = sanitize($row['resigned_abscondee'] ?? 'Resigned');
                $siteName = sanitize($row['site_name'] ?? '');
                $location = sanitize($row['location'] ?? '');
                $lastDateOfWorking = $row['last_date_of_working'] ?? null;
                $resignationSubmitted = $row['resignation_submitted'] ?? null;
                $noticePeriodServed = sanitize($row['notice_period_served'] ?? '');
                $remark = sanitize($row['remark'] ?? '');
                
                // Try to find employee_id from emp_id or name
                $employeeId = null;
                if (!empty($empId)) {
                    $stmt = $db->prepare("SELECT employee_id FROM employees WHERE employee_code = ? AND site_id = ? LIMIT 1");
                    $stmt->execute([$empId, $siteId]);
                    $emp = $stmt->fetch();
                    if ($emp) {
                        $employeeId = $emp['employee_id'];
                    }
                }
                
                // If employee_id not found by code, try by name
                if (!$employeeId && !empty($name)) {
                    $nameParts = explode(' ', trim($name));
                    if (count($nameParts) >= 2) {
                        $stmt = $db->prepare("SELECT employee_id FROM employees WHERE first_name LIKE ? AND last_name LIKE ? AND site_id = ? LIMIT 1");
                        $stmt->execute([$nameParts[0] . '%', '%' . $nameParts[count($nameParts)-1], $siteId]);
                        $emp = $stmt->fetch();
                        if ($emp) {
                            $employeeId = $emp['employee_id'];
                        }
                    }
                }
                
                // Insert record
                $stmt = $db->prepare("
                    INSERT INTO resigned_abscondee (
                        site_id, employee_id, sl_no, emp_id, name, designation, category,
                        resigned_abscondee, site_name, location, last_date_of_working,
                        resignation_submitted, notice_period_served, remark, month
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $siteId,
                    $employeeId,
                    $slNo,
                    $empId,
                    $name,
                    $designation,
                    $category,
                    $resignedAbscondee,
                    $siteName,
                    $location,
                    $lastDateOfWorking ?: null,
                    $resignationSubmitted ?: null,
                    $noticePeriodServed,
                    $remark,
                    $monthYear
                ]);
                
                $slNo++;
            }
        }
        
        $db->commit();
        $success = true;
        $_SESSION['success'] = 'Resigned & Abscondee data saved successfully.';
        header('Location: ' . $_SERVER['PHP_SELF'] . '?month=' . $selectedMonth . '&year=' . $selectedYear);
        exit;
        
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        $errors[] = $e->getMessage();
        error_log("Resigned & Abscondee save error: " . $e->getMessage());
    }
}

// Load existing data
$entries = [];
try {
    $monthYear = date('M-Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear));
    
    $stmt = $db->prepare("
        SELECT * FROM resigned_abscondee 
        WHERE site_id = ? AND month = ?
        ORDER BY sl_no ASC, exit_id ASC
    ");
    $stmt->execute([$siteId, $monthYear]);
    $entries = $stmt->fetchAll();
    
    // If no entries, create 1 default empty row
    if (empty($entries)) {
        $entries[] = [
            'exit_id' => null,
            'sl_no' => 1,
            'emp_id' => '',
            'name' => '',
            'designation' => '',
            'category' => '',
            'resigned_abscondee' => 'Resigned',
            'site_name' => '',
            'location' => '',
            'last_date_of_working' => '',
            'resignation_submitted' => '',
            'notice_period_served' => '',
            'remark' => ''
        ];
    }
    
    // Get site name
    $stmt = $db->prepare("SELECT site_name FROM sites WHERE site_id = ?");
    $stmt->execute([$siteId]);
    $site = $stmt->fetch();
    $defaultSiteName = $site['site_name'] ?? '';
    
    // Get categories for dropdown
    $categories = ['Unskilled', 'Semi-Skilled', 'Skilled', 'Highly Skilled'];
    
    // Get designations for autocomplete
    $stmt = $db->prepare("SELECT DISTINCT designation_name FROM designations WHERE site_id = ? AND designation_status = 'active' ORDER BY designation_name");
    $stmt->execute([$siteId]);
    $designations = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Get locations for autocomplete
    $stmt = $db->prepare("SELECT DISTINCT location FROM resigned_abscondee WHERE site_id = ? AND location IS NOT NULL AND location != '' ORDER BY location");
    $stmt->execute([$siteId]);
    $locations = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
} catch (Exception $e) {
    error_log("Error loading data: " . $e->getMessage());
    $entries = [];
    $defaultSiteName = '';
    $categories = ['Unskilled', 'Semi-Skilled', 'Skilled', 'Highly Skilled'];
    $designations = [];
    $locations = [];
}

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

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

.filter-section {
    background: white;
    padding: 15px;
    margin-bottom: 20px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    gap: 20px;
    flex-wrap: wrap;
}

.filter-section label {
    font-weight: bold;
    margin-right: 5px;
}

.filter-section select,
.filter-section input {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.excel-table-container {
    background: white;
    padding: 20px;
    border-radius: 8px;
    overflow-x: auto;
    width: 100%;
}

.excel-table {
    width: 100%;
    min-width: 1600px;
    border-collapse: collapse;
    font-size: 13px;
}

.excel-table th {
    background: #1e40af;
    color: white;
    padding: 10px 8px;
    text-align: center;
    font-weight: bold;
    border: 1px solid #1e3a8a;
    white-space: nowrap;
}

.excel-table td {
    padding: 8px;
    border: 1px solid #d1d5db;
    background: white;
}

.excel-table input[type="text"],
.excel-table input[type="date"],
.excel-table select,
.excel-table textarea {
    width: 100%;
    border: none;
    padding: 5px;
    font-size: 13px;
    background: transparent;
}

.excel-table input[type="text"]:focus,
.excel-table input[type="date"]:focus,
.excel-table select:focus,
.excel-table textarea:focus {
    outline: 2px solid #3b82f6;
    background: #eff6ff;
}

.excel-table .col-sl-no {
    width: 60px;
    text-align: center;
}

.excel-table .col-emp-id {
    width: 130px;
}

.excel-table .col-name {
    width: 200px;
}

.excel-table .col-designation {
    width: 160px;
}

.excel-table .col-category {
    width: 150px;
}

.excel-table .col-resigned {
    width: 160px;
}

.excel-table .col-site {
    width: 150px;
}

.excel-table .col-location {
    width: 150px;
}

.excel-table .col-date {
    width: 150px;
}

.excel-table .col-notice {
    width: 150px;
}

.excel-table .col-remarks {
    width: 250px;
}

.header-row {
    background: #f0f9ff;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    gap: 20px;
}

.header-row .site-name {
    background: #d1fae5;
    padding: 8px 15px;
    border-radius: 4px;
    font-weight: bold;
}

.header-row .month-year {
    background: #fef3c7;
    padding: 8px 15px;
    border-radius: 4px;
    font-weight: bold;
}

.btn-save {
    background: #10b981;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-weight: bold;
    margin-top: 20px;
}

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

.btn-view-report {
    background: #3b82f6;
    color: white;
    padding: 8px 15px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
}

.btn-view-report:hover {
    background: #1e293b;
}

.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;
}
</style>

<div class="resigned-abscondee-container">
    <div class="card">
        <div class="card-header">
            <h2 class="card-title">Resigned & Abscondee Entry</h2>
            <a href="<?php echo BASE_URL; ?>/modules/exit/resigned_abscondee_report.php" class="btn-view-report">View Report</a>
        </div>
        
        <?php if (!empty($errors)): ?>
        <div class="alert alert-error" style="margin: 20px;">
            <ul style="margin: 0; padding-left: 20px;">
                <?php foreach ($errors as $error): ?>
                <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>
        
        <div class="filter-section">
            <div>
                <label>Month:</label>
                <select id="filter_month" onchange="filterData()">
                    <?php for ($m = 1; $m <= 12; $m++): ?>
                    <option value="<?php echo $m; ?>" <?php echo $m == $selectedMonth ? 'selected' : ''; ?>>
                        <?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>
                    </option>
                    <?php endfor; ?>
                </select>
            </div>
            
            <div>
                <label>Year:</label>
                <input type="number" id="filter_year" value="<?php echo $selectedYear; ?>" 
                       min="2020" max="2100" onchange="filterData()" style="width: 100px;">
            </div>
            
            <!-- To Name Input Field -->
            <form method="POST" style="display: inline-flex; align-items: center; gap: 4px; background: #1e3a5f; padding: 4px 8px; border-radius: 4px; margin-left: 10px;">
                <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>
        </div>
        
        <form method="POST" id="dataForm">
            <input type="hidden" name="save_data" value="1">
            
            <div class="header-row">
                <div class="site-name">Site Name: <?php echo htmlspecialchars($defaultSiteName); ?></div>
                <div class="month-year"><?php echo date('M-Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?></div>
            </div>
            
            <div class="excel-table-container">
                <table class="excel-table">
                    <thead>
                        <tr>
                            <th class="col-sl-no">Sl No</th>
                            <th class="col-emp-id">Emp Id</th>
                            <th class="col-name">Name</th>
                            <th class="col-designation">Designation</th>
                            <th class="col-category">Category</th>
                            <th class="col-resigned">Resigned/ Abscondee</th>
                            <th class="col-site">Site Name</th>
                            <th class="col-location">Location</th>
                            <th class="col-date">Last Date of Working</th>
                            <th class="col-date">Resignation Submitted</th>
                            <th class="col-notice">Notice Period served</th>
                            <th class="col-remarks">Remarks</th>
                            <th class="col-actions" style="width: 80px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="dataTableBody">
                        <?php foreach ($entries as $index => $entry): ?>
                        <tr>
                            <td class="col-sl-no">
                                <input type="hidden" name="entries[<?php echo $index; ?>][sl_no]" value="<?php echo $entry['sl_no']; ?>">
                                <?php echo $entry['sl_no']; ?>
                            </td>
                            <td class="col-emp-id">
                                <input type="text" name="entries[<?php echo $index; ?>][emp_id]" 
                                       value="<?php echo htmlspecialchars($entry['emp_id']); ?>"
                                       placeholder="Emp ID" class="emp-id-input"
                                       data-index="<?php echo $index; ?>">
                            </td>
                            <td class="col-name">
                                <input type="text" name="entries[<?php echo $index; ?>][name]" 
                                       value="<?php echo htmlspecialchars($entry['name']); ?>"
                                       placeholder="Name" class="name-input"
                                       data-index="<?php echo $index; ?>">
                            </td>
                            <td class="col-designation">
                                <input type="text" name="entries[<?php echo $index; ?>][designation]" 
                                       value="<?php echo htmlspecialchars($entry['designation']); ?>"
                                       placeholder="Designation" list="designation-list-<?php echo $index; ?>">
                                <datalist id="designation-list-<?php echo $index; ?>">
                                    <?php foreach ($designations as $des): ?>
                                    <option value="<?php echo htmlspecialchars($des); ?>">
                                    <?php endforeach; ?>
                                </datalist>
                            </td>
                            <td class="col-category">
                                <select name="entries[<?php echo $index; ?>][category]">
                                    <option value="">Select</option>
                                    <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo htmlspecialchars($cat); ?>" 
                                            <?php echo ($entry['category'] ?? '') === $cat ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($cat); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                            <td class="col-resigned">
                                <select name="entries[<?php echo $index; ?>][resigned_abscondee]">
                                    <option value="Resigned" <?php echo ($entry['resigned_abscondee'] ?? 'Resigned') === 'Resigned' ? 'selected' : ''; ?>>Resigned</option>
                                    <option value="Abscondee" <?php echo ($entry['resigned_abscondee'] ?? '') === 'Abscondee' ? 'selected' : ''; ?>>Abscondee</option>
                                </select>
                            </td>
                            <td class="col-site">
                                <input type="text" name="entries[<?php echo $index; ?>][site_name]" 
                                       value="<?php echo htmlspecialchars($entry['site_name'] ?: $defaultSiteName); ?>"
                                       placeholder="Site Name">
                            </td>
                            <td class="col-location">
                                <input type="text" name="entries[<?php echo $index; ?>][location]" 
                                       value="<?php echo htmlspecialchars($entry['location']); ?>"
                                       placeholder="Location" list="location-list-<?php echo $index; ?>">
                                <datalist id="location-list-<?php echo $index; ?>">
                                    <?php foreach ($locations as $loc): ?>
                                    <option value="<?php echo htmlspecialchars($loc); ?>">
                                    <?php endforeach; ?>
                                </datalist>
                            </td>
                            <td class="col-date">
                                <input type="date" name="entries[<?php echo $index; ?>][last_date_of_working]" 
                                       value="<?php echo htmlspecialchars($entry['last_date_of_working']); ?>">
                            </td>
                            <td class="col-date">
                                <input type="date" name="entries[<?php echo $index; ?>][resignation_submitted]" 
                                       value="<?php echo htmlspecialchars($entry['resignation_submitted']); ?>">
                            </td>
                            <td class="col-notice">
                                <input type="text" name="entries[<?php echo $index; ?>][notice_period_served]" 
                                       value="<?php echo htmlspecialchars($entry['notice_period_served']); ?>"
                                       placeholder="e.g., Yes/No">
                            </td>
                            <td class="col-remarks">
                                <textarea name="entries[<?php echo $index; ?>][remark]" rows="2" 
                                          placeholder="Remarks"><?php echo htmlspecialchars($entry['remark']); ?></textarea>
                            </td>
                            <td class="col-actions" style="text-align: center;">
                                <button type="button" onclick="deleteRow(this)" 
                                        style="background: #ef4444; color: white; padding: 5px 10px; border: none; border-radius: 4px; cursor: pointer; font-size: 12px;"
                                        title="Delete Row">🗑️ Delete</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <div style="text-align: right; margin-top: 20px;">
                <button type="button" onclick="addRow()" style="background: #6b7280; color: white; padding: 8px 15px; border: none; border-radius: 4px; cursor: pointer; margin-right: 10px;">Add Row</button>
                <button type="submit" class="btn-save">Save Data</button>
            </div>
        </form>
    </div>
</div>

<script>
let rowIndex = <?php echo count($entries); ?>;
const designations = <?php echo json_encode($designations); ?>;
const categories = <?php echo json_encode($categories); ?>;
const locations = <?php echo json_encode($locations); ?>;
const defaultSiteName = <?php echo json_encode($defaultSiteName); ?>;

function filterData() {
    const month = document.getElementById('filter_month').value;
    const year = document.getElementById('filter_year').value;
    window.location.href = '<?php echo $_SERVER['PHP_SELF']; ?>?month=' + month + '&year=' + year;
}

function deleteRow(button) {
    const rows = document.querySelectorAll('#dataTableBody tr');
    // Prevent deleting if only one row remains
    if (rows.length <= 1) {
        alert('At least one row must remain. You cannot delete the last row.');
        return;
    }
    
    if (confirm('Are you sure you want to delete this row?')) {
        const row = button.closest('tr');
        row.remove();
        // Renumber rows
        const remainingRows = document.querySelectorAll('#dataTableBody tr');
        remainingRows.forEach((r, index) => {
            const slNoCell = r.querySelector('.col-sl-no');
            if (slNoCell) {
                // Update hidden input
                const hiddenInput = slNoCell.querySelector('input[type="hidden"]');
                if (hiddenInput) {
                    hiddenInput.value = index + 1;
                    // Get old index from name
                    const nameMatch = hiddenInput.name.match(/entries\[(\d+)\]/);
                    if (nameMatch) {
                        const oldIndex = nameMatch[1];
                        // Update all inputs in this row
                        r.querySelectorAll('input, select, textarea').forEach(input => {
                            if (input.name && input.name.includes(`entries[${oldIndex}]`)) {
                                input.name = input.name.replace(/entries\[\d+\]/, `entries[${index}]`);
                            }
                        });
                    }
                }
                // Update displayed number - find text node after hidden input
                const textNodes = Array.from(slNoCell.childNodes);
                let foundTextNode = false;
                for (let i = 0; i < textNodes.length; i++) {
                    if (textNodes[i].nodeType === 3 && textNodes[i].textContent.trim()) {
                        textNodes[i].textContent = index + 1;
                        foundTextNode = true;
                        break;
                    }
                }
                if (!foundTextNode) {
                    // Create text node if not found
                    const textNode = document.createTextNode(index + 1);
                    slNoCell.appendChild(textNode);
                }
            }
        });
    }
}

function addRow() {
    const tbody = document.getElementById('dataTableBody');
    const newRow = document.createElement('tr');
    
    // Build designation options
    let designationOptions = '';
    designations.forEach(des => {
        designationOptions += '<option value="' + des.replace(/"/g, '&quot;') + '">';
    });
    
    // Build category options
    let categoryOptions = '<option value="">Select</option>';
    categories.forEach(cat => {
        categoryOptions += '<option value="' + cat.replace(/"/g, '&quot;') + '">' + cat + '</option>';
    });
    
    // Build location options
    let locationOptions = '';
    locations.forEach(loc => {
        locationOptions += '<option value="' + loc.replace(/"/g, '&quot;') + '">';
    });
    
    newRow.innerHTML = `
        <td class="col-sl-no">
            <input type="hidden" name="entries[${rowIndex}][sl_no]" value="${rowIndex + 1}">
            ${rowIndex + 1}
        </td>
        <td class="col-emp-id">
            <input type="text" name="entries[${rowIndex}][emp_id]" placeholder="Emp ID" class="emp-id-input" data-index="${rowIndex}">
        </td>
        <td class="col-name">
            <input type="text" name="entries[${rowIndex}][name]" placeholder="Name" class="name-input" data-index="${rowIndex}">
        </td>
        <td class="col-designation">
            <input type="text" name="entries[${rowIndex}][designation]" placeholder="Designation" list="designation-list-${rowIndex}">
            <datalist id="designation-list-${rowIndex}">
                ${designationOptions}
            </datalist>
        </td>
        <td class="col-category">
            <select name="entries[${rowIndex}][category]">
                ${categoryOptions}
            </select>
        </td>
        <td class="col-resigned">
            <select name="entries[${rowIndex}][resigned_abscondee]">
                <option value="Resigned">Resigned</option>
                <option value="Abscondee">Abscondee</option>
            </select>
        </td>
        <td class="col-site">
            <input type="text" name="entries[${rowIndex}][site_name]" value="${defaultSiteName.replace(/"/g, '&quot;')}" placeholder="Site Name">
        </td>
        <td class="col-location">
            <input type="text" name="entries[${rowIndex}][location]" placeholder="Location" list="location-list-${rowIndex}">
            <datalist id="location-list-${rowIndex}">
                ${locationOptions}
            </datalist>
        </td>
        <td class="col-date">
            <input type="date" name="entries[${rowIndex}][last_date_of_working]">
        </td>
        <td class="col-date">
            <input type="date" name="entries[${rowIndex}][resignation_submitted]">
        </td>
        <td class="col-notice">
            <input type="text" name="entries[${rowIndex}][notice_period_served]" placeholder="e.g., Yes/No">
        </td>
        <td class="col-remarks">
            <textarea name="entries[${rowIndex}][remark]" rows="2" placeholder="Remarks"></textarea>
        </td>
        <td class="col-actions" style="text-align: center;">
            <button type="button" onclick="deleteRow(this)" 
                    style="background: #ef4444; color: white; padding: 5px 10px; border: none; border-radius: 4px; cursor: pointer; font-size: 12px;"
                    title="Delete Row">🗑️ Delete</button>
        </td>
    `;
    tbody.appendChild(newRow);
    
    // Re-attach event listeners for the new row
    const newEmpIdInput = newRow.querySelector('.emp-id-input');
    const newNameInput = newRow.querySelector('.name-input');
    
    if (newEmpIdInput) {
        newEmpIdInput.addEventListener('blur', function() {
            const empId = this.value.trim();
            if (empId) {
                fetchEmployeeDetails(empId, null, this.dataset.index);
            }
        });
    }
    
    if (newNameInput) {
        newNameInput.addEventListener('blur', function() {
            const name = this.value.trim();
            if (name) {
                fetchEmployeeDetails(null, name, this.dataset.index);
            }
        });
    }
    
    rowIndex++;
}

// Auto-fill employee details when emp_id or name is entered
document.addEventListener('DOMContentLoaded', function() {
    const empIdInputs = document.querySelectorAll('.emp-id-input');
    const nameInputs = document.querySelectorAll('.name-input');
    
    // Handle emp_id search
    empIdInputs.forEach(input => {
        input.addEventListener('blur', function() {
            const empId = this.value.trim();
            if (empId) {
                fetchEmployeeDetails(empId, null, this.dataset.index);
            }
        });
    });
    
    // Handle name search
    nameInputs.forEach(input => {
        input.addEventListener('blur', function() {
            const name = this.value.trim();
            if (name) {
                fetchEmployeeDetails(null, name, this.dataset.index);
            }
        });
    });
});

function fetchEmployeeDetails(empId, name, index) {
    if (!empId && !name) return;
    
    fetch('<?php echo BASE_URL; ?>/api/search_employees.php?q=' + encodeURIComponent(empId || name))
        .then(response => response.json())
        .then(data => {
            if (data.success && data.employees && data.employees.length > 0) {
                const emp = data.employees[0];
                const row = document.querySelector(`input[name="entries[${index}][emp_id]"]`).closest('tr');
                
                // Auto-fill fields
                if (!row.querySelector(`input[name="entries[${index}][emp_id]"]`).value) {
                    row.querySelector(`input[name="entries[${index}][emp_id]"]`).value = emp.employee_code || '';
                }
                if (!row.querySelector(`input[name="entries[${index}][name]"]`).value) {
                    row.querySelector(`input[name="entries[${index}][name]"]`).value = emp.full_name || '';
                }
                if (!row.querySelector(`input[name="entries[${index}][designation]"]`).value && emp.designation_name) {
                    row.querySelector(`input[name="entries[${index}][designation]"]`).value = emp.designation_name;
                }
            }
        })
        .catch(error => {
            console.error('Error fetching employee details:', error);
        });
}

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;
    
    // Build export URL with current filters
    let exportUrl = window.location.pathname + '?export=excel&month=' + month + '&year=' + year;
    
    // 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'; ?>

