<?php
/**
 * Enterprise HRM ERP System - Employee Master Sheet (Complete Excel Format)
 * All 18 columns matching Excel exactly with Import/Export functionality
 */

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

$pageTitle = 'Employee Master Sheet';
$currentModule = 'payroll';
$currentTab = 'employee_master';

$siteId = getCurrentSiteId();
$action = $_GET['action'] ?? 'list';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Fix table structure - ensure master_id has AUTO_INCREMENT
try {
    $db = getDB();
    
    // Create site_to_names table if not exists (for storing "To" names per site)
    $db->exec("
        CREATE TABLE IF NOT EXISTS `employee_master_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 table exists
    $tableExists = $db->query("SHOW TABLES LIKE 'employee_master_sheet'")->rowCount() > 0;
    
    if (!$tableExists) {
        // Create table with proper structure
        $db->exec("
            CREATE TABLE IF NOT EXISTS `employee_master_sheet` (
                `master_id` int(11) NOT NULL AUTO_INCREMENT,
                `site_id` int(11) NOT NULL,
                `employee_id` int(11) DEFAULT NULL,
                `sl_no` int(11) DEFAULT NULL,
                `emp_id` varchar(50) DEFAULT NULL,
                `employee_name` varchar(255) DEFAULT NULL,
                `category` varchar(100) DEFAULT NULL,
                `bank_ac_no` varchar(100) DEFAULT NULL,
                `bank_name` varchar(255) DEFAULT NULL,
                `department` varchar(255) DEFAULT NULL,
                `designation` varchar(255) DEFAULT NULL,
                `site` varchar(255) DEFAULT NULL,
                `contact_number` varchar(50) DEFAULT NULL,
                `fathers_name` varchar(255) DEFAULT NULL,
                `date_of_birth` date DEFAULT NULL,
                `date_of_joining` date DEFAULT NULL,
                `date_of_leaving` date DEFAULT NULL,
                `reason_for_leaving` text DEFAULT NULL,
                `pf_number` varchar(100) DEFAULT NULL,
                `uan_number` varchar(100) DEFAULT NULL,
                `insurance_number` varchar(100) DEFAULT NULL,
                `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
                `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (`master_id`),
                KEY `idx_site_id` (`site_id`),
                KEY `idx_emp_id` (`emp_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    } else {
        // Table exists, check if master_id has AUTO_INCREMENT
        $colCheck = $db->query("SHOW COLUMNS FROM employee_master_sheet LIKE 'master_id'");
        $colInfo = $colCheck->fetch(PDO::FETCH_ASSOC);
        
        if ($colInfo && strpos($colInfo['Extra'], 'auto_increment') === false) {
            // master_id exists but doesn't have AUTO_INCREMENT - fix it
            try {
                // First update any NULL or 0 master_id values
                $nullCount = $db->query("SELECT COUNT(*) FROM employee_master_sheet WHERE master_id IS NULL OR master_id = 0")->fetchColumn();
                
                if ($nullCount > 0) {
                    $maxId = (int)$db->query("SELECT COALESCE(MAX(master_id), 0) FROM employee_master_sheet WHERE master_id > 0")->fetchColumn();
                    
                    for ($i = 0; $i < $nullCount; $i++) {
                        $maxId++;
                        $db->exec("UPDATE employee_master_sheet SET master_id = {$maxId} WHERE (master_id IS NULL OR master_id = 0) LIMIT 1");
                    }
                }
                
                // Now add AUTO_INCREMENT
                $db->exec("ALTER TABLE employee_master_sheet MODIFY COLUMN `master_id` int(11) NOT NULL AUTO_INCREMENT");
                error_log("Fixed master_id AUTO_INCREMENT in employee_master_sheet table");
            } catch (Exception $e) {
                error_log("Error fixing master_id AUTO_INCREMENT: " . $e->getMessage());
            }
        }
    }
} catch (Exception $e) {
    error_log("Error checking/fixing employee_master_sheet table: " . $e->getMessage());
}

// Handle delete action
if ($action === 'delete' && $id > 0) {
    try {
        $db = getDB();
        
        // Verify record exists and belongs to current site
        $checkStmt = $db->prepare("SELECT master_id, employee_name FROM employee_master_sheet WHERE master_id = ? AND site_id = ?");
        $checkStmt->execute([$id, $siteId]);
        $record = $checkStmt->fetch();
        
        if (!$record) {
            $_SESSION['error_message'] = 'Record not found or you do not have permission to delete it.';
            header('Location: ?action=list');
            exit;
        }
        
        // Delete the record
        $deleteStmt = $db->prepare("DELETE FROM employee_master_sheet WHERE master_id = ? AND site_id = ?");
        $result = $deleteStmt->execute([$id, $siteId]);
        
        if ($result && $deleteStmt->rowCount() > 0) {
            $_SESSION['success_message'] = 'Employee Master record "' . htmlspecialchars($record['employee_name']) . '" deleted successfully.';
        } else {
            $_SESSION['error_message'] = 'Failed to delete record. Please try again.';
        }
        header('Location: ?action=list');
        exit;
        
    } catch (Exception $e) {
        error_log("Delete employee master sheet error: " . $e->getMessage());
        $_SESSION['error_message'] = 'Error deleting record: ' . $e->getMessage();
        header('Location: ?action=list');
        exit;
    }
}

// Handle delete all action
if ($action === 'delete_all') {
    try {
        $db = getDB();
        
        // Count records before delete
        $countStmt = $db->prepare("SELECT COUNT(*) FROM employee_master_sheet WHERE site_id = ?");
        $countStmt->execute([$siteId]);
        $totalRecords = $countStmt->fetchColumn();
        
        if ($totalRecords == 0) {
            $_SESSION['error_message'] = 'No records to delete.';
            header('Location: ?action=list');
            exit;
        }
        
        // Delete all records for this site
        $deleteStmt = $db->prepare("DELETE FROM employee_master_sheet WHERE site_id = ?");
        $result = $deleteStmt->execute([$siteId]);
        
        if ($result) {
            $deletedCount = $deleteStmt->rowCount();
            $_SESSION['success_message'] = "Successfully deleted {$deletedCount} employee master records.";
        } else {
            $_SESSION['error_message'] = 'Failed to delete records. Please try again.';
        }
        header('Location: ?action=list');
        exit;
        
    } catch (Exception $e) {
        error_log("Delete all employee master sheet error: " . $e->getMessage());
        $_SESSION['error_message'] = 'Error deleting records: ' . $e->getMessage();
        header('Location: ?action=list');
        exit;
    }
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $db = getDB();
        
        // Handle save "To" name
        if (isset($_POST['save_to_name'])) {
            $toName = trim($_POST['to_name'] ?? '');
            
            // Check if record exists for this site
            $checkStmt = $db->prepare("SELECT id FROM employee_master_to_names WHERE site_id = ?");
            $checkStmt->execute([$siteId]);
            $existing = $checkStmt->fetch();
            
            if ($existing) {
                // Update
                $updateStmt = $db->prepare("UPDATE employee_master_to_names SET to_name = ? WHERE site_id = ?");
                $updateStmt->execute([$toName, $siteId]);
            } else {
                // Insert
                $insertStmt = $db->prepare("INSERT INTO employee_master_to_names (site_id, to_name) VALUES (?, ?)");
                $insertStmt->execute([$siteId, $toName]);
            }
            
            $_SESSION['success_message'] = 'To Name saved successfully!';
            header('Location: ?action=list');
            exit;
        }
        
        if (isset($_POST['save'])) {
            $data = [
                'site_id' => $siteId,
                'employee_id' => !empty($_POST['employee_id']) ? (int)$_POST['employee_id'] : null,
                'sl_no' => !empty($_POST['sl_no']) ? (int)$_POST['sl_no'] : null,
                'emp_id' => $_POST['emp_id'] ?? '',
                'employee_name' => $_POST['employee_name'] ?? '',
                'category' => $_POST['category'] ?? '',
                'bank_ac_no' => $_POST['bank_ac_no'] ?? '',
                'bank_name' => $_POST['bank_name'] ?? '',
                'department' => $_POST['department'] ?? '',
                'designation' => $_POST['designation'] ?? '',
                'site' => $_POST['site'] ?? '',
                'contact_number' => $_POST['contact_number'] ?? '',
                'fathers_name' => $_POST['fathers_name'] ?? '',
                'date_of_birth' => !empty($_POST['date_of_birth']) ? $_POST['date_of_birth'] : null,
                'date_of_joining' => !empty($_POST['date_of_joining']) ? $_POST['date_of_joining'] : null,
                'date_of_leaving' => !empty($_POST['date_of_leaving']) ? $_POST['date_of_leaving'] : null,
                'reason_for_leaving' => $_POST['reason_for_leaving'] ?? '',
                'pf_number' => $_POST['pf_number'] ?? '',
                'uan_number' => $_POST['uan_number'] ?? '',
                'insurance_number' => $_POST['insurance_number'] ?? '',
            ];
            
            if ($id > 0) {
                // Update
                $stmt = $db->prepare("
                    UPDATE employee_master_sheet SET
                    employee_id = ?, sl_no = ?, emp_id = ?, employee_name = ?, category = ?,
                    bank_ac_no = ?, bank_name = ?, department = ?, designation = ?, site = ?,
                    contact_number = ?, fathers_name = ?, date_of_birth = ?, date_of_joining = ?,
                    date_of_leaving = ?, reason_for_leaving = ?, pf_number = ?, uan_number = ?,
                    insurance_number = ?
                    WHERE master_id = ? AND site_id = ?
                ");
                $stmt->execute([
                    $data['employee_id'], $data['sl_no'], $data['emp_id'], $data['employee_name'],
                    $data['category'], $data['bank_ac_no'], $data['bank_name'], $data['department'],
                    $data['designation'], $data['site'], $data['contact_number'], $data['fathers_name'],
                    $data['date_of_birth'], $data['date_of_joining'], $data['date_of_leaving'],
                    $data['reason_for_leaving'], $data['pf_number'], $data['uan_number'],
                    $data['insurance_number'], $id, $siteId
                ]);
                $_SESSION['success_message'] = 'Employee Master record updated successfully';
            } else {
                // Insert
                $stmt = $db->prepare("
                    INSERT INTO employee_master_sheet (
                        site_id, employee_id, sl_no, emp_id, employee_name, category,
                        bank_ac_no, bank_name, department, designation, site,
                        contact_number, fathers_name, date_of_birth, date_of_joining,
                        date_of_leaving, reason_for_leaving, pf_number, uan_number,
                        insurance_number
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $data['site_id'], $data['employee_id'], $data['sl_no'], $data['emp_id'],
                    $data['employee_name'], $data['category'], $data['bank_ac_no'], $data['bank_name'],
                    $data['department'], $data['designation'], $data['site'], $data['contact_number'],
                    $data['fathers_name'], $data['date_of_birth'], $data['date_of_joining'],
                    $data['date_of_leaving'], $data['reason_for_leaving'], $data['pf_number'],
                    $data['uan_number'], $data['insurance_number']
                ]);
                $_SESSION['success_message'] = 'Employee Master record created successfully';
            }
            
            header('Location: ?action=list');
            exit;
        }
        
        // Handle bulk import
        if (isset($_POST['import']) && isset($_FILES['import_file'])) {
            $file = $_FILES['import_file'];
            
            if ($file['error'] === UPLOAD_ERR_OK) {
                $csvFile = fopen($file['tmp_name'], 'r');
                
                // Skip header row
                fgetcsv($csvFile);
                
                $imported = 0;
                $errors = [];
                
                while (($row = fgetcsv($csvFile)) !== false) {
                    if (count($row) < 18) continue; // Skip incomplete rows
                    
                    try {
                        $stmt = $db->prepare("
                            INSERT INTO employee_master_sheet (
                                site_id, sl_no, emp_id, employee_name, category,
                                bank_ac_no, bank_name, department, designation, site,
                                contact_number, fathers_name, date_of_birth, date_of_joining,
                                date_of_leaving, reason_for_leaving, pf_number, uan_number,
                                insurance_number
                            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                            ON DUPLICATE KEY UPDATE
                                employee_name = VALUES(employee_name),
                                category = VALUES(category),
                                bank_ac_no = VALUES(bank_ac_no),
                                bank_name = VALUES(bank_name),
                                department = VALUES(department),
                                designation = VALUES(designation),
                                site = VALUES(site),
                                contact_number = VALUES(contact_number),
                                fathers_name = VALUES(fathers_name),
                                date_of_birth = VALUES(date_of_birth),
                                date_of_joining = VALUES(date_of_joining),
                                date_of_leaving = VALUES(date_of_leaving),
                                reason_for_leaving = VALUES(reason_for_leaving),
                                pf_number = VALUES(pf_number),
                                uan_number = VALUES(uan_number),
                                insurance_number = VALUES(insurance_number)
                        ");
                        
                        $dob = !empty($row[11]) ? date('Y-m-d', strtotime($row[11])) : null;
                        $doj = !empty($row[12]) ? date('Y-m-d', strtotime($row[12])) : null;
                        $dol = !empty($row[13]) ? date('Y-m-d', strtotime($row[13])) : null;
                        
                        $stmt->execute([
                            $siteId, $row[0], $row[1], $row[2], $row[3],
                            $row[4], $row[5], $row[6], $row[7], $row[8],
                            $row[9], $row[10], $dob, $doj, $dol,
                            $row[14], $row[15], $row[16], $row[17]
                        ]);
                        $imported++;
                    } catch (Exception $e) {
                        $errors[] = "Row " . ($imported + 1) . ": " . $e->getMessage();
                    }
                }
                
                fclose($csvFile);
                
                if ($imported > 0) {
                    $_SESSION['success_message'] = "Successfully imported $imported records";
                }
                if (!empty($errors)) {
                    $_SESSION['error_message'] = implode('<br>', array_slice($errors, 0, 5));
                }
            } else {
                $_SESSION['error_message'] = 'File upload error';
            }
            
            header('Location: ?action=list');
            exit;
        }
        
    } catch (Exception $e) {
        $_SESSION['error_message'] = 'Error: ' . $e->getMessage();
    }
}

// Handle export to Excel
if ($action === 'export') {
    try {
        $db = getDB();
        
        // Get "To" name for this site
        $toNameStmt = $db->prepare("SELECT to_name FROM employee_master_to_names WHERE site_id = ?");
        $toNameStmt->execute([$siteId]);
        $toNameRecord = $toNameStmt->fetch();
        $toName = $toNameRecord ? $toNameRecord['to_name'] : '';
        
        // Get site name
        $siteNameStmt = $db->prepare("SELECT site_name FROM sites WHERE site_id = ?");
        $siteNameStmt->execute([$siteId]);
        $siteNameRecord = $siteNameStmt->fetch();
        $siteName = $siteNameRecord ? $siteNameRecord['site_name'] : 'Site';
        
        $stmt = $db->prepare("
            SELECT sl_no, emp_id, employee_name, category, bank_ac_no, bank_name,
                   department, designation, site, contact_number, fathers_name,
                   DATE_FORMAT(date_of_birth, '%d/%m/%Y') as date_of_birth,
                   DATE_FORMAT(date_of_joining, '%d/%m/%Y') as date_of_joining,
                   DATE_FORMAT(date_of_leaving, '%d/%m/%Y') as date_of_leaving,
                   reason_for_leaving, pf_number, uan_number, insurance_number
            FROM employee_master_sheet
            WHERE site_id = ?
            ORDER BY sl_no ASC
        ");
        $stmt->execute([$siteId]);
        $records = $stmt->fetchAll();
        
        $exportFilename = 'Employee_Master_Sheet_' . $siteName . '_' . date('Y-m-d');
        
        // Define headers (used in both PhpSpreadsheet and fallback)
        $headers = [
            'SI No', 'Emp ID', 'Employee Name', 'Category', 'Bank A/c No', 'Bank Name',
            'Department', 'Designation', 'Site', 'Contact Number', "Father's Name",
            'Date of Birth', 'Date of Joining', 'Date of Leaving', 'Reason for Leaving',
            'P.F. No.', 'UAN No.', 'Insurance No.'
        ];
        
        // Check if PhpSpreadsheet is available
        $phpspreadsheet_available = class_exists('\PhpOffice\PhpSpreadsheet\Spreadsheet');
        
        if ($phpspreadsheet_available) {
            // Use PhpSpreadsheet for proper Excel format with colors
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            $sheet->setTitle('Employee Master Sheet');
            
            // Add "To" name row at top if exists
            $startRow = 1;
            if (!empty($toName)) {
                $sheet->setCellValue('A1', 'To:');
                $sheet->setCellValue('B1', $toName);
                $sheet->getStyle('A1')->getFont()->setBold(true);
                $sheet->getStyle('B1')->getFont()->setBold(true);
                $sheet->mergeCells('B1:E1');
                $startRow = 3; // Leave a blank row
            }
            
            // Style for header row (Green background, white text)
            $headerStyle = [
                'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 11],
                'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => '00FF00']],
                'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER],
                'borders' => ['allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]]
            ];
            
            // Write headers
            $col = 'A';
            foreach ($headers as $header) {
                $sheet->setCellValue($col . $startRow, $header);
                $sheet->getStyle($col . $startRow)->applyFromArray($headerStyle);
                $col++;
            }
            
            // Yellow highlight columns: Bank A/c No (E), Bank Name (F), Contact Number (J), Father's Name (K), Date of Birth (L), Date of Joining (M)
            $yellowColumns = ['E', 'F', 'J', 'K', 'L', 'M'];
            
            $row = $startRow + 1;
            foreach ($records as $record) {
                $col = 'A';
                
                // Write data
                $data = [
                    $record['sl_no'],
                    $record['emp_id'],
                    $record['employee_name'],
                    $record['category'],
                    $record['bank_ac_no'],
                    $record['bank_name'],
                    $record['department'],
                    $record['designation'],
                    $record['site'],
                    $record['contact_number'],
                    $record['fathers_name'],
                    $record['date_of_birth'],
                    $record['date_of_joining'],
                    $record['date_of_leaving'],
                    $record['reason_for_leaving'],
                    $record['pf_number'],
                    $record['uan_number'],
                    $record['insurance_number']
                ];
                
                foreach ($data as $value) {
                    $sheet->setCellValue($col . $row, $value);
                    
                    // Apply yellow background for specific columns
                    if (in_array($col, $yellowColumns)) {
                        $sheet->getStyle($col . $row)->applyFromArray([
                            'fill' => [
                                'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                                'startColor' => ['rgb' => 'FFFF00'] // Bright yellow
                            ],
                            'borders' => ['allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]]
                        ]);
                    } else {
                        // White background for other cells
                        $sheet->getStyle($col . $row)->applyFromArray([
                            'fill' => [
                                'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                                'startColor' => ['rgb' => 'FFFFFF']
                            ],
                            'borders' => ['allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]]
                        ]);
                    }
                    
                    $col++;
                }
                
                $row++;
            }
            
            // Auto-size columns
            foreach (range('A', 'R') as $columnID) {
                $sheet->getColumnDimension($columnID)->setAutoSize(true);
            }
            
            // Set headers and output
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment; filename="' . $exportFilename . '.xlsx"');
            header('Cache-Control: max-age=0');
            
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
            exit;
        } else {
            // Fallback to HTML/Excel format with colors
            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: #00FF00; color: white; font-weight: bold; padding: 8px; text-align: center; border: 1px solid #000; }
                td { padding: 5px; border: 1px solid #ccc; text-align: left; }
                .yellow-cell { background-color: #FFFF00 !important; }
                .white-cell { background-color: #FFFFFF !important; }
                .to-name { font-weight: bold; font-size: 12pt; padding: 10px; border: none; }
            </style></head><body>';
            
            // Add "To" name row at top if exists
            if (!empty($toName)) {
                echo '<table style="margin-bottom: 10px; border: none;">';
                echo '<tr><td class="to-name" style="border: none;"><strong>To:</strong> ' . htmlspecialchars($toName) . '</td></tr>';
                echo '</table>';
            }
            
            echo '<table>';
            
            // Headers
            echo '<tr>';
            foreach ($headers as $header) {
                echo '<th>' . htmlspecialchars($header) . '</th>';
            }
            echo '</tr>';
            
            // Data rows
            foreach ($records as $record) {
                echo '<tr>';
                $colIndex = 0;
                $data = [
                    $record['sl_no'],
                    $record['emp_id'],
                    $record['employee_name'],
                    $record['category'],
                    $record['bank_ac_no'],
                    $record['bank_name'],
                    $record['department'],
                    $record['designation'],
                    $record['site'],
                    $record['contact_number'],
                    $record['fathers_name'],
                    $record['date_of_birth'],
                    $record['date_of_joining'],
                    $record['date_of_leaving'],
                    $record['reason_for_leaving'],
                    $record['pf_number'],
                    $record['uan_number'],
                    $record['insurance_number']
                ];
                
                // Yellow columns: 4 (Bank A/c No), 5 (Bank Name), 9 (Contact Number), 10 (Father's Name), 11 (Date of Birth), 12 (Date of Joining)
                $yellowColIndices = [4, 5, 9, 10, 11, 12];
                
                foreach ($data as $value) {
                    $cellClass = in_array($colIndex, $yellowColIndices) ? 'yellow-cell' : 'white-cell';
                    echo '<td class="' . $cellClass . '">' . htmlspecialchars($value ?? '') . '</td>';
                    $colIndex++;
                }
                echo '</tr>';
            }
            
            echo '</table></body></html>';
            exit;
        }
        
    } catch (Exception $e) {
        die('Export error: ' . $e->getMessage());
    }
}

// Download sample file
if ($action === 'download_sample') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="employee_master_sample.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Header row
    fputcsv($output, [
        'Sl No', 'Emp ID', 'Employee Name', 'Category', 'Bank A/c No', 'Bank Name',
        'Department', 'Designation', 'Site', 'Contact Number', "Father's Name",
        'Date of Birth', 'Date of Joining', 'Date of Leaving', 'Reason for Leaving',
        'P.F. No.', 'UAN No.', 'Insurance No.'
    ]);
    
    // Sample data rows
    fputcsv($output, [
        '1', 'EMP001', 'Srikanta Mahakund', 'Highly Skilled', '123456789', 'HDFC Bank',
        'HR', 'Manager', 'Base Office', '9876543210', 'Father Name',
        '01/01/1990', '01/01/2020', '', '', 'PF123456', 'UAN123456', 'INS123'
    ]);
    fputcsv($output, [
        '2', 'EMP002', 'Susanta Das', 'Highly Skilled', '987654321', 'SBI',
        'Operation', 'Executive', 'Base Office', '9876543211', 'Father Name 2',
        '15/05/1992', '15/06/2021', '', '', 'PF234567', 'UAN234567', 'INS234'
    ]);
    
    fclose($output);
    exit;
}

try {
    $db = getDB();
    
    // Get all records
    $stmt = $db->prepare("
        SELECT ems.*
        FROM employee_master_sheet ems
        WHERE ems.site_id = ?
        ORDER BY ems.sl_no ASC, ems.master_id ASC
    ");
    $stmt->execute([$siteId]);
    $records = $stmt->fetchAll();
    
    // Get record for edit
    $record = null;
    if ($id > 0 && $action === 'edit') {
        $stmt = $db->prepare("SELECT * FROM employee_master_sheet WHERE master_id = ? AND site_id = ?");
        $stmt->execute([$id, $siteId]);
        $record = $stmt->fetch();
    }
    
    // Get categories for dropdown
    $stmt = $db->prepare("
        SELECT DISTINCT category FROM employee_master_sheet 
        WHERE site_id = ? AND category IS NOT NULL AND category != ''
        ORDER BY category
    ");
    $stmt->execute([$siteId]);
    $categories = $stmt->fetchAll(PDO::FETCH_COLUMN);
    if (empty($categories)) {
        $categories = ['Highly Skilled', 'Skilled', 'Semi-Skilled', 'Unskilled'];
    }
    
    // Get departments for dropdown
    $stmt = $db->prepare("SELECT department_name FROM departments WHERE site_id = ? AND department_status = 'active' ORDER BY department_name");
    $stmt->execute([$siteId]);
    $departments = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Get sites for dropdown
    $stmt = $db->prepare("SELECT site_name FROM sites WHERE site_status = 'active' ORDER BY site_name");
    $stmt->execute();
    $sites = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Get "To" name for current site
    $stmt = $db->prepare("SELECT to_name FROM employee_master_to_names WHERE site_id = ?");
    $stmt->execute([$siteId]);
    $toNameRecord = $stmt->fetch();
    $currentToName = $toNameRecord ? $toNameRecord['to_name'] : '';
    
} catch (Exception $e) {
    error_log("Employee Master Sheet error: " . $e->getMessage());
    $records = [];
    $record = null;
    $categories = [];
    $departments = [];
    $sites = [];
    $currentToName = '';
}

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

<style>
.excel-master-container {
    padding: 20px;
    background: #e7f3ff;
}

.action-toolbar {
    background: white;
    padding: 15px;
    border-radius: 5px;
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
}

.excel-table-wrapper {
    background: white;
    border-radius: 5px;
    padding: 20px;
    overflow-x: auto;
}

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

.excel-table thead {
    background: #00FF00;
}

.excel-table thead th {
    padding: 10px 8px;
    text-align: left;
    border: 1px solid #000;
    font-weight: bold;
    color: #000;
    white-space: nowrap;
}

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

.excel-table tbody tr:nth-child(even) {
    background: #f9f9f9;
}

.column-yellow {
    background: #FFFF00 !important;
}

.btn {
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    text-decoration: none;
    display: inline-block;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.btn-primary { 
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.btn-secondary { 
    background: #6c757d;
    color: white;
}

.btn-warning { 
    background: #ffc107;
    color: #000;
}

.btn-danger { 
    background: #dc3545;
    color: white;
}

.btn-success {
    background: #28a745;
    color: white;
}

.btn-sm {
    padding: 4px 8px;
    font-size: 10px;
}

.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0,0,0,0.5);
}

.modal-content {
    background-color: white;
    margin: 2% auto;
    padding: 0;
    border: none;
    width: 95%;
    max-width: 1000px;
    border-radius: 12px;
    max-height: 92vh;
    overflow: hidden;
    box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}

.modal-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 20px 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-header h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
}

.modal-body {
    padding: 30px;
    max-height: calc(92vh - 80px);
    overflow-y: auto;
}

.close {
    color: white;
    font-size: 28px;
    font-weight: 300;
    cursor: pointer;
    opacity: 0.8;
    transition: opacity 0.3s;
    background: none;
    border: none;
    line-height: 1;
}

.close:hover {
    opacity: 1;
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
}

.form-section {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    border-left: 4px solid #007bff;
}

.form-section h3 {
    margin: 0 0 15px 0;
    font-size: 14px;
    color: #007bff;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.form-group {
    margin-bottom: 18px;
}

.form-group.full-width {
    grid-column: 1 / -1;
}

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

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

.form-group input,
.form-group select,
.form-group textarea {
    width: 100%;
    padding: 10px 12px;
    border: 2px solid #e0e0e0;
    border-radius: 6px;
    font-size: 13px;
    transition: all 0.3s;
    background: white;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
    outline: none;
    border-color: #007bff;
    box-shadow: 0 0 0 3px rgba(0,123,255,0.1);
}

.form-group input[type="date"] {
    appearance: none;
    -webkit-appearance: none;
}

.form-group textarea {
    resize: vertical;
    min-height: 80px;
}

.form-actions {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
    padding-top: 20px;
    border-top: 2px solid #e0e0e0;
    margin-top: 20px;
}

.form-hint {
    display: block;
    font-size: 11px;
    color: #6c757d;
    margin-top: 5px;
}

.alert {
    padding: 12px;
    margin-bottom: 20px;
    border-radius: 5px;
}

.alert-success {
    background: #d4edda;
    border: 1px solid #c3e6cb;
    color: #155724;
}

.alert-danger {
    background: #f8d7da;
    border: 1px solid #f5c6cb;
    color: #721c24;
}

/* Live Search Styles */
.search-dropdown {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid #ddd;
    border-top: none;
    max-height: 300px;
    overflow-y: auto;
    z-index: 1000;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.search-dropdown.active {
    display: block;
}

.search-result-item {
    padding: 10px;
    cursor: pointer;
    border-bottom: 1px solid #f0f0f0;
    transition: background 0.2s;
}

.search-result-item:hover {
    background: #f8f9fa;
}

.search-result-item:last-child {
    border-bottom: none;
}

.search-result-name {
    font-weight: bold;
    color: #333;
    font-size: 13px;
}

.search-result-details {
    font-size: 11px;
    color: #666;
    margin-top: 3px;
}

.search-result-details span {
    margin-right: 10px;
}

.search-no-results {
    padding: 10px;
    text-align: center;
    color: #999;
    font-size: 12px;
}

.search-loading {
    padding: 10px;
    text-align: center;
    color: #666;
    font-size: 12px;
}
</style>

<div class="excel-master-container">
    <?php if (isset($_SESSION['success_message'])): ?>
    <div class="alert alert-success">
        <?php echo htmlspecialchars($_SESSION['success_message']); unset($_SESSION['success_message']); ?>
    </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error_message'])): ?>
    <div class="alert alert-danger">
        <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
    </div>
    <?php endif; ?>
    
    <div class="action-toolbar">
        <button onclick="openModal('employeeModal')" class="btn btn-primary">+ Add New</button>
        
        <!-- To Name Input Field -->
        <form method="POST" style="display: inline-flex; align-items: center; gap: 5px; margin-left: 10px; background: #f8f9fa; padding: 5px 10px; border-radius: 6px; border: 1px solid #dee2e6;">
            <label style="font-size: 12px; font-weight: 600; color: #495057; white-space: nowrap;">To:</label>
            <input type="text" name="to_name" value="<?php echo htmlspecialchars($currentToName); ?>" 
                   placeholder="Enter recipient name" 
                   style="padding: 6px 10px; border: 1px solid #ced4da; border-radius: 4px; font-size: 12px; width: 180px;">
            <button type="submit" name="save_to_name" class="btn btn-success" 
                    style="padding: 6px 10px; font-size: 11px; display: inline-flex; align-items: center; gap: 3px;" 
                    title="Save To Name">
                ✓
            </button>
        </form>
        
        <a href="?action=export" class="btn btn-secondary" style="background: #28a745; border-color: #28a745; color: white;">📊 Export to Excel</a>
        <button onclick="openModal('importModal')" class="btn btn-warning">📤 Bulk Import</button>
        <a href="?action=download_sample" class="btn btn-secondary">📄 Download Sample File</a>
        <button type="button" onclick="deleteAllRecords()" class="btn btn-danger" style="margin-left: 10px;">🗑️ Delete All</button>
        <span style="margin-left: auto; font-size: 12px; color: #666;">
            Total Records: <?php echo count($records); ?>
        </span>
    </div>
    
    <div class="excel-table-wrapper">
        <table class="excel-table">
            <thead>
                <tr>
                    <th>Sl No</th>
                    <th>Emp ID</th>
                    <th>Employee Name</th>
                    <th>Category</th>
                    <th>Bank A/c No</th>
                    <th>Bank Name</th>
                    <th>Department</th>
                    <th>Designation</th>
                    <th>Site</th>
                    <th>Contact Number</th>
                    <th>Father's Name</th>
                    <th>Date of Birth</th>
                    <th>Date of Joining</th>
                    <th>Date of Leaving</th>
                    <th>Reason for Leaving</th>
                    <th>P.F. No.</th>
                    <th>UAN No.</th>
                    <th>Insurance No.</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($records)): ?>
                <tr>
                    <td colspan="19" style="text-align: center; padding: 20px;">
                        No records found. Click "Add New" or "Bulk Import" to add records.
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($records as $rec): ?>
                <tr>
                    <td><?php echo htmlspecialchars($rec['sl_no'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($rec['emp_id'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($rec['employee_name'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($rec['category'] ?? ''); ?></td>
                    <td class="column-yellow"><?php echo htmlspecialchars($rec['bank_ac_no'] ?? ''); ?></td>
                    <td class="column-yellow"><?php echo htmlspecialchars($rec['bank_name'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($rec['department'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($rec['designation'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($rec['site'] ?? ''); ?></td>
                    <td class="column-yellow"><?php echo htmlspecialchars($rec['contact_number'] ?? ''); ?></td>
                    <td class="column-yellow"><?php echo htmlspecialchars($rec['fathers_name'] ?? ''); ?></td>
                    <td class="column-yellow"><?php echo $rec['date_of_birth'] ? date('d/m/Y', strtotime($rec['date_of_birth'])) : ''; ?></td>
                    <td class="column-yellow"><?php echo $rec['date_of_joining'] ? date('d/m/Y', strtotime($rec['date_of_joining'])) : ''; ?></td>
                    <td><?php echo $rec['date_of_leaving'] ? date('d/m/Y', strtotime($rec['date_of_leaving'])) : ''; ?></td>
                    <td><?php echo htmlspecialchars($rec['reason_for_leaving'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($rec['pf_number'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($rec['uan_number'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($rec['insurance_number'] ?? ''); ?></td>
                    <td>
                        <button type="button" onclick="deleteSingleRecord(<?php echo $rec['master_id']; ?>, '<?php echo htmlspecialchars(addslashes($rec['employee_name'] ?? 'this record')); ?>')" class="btn btn-danger btn-sm">Delete</button>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Add/Edit Modal -->
<div id="employeeModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2><?php echo $id > 0 ? 'Edit' : 'Add'; ?> Employee Master Record</h2>
            <button class="close" onclick="closeModal('employeeModal')">&times;</button>
        </div>
        <div class="modal-body">
            <form method="POST" action="">
                <input type="hidden" name="master_id" value="<?php echo $id; ?>">
                
                <!-- Basic Information -->
                <div class="form-section">
                    <h3>📋 Basic Information</h3>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Sl No<span class="required">*</span></label>
                            <input type="number" name="sl_no" value="<?php echo htmlspecialchars($record['sl_no'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label>Emp ID<span class="required">*</span></label>
                            <input type="text" name="emp_id" value="<?php echo htmlspecialchars($record['emp_id'] ?? ''); ?>" required placeholder="Enter employee ID">
                        </div>
                        
                        <div class="form-group full-width">
                            <label>Employee Name<span class="required">*</span></label>
                            <div style="position: relative;">
                                <input type="text" 
                                       name="employee_name" 
                                       id="employee_name_search" 
                                       value="<?php echo htmlspecialchars($record['employee_name'] ?? ''); ?>" 
                                       autocomplete="off"
                                       placeholder="Type to search employee..."
                                       required>
                                <div id="employee_search_results" class="search-dropdown"></div>
                            </div>
                            <small class="form-hint">💡 Type at least 2 characters to search existing employees</small>
                        </div>
                        
                        <div class="form-group">
                            <label>Category</label>
                            <select name="category" style="appearance: auto;">
                                <option value="">-- Select Category --</option>
                                <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo htmlspecialchars($cat); ?>" <?php echo ($record['category'] ?? '') == $cat ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cat); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>Father's Name</label>
                            <input type="text" name="fathers_name" value="<?php echo htmlspecialchars($record['fathers_name'] ?? ''); ?>" placeholder="Enter father's name">
                        </div>
                    </div>
                </div>
                
                <!-- Work Information -->
                <div class="form-section">
                    <h3>💼 Work Information</h3>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Department</label>
                            <select name="department" style="appearance: auto;">
                                <option value="">-- Select Department --</option>
                                <?php foreach ($departments as $dept): ?>
                                <option value="<?php echo htmlspecialchars($dept); ?>" <?php echo ($record['department'] ?? '') == $dept ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($dept); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>Designation</label>
                            <input type="text" name="designation" value="<?php echo htmlspecialchars($record['designation'] ?? ''); ?>" placeholder="Enter designation">
                        </div>
                        
                        <div class="form-group">
                            <label>Site</label>
                            <select name="site" style="appearance: auto;">
                                <option value="">-- Select Site --</option>
                                <?php foreach ($sites as $site): ?>
                                <option value="<?php echo htmlspecialchars($site); ?>" <?php echo ($record['site'] ?? '') == $site ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($site); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>Contact Number</label>
                            <input type="tel" name="contact_number" value="<?php echo htmlspecialchars($record['contact_number'] ?? ''); ?>" placeholder="Enter contact number">
                        </div>
                    </div>
                </div>
                
                <!-- Bank Details -->
                <div class="form-section">
                    <h3>🏦 Bank Details</h3>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Bank Name</label>
                            <input type="text" name="bank_name" value="<?php echo htmlspecialchars($record['bank_name'] ?? ''); ?>" placeholder="Enter bank name">
                        </div>
                        
                        <div class="form-group">
                            <label>Bank A/c No</label>
                            <input type="text" name="bank_ac_no" value="<?php echo htmlspecialchars($record['bank_ac_no'] ?? ''); ?>" placeholder="Enter account number">
                        </div>
                    </div>
                </div>
                
                <!-- Dates -->
                <div class="form-section">
                    <h3>📅 Important Dates</h3>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Date of Birth</label>
                            <input type="date" name="date_of_birth" value="<?php echo $record['date_of_birth'] ?? ''; ?>">
                        </div>
                        
                        <div class="form-group">
                            <label>Date of Joining</label>
                            <input type="date" name="date_of_joining" value="<?php echo $record['date_of_joining'] ?? ''; ?>">
                        </div>
                        
                        <div class="form-group">
                            <label>Date of Leaving</label>
                            <input type="date" name="date_of_leaving" value="<?php echo $record['date_of_leaving'] ?? ''; ?>">
                        </div>
                        
                        <div class="form-group full-width">
                            <label>Reason for Leaving</label>
                            <textarea name="reason_for_leaving" rows="2" placeholder="Enter reason if employee has left"><?php echo htmlspecialchars($record['reason_for_leaving'] ?? ''); ?></textarea>
                        </div>
                    </div>
                </div>
                
                <!-- Statutory Details -->
                <div class="form-section">
                    <h3>📝 Statutory Details</h3>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>P.F. No.</label>
                            <input type="text" name="pf_number" value="<?php echo htmlspecialchars($record['pf_number'] ?? ''); ?>" placeholder="Provident Fund Number">
                        </div>
                        
                        <div class="form-group">
                            <label>UAN No.</label>
                            <input type="text" name="uan_number" value="<?php echo htmlspecialchars($record['uan_number'] ?? ''); ?>" placeholder="Universal Account Number">
                        </div>
                        
                        <div class="form-group">
                            <label>Insurance No.</label>
                            <input type="text" name="insurance_number" value="<?php echo htmlspecialchars($record['insurance_number'] ?? ''); ?>" placeholder="Insurance Number">
                        </div>
                    </div>
                </div>
                
                <div class="form-actions">
                    <button type="button" onclick="closeModal('employeeModal')" class="btn btn-secondary">✕ Cancel</button>
                    <button type="submit" name="save" class="btn btn-primary">✓ Save Employee</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Import Modal -->
<div id="importModal" class="modal">
    <div class="modal-content" style="max-width: 650px;">
        <div class="modal-header">
            <h2>📤 Bulk Import Employee Master Sheet</h2>
            <button class="close" onclick="closeModal('importModal')">&times;</button>
        </div>
        <div class="modal-body">
            <form method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Select CSV File<span class="required">*</span></label>
                    <input type="file" name="import_file" accept=".csv" required style="padding: 12px;">
                    <small class="form-hint">📄 File must be in CSV format with 18 columns</small>
                </div>
                
                <div style="background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%); padding: 20px; border-radius: 8px; border-left: 4px solid #667eea; margin: 20px 0;">
                    <h4 style="margin: 0 0 15px 0; color: #667eea; font-size: 14px;">📋 Import Instructions</h4>
                    <ul style="margin: 0; padding-left: 20px; font-size: 12px; line-height: 1.8;">
                        <li>Download the sample file first to see the correct format</li>
                        <li>All 18 columns must be present in the exact order</li>
                        <li>Dates should be in DD/MM/YYYY format</li>
                        <li>First row should be the header row (will be skipped)</li>
                        <li>Existing records with same Emp ID will be updated</li>
                    </ul>
                </div>
                
                <div class="form-actions">
                    <a href="?action=download_sample" class="btn btn-warning">📄 Download Sample</a>
                    <button type="button" onclick="closeModal('importModal')" class="btn btn-secondary">✕ Cancel</button>
                    <button type="submit" name="import" class="btn btn-primary">✓ Import Data</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function openModal(modalId) {
    document.getElementById(modalId).style.display = 'block';
}

function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

function editRecord(id) {
    window.location.href = '?action=edit&id=' + id;
}

// Delete single record
function deleteSingleRecord(recordId, recordName) {
    if (!recordId || recordId <= 0) {
        alert('Invalid record ID. Cannot delete.');
        return false;
    }
    
    if (confirm('Are you sure you want to delete "' + recordName + '"?\n\nThis action cannot be undone.')) {
        window.location.href = '?action=delete&id=' + recordId;
    }
    return false;
}

// Delete all records
function deleteAllRecords() {
    var totalRecords = <?php echo count($records); ?>;
    
    if (totalRecords === 0) {
        alert('No records to delete.');
        return false;
    }
    
    var confirmMsg = 'WARNING: You are about to delete ALL ' + totalRecords + ' employee master records!\n\n';
    confirmMsg += 'This action CANNOT be undone.\n\n';
    confirmMsg += 'Are you absolutely sure you want to proceed?';
    
    if (confirm(confirmMsg)) {
        // Double confirmation for safety
        if (confirm('FINAL CONFIRMATION: Delete all ' + totalRecords + ' records?')) {
            window.location.href = '?action=delete_all';
        }
    }
    return false;
}

<?php if ($action === 'edit' && $id > 0): ?>
document.addEventListener('DOMContentLoaded', function() {
    openModal('employeeModal');
});
<?php endif; ?>

window.onclick = function(event) {
    var modals = document.getElementsByClassName('modal');
    for (var i = 0; i < modals.length; i++) {
        if (event.target == modals[i]) {
            closeModal(modals[i].id);
        }
    }
}

// Employee Live Search
let searchTimeout = null;
const employeeSearchInput = document.getElementById('employee_name_search');
const searchResultsDiv = document.getElementById('employee_search_results');

if (employeeSearchInput) {
    employeeSearchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        
        const query = this.value.trim();
        
        if (query.length < 2) {
            searchResultsDiv.classList.remove('active');
            return;
        }
        
        // Show loading
        searchResultsDiv.innerHTML = '<div class="search-loading">Searching...</div>';
        searchResultsDiv.classList.add('active');
        
        searchTimeout = setTimeout(function() {
            searchEmployees(query);
        }, 300); // Wait 300ms after user stops typing
    });
    
    // Close dropdown when clicking outside
    document.addEventListener('click', function(e) {
        if (!employeeSearchInput.contains(e.target) && !searchResultsDiv.contains(e.target)) {
            searchResultsDiv.classList.remove('active');
        }
    });
}

function searchEmployees(query) {
    fetch('<?php echo BASE_URL; ?>/modules/employee/search_employee_ajax.php?q=' + encodeURIComponent(query))
        .then(response => response.json())
        .then(data => {
            if (data.success && data.employees.length > 0) {
                let html = '';
                data.employees.forEach(function(emp) {
                    html += '<div class="search-result-item" onclick="selectEmployee(' + 
                            emp.employee_id + ', \'' + 
                            escapeHtml(emp.employee_name) + '\', \'' + 
                            escapeHtml(emp.emp_id || '') + '\', \'' + 
                            escapeHtml(emp.department || '') + '\', \'' + 
                            escapeHtml(emp.designation || '') + '\', \'' + 
                            escapeHtml(emp.contact_number || '') + '\')">';
                    html += '<div class="search-result-name">' + escapeHtml(emp.employee_name) + '</div>';
                    html += '<div class="search-result-details">';
                    if (emp.emp_id) html += '<span>ID: ' + escapeHtml(emp.emp_id) + '</span>';
                    if (emp.department) html += '<span>Dept: ' + escapeHtml(emp.department) + '</span>';
                    if (emp.designation) html += '<span>Desig: ' + escapeHtml(emp.designation) + '</span>';
                    html += '</div>';
                    html += '</div>';
                });
                searchResultsDiv.innerHTML = html;
            } else {
                searchResultsDiv.innerHTML = '<div class="search-no-results">No employees found</div>';
            }
            searchResultsDiv.classList.add('active');
        })
        .catch(error => {
            console.error('Search error:', error);
            searchResultsDiv.innerHTML = '<div class="search-no-results">Search error. Please try again.</div>';
        });
}

function selectEmployee(employeeId, name, empId, department, designation, contactNumber) {
    // Fill the form fields
    document.getElementById('employee_name_search').value = name;
    
    if (empId && document.querySelector('input[name="emp_id"]')) {
        document.querySelector('input[name="emp_id"]').value = empId;
    }
    
    if (department && document.querySelector('input[name="department"]')) {
        document.querySelector('input[name="department"]').value = department;
    }
    
    if (designation && document.querySelector('input[name="designation"]')) {
        document.querySelector('input[name="designation"]').value = designation;
    }
    
    if (contactNumber && document.querySelector('input[name="contact_number"]')) {
        document.querySelector('input[name="contact_number"]').value = contactNumber;
    }
    
    if (document.querySelector('input[name="employee_id"]')) {
        document.querySelector('input[name="employee_id"]').value = employeeId;
    }
    
    // Close dropdown
    searchResultsDiv.classList.remove('active');
}

function escapeHtml(text) {
    if (!text) return '';
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
</script>

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

