<?php
/**
 * Enterprise HRM ERP System - Create Employee Master Change
 */

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

// Check permissions - allow HR Admin and Super Admin
if (!isHRAdmin() && !isSuperAdmin()) {
    redirect(BASE_URL . '/dashboard.php', 'Access denied. Only HR Admin and Super Admin can access this page.', 'error');
}

$pageTitle = 'Add Employee Master Change';
$currentModule = 'payroll';
$currentTab = 'employee_master_change';

$siteId = getCurrentSiteId();
if (!$siteId) {
    redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Site not found. Please select/assign a site and try again.', 'error');
}

$errors = [];
$formData = [];

// Get dropdown data
try {
    $db = getDB();
    
    // Check if table exists, if not create it
    $tableExists = $db->query("SHOW TABLES LIKE 'employee_master_change'")->rowCount() > 0;
    if (!$tableExists) {
        $db->exec("
            CREATE TABLE IF NOT EXISTS `employee_master_change` (
                `change_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,
                `name` varchar(255) DEFAULT NULL,
                `designation` varchar(255) DEFAULT NULL,
                `site_name` varchar(255) DEFAULT NULL,
                `category` varchar(100) DEFAULT NULL,
                `change_month` int(11) DEFAULT NULL,
                `change_year` int(11) DEFAULT NULL,
                `present_address` text,
                `permanent_address` text,
                `pay_mode` enum('Bank','Hold') DEFAULT 'Bank',
                `bank_name` varchar(255) DEFAULT NULL,
                `bank_account_number` varchar(100) DEFAULT NULL,
                `bank_ref_number` varchar(100) DEFAULT NULL,
                `bank_ifsc_code` varchar(50) DEFAULT NULL,
                `esic_number` varchar(50) DEFAULT NULL,
                `pf_number` varchar(50) DEFAULT NULL,
                `remarks` text,
                `created_by` int(11) DEFAULT NULL,
                `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
                `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (`change_id`),
                KEY `fk_emc_site` (`site_id`),
                KEY `fk_emc_emp` (`employee_id`),
                KEY `fk_emc_created_by` (`created_by`),
                KEY `idx_emp_id` (`emp_id`),
                KEY `idx_name` (`name`),
                CONSTRAINT `fk_emc_site` FOREIGN KEY (`site_id`) REFERENCES `sites` (`site_id`) ON DELETE RESTRICT,
                CONSTRAINT `fk_emc_emp` FOREIGN KEY (`employee_id`) REFERENCES `employees` (`employee_id`) ON DELETE SET NULL,
                CONSTRAINT `fk_emc_created_by` FOREIGN KEY (`created_by`) REFERENCES `users` (`user_id`) ON DELETE SET NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    } else {
        // Table exists - check if change_id has AUTO_INCREMENT
        $colCheck = $db->query("SHOW COLUMNS FROM employee_master_change LIKE 'change_id'");
        $colInfo = $colCheck->fetch(PDO::FETCH_ASSOC);
        
        if ($colInfo && strpos(strtolower($colInfo['Extra']), 'auto_increment') === false) {
            // change_id exists but doesn't have AUTO_INCREMENT - fix it
            try {
                // First update any NULL or 0 change_id values
                $nullCount = (int)$db->query("SELECT COUNT(*) FROM employee_master_change WHERE change_id IS NULL OR change_id = 0")->fetchColumn();
                
                if ($nullCount > 0) {
                    $maxId = (int)$db->query("SELECT COALESCE(MAX(change_id), 0) FROM employee_master_change WHERE change_id > 0")->fetchColumn();
                    
                    for ($i = 0; $i < $nullCount; $i++) {
                        $maxId++;
                        $db->exec("UPDATE employee_master_change SET change_id = {$maxId} WHERE (change_id IS NULL OR change_id = 0) LIMIT 1");
                    }
                }
                
                // Now add AUTO_INCREMENT
                $db->exec("ALTER TABLE employee_master_change MODIFY COLUMN `change_id` int(11) NOT NULL AUTO_INCREMENT");
                error_log("Fixed change_id AUTO_INCREMENT in employee_master_change table");
            } catch (Exception $e) {
                error_log("Error fixing change_id AUTO_INCREMENT: " . $e->getMessage());
            }
        }
        
        // Table exists, check and add missing columns
        $stmt = $db->query("SHOW COLUMNS FROM employee_master_change");
        $existingColumns = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $existingColumns[] = $row['Field'];
        }
        
        // Define all required columns
        $requiredColumns = [
            'sl_no' => "ALTER TABLE employee_master_change ADD COLUMN `sl_no` int(11) DEFAULT NULL",
            'emp_id' => "ALTER TABLE employee_master_change ADD COLUMN `emp_id` varchar(50) DEFAULT NULL",
            'name' => "ALTER TABLE employee_master_change ADD COLUMN `name` varchar(255) DEFAULT NULL",
            'designation' => "ALTER TABLE employee_master_change ADD COLUMN `designation` varchar(255) DEFAULT NULL",
            'site_name' => "ALTER TABLE employee_master_change ADD COLUMN `site_name` varchar(255) DEFAULT NULL",
            'category' => "ALTER TABLE employee_master_change ADD COLUMN `category` varchar(100) DEFAULT NULL",
            'change_month' => "ALTER TABLE employee_master_change ADD COLUMN `change_month` int(11) DEFAULT NULL",
            'change_year' => "ALTER TABLE employee_master_change ADD COLUMN `change_year` int(11) DEFAULT NULL",
            'present_address' => "ALTER TABLE employee_master_change ADD COLUMN `present_address` text",
            'permanent_address' => "ALTER TABLE employee_master_change ADD COLUMN `permanent_address` text",
            'pay_mode' => "ALTER TABLE employee_master_change ADD COLUMN `pay_mode` enum('Bank','Hold') DEFAULT 'Bank'",
            'bank_name' => "ALTER TABLE employee_master_change ADD COLUMN `bank_name` varchar(255) DEFAULT NULL",
            'bank_account_number' => "ALTER TABLE employee_master_change ADD COLUMN `bank_account_number` varchar(100) DEFAULT NULL",
            'bank_ref_number' => "ALTER TABLE employee_master_change ADD COLUMN `bank_ref_number` varchar(100) DEFAULT NULL",
            'bank_ifsc_code' => "ALTER TABLE employee_master_change ADD COLUMN `bank_ifsc_code` varchar(50) DEFAULT NULL",
            'esic_number' => "ALTER TABLE employee_master_change ADD COLUMN `esic_number` varchar(50) DEFAULT NULL",
            'pf_number' => "ALTER TABLE employee_master_change ADD COLUMN `pf_number` varchar(50) DEFAULT NULL",
            'remarks' => "ALTER TABLE employee_master_change ADD COLUMN `remarks` text",
        ];
        
        // Add missing columns
        foreach ($requiredColumns as $column => $alterSql) {
            if (!in_array($column, $existingColumns)) {
                try {
                    $db->exec($alterSql);
                    error_log("Added missing column: {$column} to employee_master_change table");
                } catch (Exception $e) {
                    error_log("Error adding column {$column}: " . $e->getMessage());
                }
            }
        }
    }
    
    // Get next SL No
    $stmt = $db->prepare("SELECT MAX(sl_no) FROM employee_master_change WHERE site_id = ?");
    $stmt->execute([$siteId]);
    $maxSlNo = $stmt->fetchColumn();
    $nextSlNo = ($maxSlNo ? (int)$maxSlNo : 0) + 1;
    
    // Get site name
    $stmt = $db->prepare("SELECT site_name FROM sites WHERE site_id = ?");
    $stmt->execute([$siteId]);
    $siteName = $stmt->fetchColumn();
    
    // Get employees for dropdown
    $accessibleSiteIds = getAccessibleSiteIds();
    if (!empty($accessibleSiteIds)) {
        $placeholders = implode(',', array_fill(0, count($accessibleSiteIds), '?'));
        $stmt = $db->prepare("
            SELECT employee_id, employee_code, first_name, middle_name, last_name, designation_id
            FROM employees 
            WHERE site_id IN ($placeholders) AND employment_status = 'active'
            ORDER BY employee_code
        ");
        $stmt->execute($accessibleSiteIds);
        $employees = $stmt->fetchAll();
    } else {
        $employees = [];
    }
    
    // Get designations
    $stmt = $db->prepare("SELECT designation_id, designation_name FROM designations WHERE site_id = ? AND designation_status = 'active' ORDER BY designation_name");
    $stmt->execute([$siteId]);
    $designations = $stmt->fetchAll();
    
    // Get categories
    $stmt = $db->prepare("SELECT DISTINCT category FROM employee_master_change WHERE category IS NOT NULL AND category != '' ORDER BY category");
    $stmt->execute();
    $categories = $stmt->fetchAll(PDO::FETCH_COLUMN);
    if (empty($categories)) {
        $categories = ['Highly Skilled', 'Skilled', 'Semi-Skilled', 'Unskilled', 'FTC', 'Contract'];
    }
    
} catch (Exception $e) {
    error_log("Error loading data: " . $e->getMessage());
    $nextSlNo = 1;
    $siteName = '';
    $employees = [];
    $designations = [];
    $categories = [];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'sl_no' => isset($_POST['sl_no']) ? (int)$_POST['sl_no'] : $nextSlNo,
        'employee_id' => isset($_POST['employee_id']) ? (int)$_POST['employee_id'] : null,
        'emp_id' => sanitize($_POST['emp_id'] ?? ''),
        'name' => sanitize($_POST['name'] ?? ''),
        'designation' => sanitize($_POST['designation'] ?? ''),
        'site_name' => sanitize($_POST['site_name'] ?? $siteName),
        'category' => sanitize($_POST['category'] ?? ''),
        'change_month' => isset($_POST['change_month']) ? (int)$_POST['change_month'] : null,
        'change_year' => isset($_POST['change_year']) ? (int)$_POST['change_year'] : null,
        'present_address' => sanitize($_POST['present_address'] ?? ''),
        'permanent_address' => sanitize($_POST['permanent_address'] ?? ''),
        'pay_mode' => sanitize($_POST['pay_mode'] ?? 'Bank'),
        'bank_name' => sanitize($_POST['bank_name'] ?? ''),
        'bank_account_number' => sanitize($_POST['bank_account_number'] ?? ''),
        'bank_ref_number' => sanitize($_POST['bank_ref_number'] ?? ''),
        'bank_ifsc_code' => sanitize($_POST['bank_ifsc_code'] ?? ''),
        'esic_number' => sanitize($_POST['esic_number'] ?? ''),
        'pf_number' => sanitize($_POST['pf_number'] ?? ''),
        'remarks' => sanitize($_POST['remarks'] ?? ''),
    ];
    
    // Validation
    if (empty($formData['name'])) {
        $errors[] = 'Name is required.';
    }
    
    if (empty($formData['emp_id']) && empty($formData['employee_id'])) {
        $errors[] = 'Either Employee ID or Emp ID is required.';
    }
    
    // If employee_id is provided, fetch employee details
    if (!empty($formData['employee_id']) && empty($errors)) {
        try {
            $stmt = $db->prepare("
                SELECT employee_code, first_name, middle_name, last_name, designation_id
                FROM employees 
                WHERE employee_id = ?
            ");
            $stmt->execute([$formData['employee_id']]);
            $emp = $stmt->fetch();
            
            if ($emp) {
                if (empty($formData['emp_id'])) {
                    $formData['emp_id'] = $emp['employee_code'];
                }
                if (empty($formData['name'])) {
                    $formData['name'] = trim($emp['first_name'] . ' ' . ($emp['middle_name'] ?? '') . ' ' . $emp['last_name']);
                }
                if (empty($formData['designation']) && !empty($emp['designation_id'])) {
                    $stmt2 = $db->prepare("SELECT designation_name FROM designations WHERE designation_id = ?");
                    $stmt2->execute([$emp['designation_id']]);
                    $desig = $stmt2->fetchColumn();
                    if ($desig) {
                        $formData['designation'] = $desig;
                    }
                }
            }
        } catch (Exception $e) {
            error_log("Error fetching employee details: " . $e->getMessage());
        }
    }
    
    // If no errors, insert record
    if (empty($errors)) {
        try {
            // Ensure table structure is correct before INSERT
            $tableExists = $db->query("SHOW TABLES LIKE 'employee_master_change'")->rowCount() > 0;
            if ($tableExists) {
                $stmt = $db->query("SHOW COLUMNS FROM employee_master_change");
                $existingColumns = [];
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    $existingColumns[] = $row['Field'];
                }
                
                // Check for critical missing columns and add them
                $criticalColumns = [
                    'sl_no' => "ALTER TABLE employee_master_change ADD COLUMN `sl_no` int(11) DEFAULT NULL",
                    'emp_id' => "ALTER TABLE employee_master_change ADD COLUMN `emp_id` varchar(50) DEFAULT NULL",
                    'name' => "ALTER TABLE employee_master_change ADD COLUMN `name` varchar(255) DEFAULT NULL",
                    'designation' => "ALTER TABLE employee_master_change ADD COLUMN `designation` varchar(255) DEFAULT NULL",
                    'site_name' => "ALTER TABLE employee_master_change ADD COLUMN `site_name` varchar(255) DEFAULT NULL",
                    'category' => "ALTER TABLE employee_master_change ADD COLUMN `category` varchar(100) DEFAULT NULL",
                    'change_month' => "ALTER TABLE employee_master_change ADD COLUMN `change_month` int(11) DEFAULT NULL",
                    'change_year' => "ALTER TABLE employee_master_change ADD COLUMN `change_year` int(11) DEFAULT NULL",
                    'present_address' => "ALTER TABLE employee_master_change ADD COLUMN `present_address` text",
                    'permanent_address' => "ALTER TABLE employee_master_change ADD COLUMN `permanent_address` text",
                    'pay_mode' => "ALTER TABLE employee_master_change ADD COLUMN `pay_mode` enum('Bank','Hold') DEFAULT 'Bank'",
                    'bank_name' => "ALTER TABLE employee_master_change ADD COLUMN `bank_name` varchar(255) DEFAULT NULL",
                    'bank_account_number' => "ALTER TABLE employee_master_change ADD COLUMN `bank_account_number` varchar(100) DEFAULT NULL",
                    'bank_ref_number' => "ALTER TABLE employee_master_change ADD COLUMN `bank_ref_number` varchar(100) DEFAULT NULL",
                    'bank_ifsc_code' => "ALTER TABLE employee_master_change ADD COLUMN `bank_ifsc_code` varchar(50) DEFAULT NULL",
                    'esic_number' => "ALTER TABLE employee_master_change ADD COLUMN `esic_number` varchar(50) DEFAULT NULL",
                    'pf_number' => "ALTER TABLE employee_master_change ADD COLUMN `pf_number` varchar(50) DEFAULT NULL",
                    'remarks' => "ALTER TABLE employee_master_change ADD COLUMN `remarks` text",
                ];
                
                foreach ($criticalColumns as $column => $alterSql) {
                    if (!in_array($column, $existingColumns)) {
                        try {
                            $db->exec($alterSql);
                            error_log("Added missing column: {$column} to employee_master_change table");
                        } catch (Exception $e) {
                            error_log("Error adding column {$column}: " . $e->getMessage());
                        }
                    }
                }
                
                // FIX: Check and fix change_id AUTO_INCREMENT before INSERT
                $colCheck = $db->query("SHOW COLUMNS FROM employee_master_change LIKE 'change_id'");
                $colInfo = $colCheck->fetch(PDO::FETCH_ASSOC);
                
                if ($colInfo && strpos(strtolower($colInfo['Extra']), 'auto_increment') === false) {
                    error_log("Fixing change_id AUTO_INCREMENT before INSERT...");
                    try {
                        // Update any NULL or 0 change_id values first
                        $nullCount = (int)$db->query("SELECT COUNT(*) FROM employee_master_change WHERE change_id IS NULL OR change_id = 0")->fetchColumn();
                        if ($nullCount > 0) {
                            $maxId = (int)$db->query("SELECT COALESCE(MAX(change_id), 0) FROM employee_master_change WHERE change_id > 0")->fetchColumn();
                            for ($i = 0; $i < $nullCount; $i++) {
                                $maxId++;
                                $db->exec("UPDATE employee_master_change SET change_id = {$maxId} WHERE (change_id IS NULL OR change_id = 0) LIMIT 1");
                            }
                        }
                        // Add AUTO_INCREMENT
                        $db->exec("ALTER TABLE employee_master_change MODIFY COLUMN `change_id` int(11) NOT NULL AUTO_INCREMENT");
                        error_log("Fixed change_id AUTO_INCREMENT successfully");
                    } catch (Exception $autoIncErr) {
                        error_log("Error fixing AUTO_INCREMENT: " . $autoIncErr->getMessage());
                    }
                }
            }
            
            $userId = getCurrentUserId();
            
            $sql = "
                INSERT INTO employee_master_change 
                (site_id, employee_id, sl_no, emp_id, name, designation, site_name, category, 
                 change_month, change_year, present_address, permanent_address, pay_mode, bank_name, bank_account_number, 
                 bank_ref_number, bank_ifsc_code, esic_number, pf_number, remarks, created_by)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ";
            
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $siteId,
                $formData['employee_id'],
                $formData['sl_no'],
                $formData['emp_id'],
                $formData['name'],
                $formData['designation'],
                $formData['site_name'],
                $formData['category'],
                $formData['change_month'],
                $formData['change_year'],
                $formData['present_address'],
                $formData['permanent_address'],
                $formData['pay_mode'],
                $formData['bank_name'],
                $formData['bank_account_number'],
                $formData['bank_ref_number'],
                $formData['bank_ifsc_code'],
                $formData['esic_number'],
                $formData['pf_number'],
                $formData['remarks'],
                $userId
            ]);
            
            logAudit('CREATE', 'employee_master_change', $db->lastInsertId(), null, $formData);
            
            redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Employee master change record created successfully.');
            
        } catch (Exception $e) {
            error_log("Error creating employee master change: " . $e->getMessage());
            $errors[] = 'Error creating record: ' . $e->getMessage();
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2>Add Employee Master Change</h2>
        <a href="<?php echo BASE_URL; ?>/modules/employee/employee_master_change_list.php" class="btn btn-secondary">Back to List</a>
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error">
        <ul>
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <form method="POST" class="form-container">
        <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($formData['sl_no'] ?? $nextSlNo); ?>" required>
                </div>
                
                <div class="form-group">
                    <label>Employee (Search to auto-fill)</label>
                    <div style="position: relative;">
                        <input type="hidden" name="employee_id" id="employee_id" value="">
                        <input type="text" 
                               id="employee_search" 
                               autocomplete="off"
                               placeholder="Type employee code or name to search..."
                               class="form-control employee-search-input">
                        <div id="employee_search_results" class="search-dropdown"></div>
                    </div>
                    <small style="color: #666; font-size: 11px;">Type at least 2 characters to search</small>
                </div>
                
                <div class="form-group">
                    <label>Emp ID <span class="required">*</span></label>
                    <input type="text" name="emp_id" id="emp_id" value="<?php echo htmlspecialchars($formData['emp_id'] ?? ''); ?>" required>
                </div>
                
                <div class="form-group">
                    <label>Name <span class="required">*</span></label>
                    <input type="text" name="name" id="name" value="<?php echo htmlspecialchars($formData['name'] ?? ''); ?>" required>
                </div>
                
                <div class="form-group">
                    <label>Designation</label>
                    <input type="text" name="designation" id="designation" value="<?php echo htmlspecialchars($formData['designation'] ?? ''); ?>" list="designation-list">
                    <datalist id="designation-list">
                        <?php foreach ($designations as $desig): ?>
                        <option value="<?php echo htmlspecialchars($desig['designation_name']); ?>">
                        <?php endforeach; ?>
                    </datalist>
                </div>
                
                <div class="form-group">
                    <label>Site Name</label>
                    <input type="text" name="site_name" value="<?php echo htmlspecialchars($formData['site_name'] ?? $siteName); ?>">
                </div>
                
                <div class="form-group">
                    <label>Category</label>
                    <input type="text" name="category" value="<?php echo htmlspecialchars($formData['category'] ?? ''); ?>" list="category-list">
                    <datalist id="category-list">
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo htmlspecialchars($cat); ?>">
                        <?php endforeach; ?>
                    </datalist>
                </div>
                
                <div class="form-group">
                    <label>Month</label>
                    <select name="change_month" class="form-control">
                        <option value="">Select Month</option>
                        <?php 
                        $months = [
                            1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April',
                            5 => 'May', 6 => 'June', 7 => 'July', 8 => 'August',
                            9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December'
                        ];
                        $selectedMonth = $formData['change_month'] ?? date('n');
                        foreach ($months as $num => $name): 
                        ?>
                        <option value="<?php echo $num; ?>" <?php echo $selectedMonth == $num ? 'selected' : ''; ?>>
                            <?php echo $name; ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Year</label>
                    <input type="number" 
                           name="change_year" 
                           class="form-control" 
                           value="<?php echo htmlspecialchars($formData['change_year'] ?? date('Y')); ?>" 
                           min="2000" 
                           max="2099" 
                           placeholder="Enter year (e.g., 2025)">
                    <small style="color: #666; font-size: 11px;">Type the year (2000-2099)</small>
                </div>
            </div>
        </div>
        
        <div class="form-section">
            <h3>Address Information</h3>
            <div class="form-grid">
                <div class="form-group full-width">
                    <label>Present Address</label>
                    <textarea name="present_address" rows="3"><?php echo htmlspecialchars($formData['present_address'] ?? ''); ?></textarea>
                </div>
                
                <div class="form-group full-width">
                    <label>Permanent Address</label>
                    <textarea name="permanent_address" rows="3"><?php echo htmlspecialchars($formData['permanent_address'] ?? ''); ?></textarea>
                </div>
            </div>
        </div>
        
        <div class="form-section">
            <h3>Bank & Payment Information</h3>
            <div class="form-grid">
                <div class="form-group">
                    <label>Pay Mode <span class="required">*</span></label>
                    <select name="pay_mode" required>
                        <option value="Bank" <?php echo ($formData['pay_mode'] ?? 'Bank') === 'Bank' ? 'selected' : ''; ?>>Bank</option>
                        <option value="Hold" <?php echo ($formData['pay_mode'] ?? '') === 'Hold' ? 'selected' : ''; ?>>Hold</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Bank Name</label>
                    <input type="text" name="bank_name" value="<?php echo htmlspecialchars($formData['bank_name'] ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label>Bank A/C No.</label>
                    <input type="text" name="bank_account_number" value="<?php echo htmlspecialchars($formData['bank_account_number'] ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label>Bank Ref. No.</label>
                    <input type="text" name="bank_ref_number" value="<?php echo htmlspecialchars($formData['bank_ref_number'] ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label>Bank IFSC Code</label>
                    <input type="text" name="bank_ifsc_code" value="<?php echo htmlspecialchars($formData['bank_ifsc_code'] ?? ''); ?>" style="text-transform: uppercase;">
                </div>
            </div>
        </div>
        
        <div class="form-section">
            <h3>Statutory Information</h3>
            <div class="form-grid">
                <div class="form-group">
                    <label>ESIC No</label>
                    <input type="text" name="esic_number" value="<?php echo htmlspecialchars($formData['esic_number'] ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label>PF NO</label>
                    <input type="text" name="pf_number" value="<?php echo htmlspecialchars($formData['pf_number'] ?? ''); ?>">
                </div>
            </div>
        </div>
        
        <div class="form-section">
            <h3>Additional Information</h3>
            <div class="form-grid">
                <div class="form-group full-width">
                    <label>Remarks (Please mention the Change)</label>
                    <textarea name="remarks" rows="4"><?php echo htmlspecialchars($formData['remarks'] ?? ''); ?></textarea>
                </div>
            </div>
        </div>
        
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">Save</button>
            <a href="<?php echo BASE_URL; ?>/modules/employee/employee_master_change_list.php" class="btn btn-secondary">Cancel</a>
        </div>
    </form>
</div>

<script>
let searchTimeout;
const employeeSearchInput = document.getElementById('employee_search');
const employeeIdInput = document.getElementById('employee_id');
const searchResultsDiv = document.getElementById('employee_search_results');
const empIdInput = document.getElementById('emp_id');
const nameInput = document.getElementById('name');
const designationInput = document.getElementById('designation');

if (employeeSearchInput) {
    employeeSearchInput.addEventListener('input', function(e) {
        const query = e.target.value.trim();
        clearTimeout(searchTimeout);
        
        if (query.length < 2) {
            searchResultsDiv.classList.remove('active');
            employeeIdInput.value = '';
            clearEmployeeDetails();
            return;
        }
        
        searchResultsDiv.innerHTML = '<div class="search-loading">Searching...</div>';
        searchResultsDiv.classList.add('active');
        
        searchTimeout = setTimeout(function() {
            searchEmployees(query);
        }, 300);
    });
}

function searchEmployees(query) {
    if (!employeeSearchInput || !searchResultsDiv) return;
    
    fetch('<?php echo BASE_URL; ?>/api/search_employees.php?q=' + encodeURIComponent(query))
        .then(response => response.json())
        .then(data => {
            if (data.success && data.employees && data.employees.length > 0) {
                let html = '';
                data.employees.forEach(function(emp) {
                    html += '<div class="search-result-item" onclick="selectEmployee(' + 
                            JSON.stringify(emp).replace(/"/g, '&quot;') + ')">';
                    html += '<div class="search-result-name">' + escapeHtml(emp.full_name) + '</div>';
                    html += '<div class="search-result-details">';
                    html += '<span>ID: ' + escapeHtml(emp.employee_code) + '</span>';
                    if (emp.department_name) html += '<span>Dept: ' + escapeHtml(emp.department_name) + '</span>';
                    if (emp.designation_name) html += '<span>Desig: ' + escapeHtml(emp.designation_name) + '</span>';
                    html += '</div></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(emp) {
    if (!employeeSearchInput || !employeeIdInput || !searchResultsDiv) return;
    
    employeeSearchInput.value = emp.full_name + ' (' + emp.employee_code + ')';
    employeeIdInput.value = emp.employee_id;
    
    // Auto-fill employee details
    if (empIdInput) empIdInput.value = emp.employee_code || '';
    if (nameInput) nameInput.value = emp.full_name || '';
    if (designationInput && emp.designation_name) designationInput.value = emp.designation_name || '';
    
    searchResultsDiv.classList.remove('active');
}

function clearEmployeeDetails() {
    if (empIdInput) empIdInput.value = '';
    if (nameInput) nameInput.value = '';
    if (designationInput) designationInput.value = '';
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Close dropdown when clicking outside
document.addEventListener('click', function(e) {
    if (employeeSearchInput && searchResultsDiv) {
        if (!employeeSearchInput.contains(e.target) && !searchResultsDiv.contains(e.target)) {
            searchResultsDiv.classList.remove('active');
        }
    }
});
</script>

<style>
.form-container {
    padding: 20px;
}

.form-section {
    margin-bottom: 30px;
    padding: 20px;
    background: #f9f9f9;
    border-radius: 5px;
}

.form-section h3 {
    margin-top: 0;
    margin-bottom: 20px;
    color: #333;
    border-bottom: 2px solid #4CAF50;
    padding-bottom: 10px;
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 15px;
}

.form-group {
    display: flex;
    flex-direction: column;
}

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

.form-group label {
    margin-bottom: 5px;
    font-weight: 500;
    color: #555;
}

.form-group .required {
    color: #dc3545;
}

.form-group input,
.form-group select,
.form-group textarea {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

.form-actions {
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #ddd;
    display: flex;
    gap: 10px;
}

/* Employee Search Styles */
.employee-search-input {
    width: 100%;
}

.search-dropdown {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid #ddd;
    border-top: none;
    border-radius: 0 0 4px 4px;
    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 15px;
    cursor: pointer;
    border-bottom: 1px solid #f0f0f0;
    transition: background-color 0.2s;
}

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

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

.search-result-name {
    font-weight: 500;
    color: #333;
    margin-bottom: 5px;
}

.search-result-details {
    font-size: 12px;
    color: #666;
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
}

.search-result-details span {
    display: inline-block;
}

.search-loading,
.search-no-results {
    padding: 15px;
    text-align: center;
    color: #666;
    font-size: 14px;
}

.search-loading {
    color: #4CAF50;
}
</style>

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

