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

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

$pageTitle = 'Create Employee Transfer';
$currentModule = 'transfer';

$siteId = getCurrentSiteId();
$errors = [];
$formData = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'employee_id' => isset($_POST['employee_id']) ? (int)$_POST['employee_id'] : 0,
        'from_site_id' => isset($_POST['from_site_id']) ? (int)$_POST['from_site_id'] : 0,
        'to_site_id' => isset($_POST['to_site_id']) ? (int)$_POST['to_site_id'] : 0,
        'transfer_date' => $_POST['transfer_date'] ?? '',
        'transfer_reason' => sanitize($_POST['transfer_reason'] ?? ''),
        'new_department_id' => isset($_POST['new_department_id']) && $_POST['new_department_id'] > 0 ? (int)$_POST['new_department_id'] : null,
        'new_designation_id' => isset($_POST['new_designation_id']) && $_POST['new_designation_id'] > 0 ? (int)$_POST['new_designation_id'] : null,
    ];
    
    // Validation
    if ($formData['employee_id'] <= 0) {
        $errors[] = 'Please select an employee.';
    }
    
    if ($formData['from_site_id'] <= 0 || $formData['to_site_id'] <= 0) {
        $errors[] = 'Please select both from and to sites.';
    }
    
    if ($formData['from_site_id'] == $formData['to_site_id']) {
        $errors[] = 'From site and to site must be different.';
    }
    
    if (empty($formData['transfer_date'])) {
        $errors[] = 'Transfer date is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Get employee current details
            $stmt = $db->prepare("SELECT site_id, department_id, designation_id FROM employees WHERE employee_id = ?");
            $stmt->execute([$formData['employee_id']]);
            $employee = $stmt->fetch();
            
            if (!$employee) {
                throw new Exception('Employee not found.');
            }
            
            // Insert transfer record
            $stmt = $db->prepare("
                INSERT INTO employee_transfers (
                    employee_id, from_site_id, to_site_id, transfer_date,
                    transfer_reason, old_department_id, new_department_id,
                    old_designation_id, new_designation_id, transfer_status, created_by
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)
            ");
            $stmt->execute([
                $formData['employee_id'],
                $formData['from_site_id'],
                $formData['to_site_id'],
                $formData['transfer_date'],
                $formData['transfer_reason'],
                $employee['department_id'],
                $formData['new_department_id'],
                $employee['designation_id'],
                $formData['new_designation_id'],
                getCurrentUserId()
            ]);
            
            $transferId = $db->lastInsertId();
            
            // If auto-approve or immediate transfer, update employee
            if (hasAdminAccess()) {
                // Update employee site and department/designation
                $updateFields = ['site_id = ?'];
                $updateParams = [$formData['to_site_id']];
                
                if ($formData['new_department_id']) {
                    $updateFields[] = 'department_id = ?';
                    $updateParams[] = $formData['new_department_id'];
                }
                
                if ($formData['new_designation_id']) {
                    $updateFields[] = 'designation_id = ?';
                    $updateParams[] = $formData['new_designation_id'];
                }
                
                $updateParams[] = $formData['employee_id'];
                
                $stmt = $db->prepare("UPDATE employees SET " . implode(', ', $updateFields) . " WHERE employee_id = ?");
                $stmt->execute($updateParams);
                
                // Update transfer status
                $stmt = $db->prepare("
                    UPDATE employee_transfers SET
                        transfer_status = 'completed',
                        approved_by = ?,
                        approved_at = NOW()
                    WHERE transfer_id = ?
                ");
                $stmt->execute([getCurrentUserId(), $transferId]);
            }
            
            $db->commit();
            
            logAudit('CREATE', 'employee_transfers', $transferId);
            
            redirect(BASE_URL . '/modules/transfer/list.php', 'Employee transfer created successfully.');
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error creating transfer: " . $e->getMessage());
            $errors[] = 'An error occurred while creating transfer. Please try again.';
        }
    }
}

// Get employees
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT employee_id, employee_code, first_name, last_name, middle_name, site_id, department_id, designation_id
        FROM employees
        WHERE employment_status = 'active'
        ORDER BY employee_code
    ");
    $stmt->execute();
    $employees = $stmt->fetchAll();
    
    // Get sites
    $stmt = $db->prepare("SELECT site_id, site_name FROM sites WHERE site_status = 'active' ORDER BY site_name");
    $stmt->execute();
    $sites = $stmt->fetchAll();
    
    // Get departments
    $stmt = $db->prepare("SELECT department_id, department_name FROM departments WHERE department_status = 'active' ORDER BY department_name");
    $stmt->execute();
    $departments = $stmt->fetchAll();
    
    // Get designations
    $stmt = $db->prepare("SELECT designation_id, designation_name FROM designations WHERE designation_status = 'active' ORDER BY designation_name");
    $stmt->execute();
    $designations = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Error loading data: " . $e->getMessage());
    $employees = [];
    $sites = [];
    $departments = [];
    $designations = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Create Employee Transfer</h2>
        <a href="<?php echo BASE_URL; ?>/modules/transfer/list.php" class="btn btn-secondary">Back to Transfers</a>
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <form method="POST" style="margin-top: 20px;">
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
            <div class="form-group">
                <label class="form-label" for="employee_id">Employee *</label>
                <select id="employee_id" name="employee_id" class="form-control" required onchange="loadEmployeeDetails()">
                    <option value="">Select Employee</option>
                    <?php foreach ($employees as $emp): ?>
                    <option value="<?php echo $emp['employee_id']; ?>" 
                            data-site="<?php echo $emp['site_id']; ?>"
                            data-dept="<?php echo $emp['department_id']; ?>"
                            data-desig="<?php echo $emp['designation_id']; ?>">
                        <?php echo htmlspecialchars($emp['employee_code'] . ' - ' . trim($emp['first_name'] . ' ' . ($emp['middle_name'] ?? '') . ' ' . $emp['last_name'])); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="transfer_date">Transfer Date *</label>
                <input type="date" id="transfer_date" name="transfer_date" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['transfer_date'] ?? date('Y-m-d')); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="from_site_id">From Site *</label>
                <select id="from_site_id" name="from_site_id" class="form-control" required>
                    <option value="">Select Site</option>
                    <?php foreach ($sites as $site): ?>
                    <option value="<?php echo $site['site_id']; ?>">
                        <?php echo htmlspecialchars($site['site_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="to_site_id">To Site *</label>
                <select id="to_site_id" name="to_site_id" class="form-control" required>
                    <option value="">Select Site</option>
                    <?php foreach ($sites as $site): ?>
                    <option value="<?php echo $site['site_id']; ?>">
                        <?php echo htmlspecialchars($site['site_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="new_department_id">New Department</label>
                <select id="new_department_id" name="new_department_id" class="form-control">
                    <option value="">Keep Current</option>
                    <?php foreach ($departments as $dept): ?>
                    <option value="<?php echo $dept['department_id']; ?>">
                        <?php echo htmlspecialchars($dept['department_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="new_designation_id">New Designation</label>
                <select id="new_designation_id" name="new_designation_id" class="form-control">
                    <option value="">Keep Current</option>
                    <?php foreach ($designations as $desig): ?>
                    <option value="<?php echo $desig['designation_id']; ?>">
                        <?php echo htmlspecialchars($desig['designation_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group" style="grid-column: 1 / -1;">
                <label class="form-label" for="transfer_reason">Transfer Reason</label>
                <textarea id="transfer_reason" name="transfer_reason" class="form-control" rows="3"
                          placeholder="Enter transfer reason..."><?php echo htmlspecialchars($formData['transfer_reason'] ?? ''); ?></textarea>
            </div>
        </div>
        
        <div style="margin-top: 30px; text-align: right; padding-top: 20px; border-top: 1px solid var(--border-color);">
            <a href="<?php echo BASE_URL; ?>/modules/transfer/list.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Create Transfer</button>
        </div>
    </form>
</div>

<script>
function loadEmployeeDetails() {
    const select = document.getElementById('employee_id');
    const option = select.options[select.selectedIndex];
    if (option.value) {
        document.getElementById('from_site_id').value = option.dataset.site || '';
    }
}
</script>

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

