<?php
/**
 * Enterprise HRM ERP System - Edit 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 = 'Edit Employee Master Change';
$currentModule = 'payroll';
$currentTab = 'employee_master_change';

$siteId = getCurrentSiteId();

// Get and validate ID from URL
$changeId = 0;
if (isset($_GET['id'])) {
    $changeId = filter_var($_GET['id'], FILTER_VALIDATE_INT);
    if ($changeId === false) {
        $changeId = 0;
    }
}

if ($changeId <= 0) {
    redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Invalid record ID. Please select a valid record to edit.', 'error');
}

// Get record data
try {
    $db = getDB();
    
    // Build where clause based on role
    if (isHRAdmin()) {
        $where = "change_id = ? AND created_by = ?";
        $params = [$changeId, getCurrentUserId()];
    } else {
        $where = "change_id = ?";
        $params = [$changeId];
    }
    
    // First check if table exists
    $tableExists = $db->query("SHOW TABLES LIKE 'employee_master_change'")->rowCount() > 0;
    if (!$tableExists) {
        redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Table does not exist. Please run the migration first.', 'error');
    }
    
    // Check if change_id column exists
    $stmt = $db->query("SHOW COLUMNS FROM employee_master_change LIKE 'change_id'");
    if ($stmt->rowCount() == 0) {
        redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Table structure is incorrect. Please run the migration.', 'error');
    }
    
    $stmt = $db->prepare("SELECT * FROM employee_master_change WHERE {$where}");
    $stmt->execute($params);
    $record = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$record) {
        error_log("Edit page - Record not found. change_id: {$changeId}, where: {$where}, params: " . print_r($params, true));
        redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Record not found or access denied. Record ID: ' . $changeId, 'error');
    }
    
    // Ensure change_id exists in record
    if (empty($record['change_id'])) {
        error_log("Edit page - Record found but change_id is empty. Record: " . print_r($record, true));
        redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Record found but ID is missing. Please contact administrator.', 'error');
    }
    
    $formData = $record;
    
    // 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([$record['site_id']]);
    $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 record: " . $e->getMessage());
    redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Error loading record data.', 'error');
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'sl_no' => isset($_POST['sl_no']) ? (int)$_POST['sl_no'] : null,
        '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'] ?? ''),
        '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, update record
    if (empty($errors)) {
        try {
            $oldValues = $record;
            
            $sql = "
                UPDATE employee_master_change 
                SET sl_no = ?, employee_id = ?, 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 = ?
                WHERE change_id = ?
            ";
            
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $formData['sl_no'],
                $formData['employee_id'],
                $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'],
                $changeId
            ]);
            
            logAudit('UPDATE', 'employee_master_change', $changeId, $oldValues, $formData);
            
            redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Employee master change record updated successfully.');
            
        } catch (Exception $e) {
            error_log("Error updating employee master change: " . $e->getMessage());
            $errors[] = 'Error updating record: ' . $e->getMessage();
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2>Edit 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</label>
                    <input type="number" name="sl_no" value="<?php echo htmlspecialchars($formData['sl_no'] ?? ''); ?>">
                </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="<?php echo htmlspecialchars($formData['employee_id'] ?? ''); ?>">
                        <input type="text" 
                               id="employee_search" 
                               autocomplete="off"
                               placeholder="Type employee code or name to search..."
                               value="<?php 
                                   if (!empty($formData['employee_id'])) {
                                       $selectedEmp = null;
                                       foreach ($employees as $emp) {
                                           if ($emp['employee_id'] == $formData['employee_id']) {
                                               $selectedEmp = $emp;
                                               break;
                                           }
                                       }
                                       if ($selectedEmp) {
                                           echo htmlspecialchars($selectedEmp['employee_code'] . ' - ' . trim($selectedEmp['first_name'] . ' ' . ($selectedEmp['middle_name'] ?? '') . ' ' . $selectedEmp['last_name']));
                                       }
                                   }
                               ?>"
                               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'] ?? ''); ?>">
                </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'] ?? '';
                        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'] ?? ''); ?>" 
                           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">Update</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'; ?>

