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

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

$pageTitle = 'Create Exit Record';
$currentModule = 'exit';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'employee_id' => isset($_POST['employee_id']) ? (int)$_POST['employee_id'] : 0,
        'exit_type' => sanitize($_POST['exit_type'] ?? 'resigned'),
        'last_working_date' => $_POST['last_working_date'] ?? '',
        'notice_served_date' => $_POST['notice_served_date'] ?? '',
        'notice_period_days' => isset($_POST['notice_period_days']) ? (int)$_POST['notice_period_days'] : 0,
        'exit_reason' => sanitize($_POST['exit_reason'] ?? ''),
        'final_settlement_amount' => isset($_POST['final_settlement_amount']) ? (float)$_POST['final_settlement_amount'] : 0,
        'final_settlement_date' => $_POST['final_settlement_date'] ?? '',
    ];
    
    // Validation
    if ($formData['employee_id'] <= 0) {
        $errors[] = 'Please select an employee.';
    }
    
    if (empty($formData['last_working_date'])) {
        $errors[] = 'Last working date is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Check if exit record already exists
            $stmt = $db->prepare("SELECT exit_id FROM employee_exits WHERE employee_id = ?");
            $stmt->execute([$formData['employee_id']]);
            if ($stmt->fetch()) {
                $errors[] = 'Exit record already exists for this employee.';
                $db->rollBack();
            } else {
                // Insert exit record
                $stmt = $db->prepare("
                    INSERT INTO employee_exits (
                        employee_id, site_id, exit_type, last_working_date,
                        notice_served_date, notice_period_days, exit_reason,
                        final_settlement_amount, final_settlement_date,
                        exit_status, created_by
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)
                ");
                $stmt->execute([
                    $formData['employee_id'],
                    $siteId,
                    $formData['exit_type'],
                    $formData['last_working_date'],
                    $formData['notice_served_date'] ?: null,
                    $formData['notice_period_days'],
                    $formData['exit_reason'],
                    $formData['final_settlement_amount'],
                    $formData['final_settlement_date'] ?: null,
                    getCurrentUserId()
                ]);
                
                $exitId = $db->lastInsertId();
                
                // Update employee status
                $newStatus = $formData['exit_type'] === 'resigned' ? 'resigned' : 
                            ($formData['exit_type'] === 'absconded' ? 'absconded' : 'terminated');
                
                $stmt = $db->prepare("
                    UPDATE employees SET
                        employment_status = ?,
                        updated_at = NOW()
                    WHERE employee_id = ?
                ");
                $stmt->execute([$newStatus, $formData['employee_id']]);
                
                $db->commit();
                
                logAudit('CREATE', 'employee_exits', $exitId);
                
                redirect(BASE_URL . '/modules/exit/list.php', 'Exit record created successfully.');
            }
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error creating exit: " . $e->getMessage());
            $errors[] = 'An error occurred while creating exit record. Please try again.';
        }
    }
}

// Get active employees
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT employee_id, employee_code, first_name, last_name, middle_name
        FROM employees
        WHERE site_id = ? AND employment_status = 'active'
        ORDER BY employee_code
    ");
    $stmt->execute([$siteId]);
    $employees = $stmt->fetchAll();
} catch (Exception $e) {
    error_log("Error loading employees: " . $e->getMessage());
    $employees = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Create Employee Exit Record</h2>
        <a href="<?php echo BASE_URL; ?>/modules/exit/list.php" class="btn btn-secondary">Back to Exits</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>
                    <option value="">Select Employee</option>
                    <?php foreach ($employees as $emp): ?>
                    <option value="<?php echo $emp['employee_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="exit_type">Exit Type *</label>
                <select id="exit_type" name="exit_type" class="form-control" required>
                    <option value="resigned" <?php echo ($formData['exit_type'] ?? 'resigned') === 'resigned' ? 'selected' : ''; ?>>Resigned</option>
                    <option value="absconded" <?php echo ($formData['exit_type'] ?? '') === 'absconded' ? 'selected' : ''; ?>>Absconded</option>
                    <option value="terminated" <?php echo ($formData['exit_type'] ?? '') === 'terminated' ? 'selected' : ''; ?>>Terminated</option>
                    <option value="retired" <?php echo ($formData['exit_type'] ?? '') === 'retired' ? 'selected' : ''; ?>>Retired</option>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="last_working_date">Last Working Date *</label>
                <input type="date" id="last_working_date" name="last_working_date" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['last_working_date'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="notice_served_date">Notice Served Date</label>
                <input type="date" id="notice_served_date" name="notice_served_date" class="form-control"
                       value="<?php echo htmlspecialchars($formData['notice_served_date'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="notice_period_days">Notice Period (Days)</label>
                <input type="number" id="notice_period_days" name="notice_period_days" class="form-control"
                       value="<?php echo htmlspecialchars($formData['notice_period_days'] ?? '0'); ?>" min="0">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="final_settlement_amount">Final Settlement Amount</label>
                <input type="number" id="final_settlement_amount" name="final_settlement_amount" class="form-control"
                       value="<?php echo htmlspecialchars($formData['final_settlement_amount'] ?? '0'); ?>" min="0" step="0.01">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="final_settlement_date">Final Settlement Date</label>
                <input type="date" id="final_settlement_date" name="final_settlement_date" class="form-control"
                       value="<?php echo htmlspecialchars($formData['final_settlement_date'] ?? ''); ?>">
            </div>
            
            <div class="form-group" style="grid-column: 1 / -1;">
                <label class="form-label" for="exit_reason">Exit Reason</label>
                <textarea id="exit_reason" name="exit_reason" class="form-control" rows="3"
                          placeholder="Enter exit reason..."><?php echo htmlspecialchars($formData['exit_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/exit/list.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Create Exit Record</button>
        </div>
    </form>
</div>

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

