<?php
/**
 * Enterprise HRM ERP System - Overtime Rates Configuration
 */

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

if (!hasAdminAccess()) {
    $_SESSION['error'] = 'You do not have permission to access this resource.';
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$pageTitle = 'Overtime Rates';
$currentModule = 'overtime';

$siteId = getCurrentSiteId();
$errors = [];
$success = false;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'rate_name' => sanitize($_POST['rate_name'] ?? ''),
        'rate_multiplier' => isset($_POST['rate_multiplier']) ? (float)$_POST['rate_multiplier'] : 1.5,
        'effective_from' => $_POST['effective_from'] ?? '',
        'effective_to' => $_POST['effective_to'] ?? '',
        'is_active' => isset($_POST['is_active']) ? 1 : 0,
    ];
    
    // Validation
    if (empty($formData['rate_name'])) {
        $errors[] = 'Rate name is required.';
    }
    
    if ($formData['rate_multiplier'] <= 0) {
        $errors[] = 'Rate multiplier must be greater than 0.';
    }
    
    if (empty($formData['effective_from'])) {
        $errors[] = 'Effective from date is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $stmt = $db->prepare("
                INSERT INTO overtime_rates (
                    site_id, rate_name, rate_multiplier, 
                    effective_from, effective_to, is_active
                ) VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $siteId,
                $formData['rate_name'],
                $formData['rate_multiplier'],
                $formData['effective_from'],
                $formData['effective_to'] ?: null,
                $formData['is_active']
            ]);
            
            $success = true;
            logAudit('CREATE', 'overtime_rates', $db->lastInsertId());
            
        } catch (Exception $e) {
            error_log("Error creating OT rate: " . $e->getMessage());
            $errors[] = 'An error occurred while creating overtime rate. Please try again.';
        }
    }
}

// Get OT rates
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT * FROM overtime_rates
        WHERE site_id = ?
        ORDER BY effective_from DESC, created_at DESC
    ");
    $stmt->execute([$siteId]);
    $rates = $stmt->fetchAll();
} catch (Exception $e) {
    error_log("Error loading OT rates: " . $e->getMessage());
    $rates = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Overtime Rates Configuration</h2>
        <a href="<?php echo BASE_URL; ?>/modules/overtime/list.php" class="btn btn-secondary">Back to Overtime</a>
    </div>
    
    <?php if ($success): ?>
    <div class="alert alert-success" style="margin-top: 20px;">
        Overtime rate created successfully.
    </div>
    <?php endif; ?>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error" style="margin-top: 20px;">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <!-- Add New Rate Form -->
    <div style="margin-top: 20px; padding: 20px; background: #f9fafb; border-radius: 8px;">
        <h3 style="margin-bottom: 15px;">Add New Overtime Rate</h3>
        <form method="POST">
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
                <div class="form-group">
                    <label class="form-label" for="rate_name">Rate Name *</label>
                    <input type="text" id="rate_name" name="rate_name" class="form-control" required
                           placeholder="e.g., Standard OT Rate">
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="rate_multiplier">Rate Multiplier *</label>
                    <input type="number" id="rate_multiplier" name="rate_multiplier" class="form-control" required
                           value="1.5" min="0.1" max="10" step="0.1">
                    <small style="color: var(--text-secondary);">Multiplier for hourly rate (e.g., 1.5 = 1.5x hourly rate)</small>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="effective_from">Effective From *</label>
                    <input type="date" id="effective_from" name="effective_from" class="form-control" required
                           value="<?php echo date('Y-m-d'); ?>">
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="effective_to">Effective To</label>
                    <input type="date" id="effective_to" name="effective_to" class="form-control"
                           placeholder="Leave blank for indefinite">
                </div>
                
                <div class="form-group" style="grid-column: 1 / -1;">
                    <label style="display: flex; align-items: center; gap: 10px; cursor: pointer;">
                        <input type="checkbox" id="is_active" name="is_active" value="1" checked>
                        <span>Active</span>
                    </label>
                </div>
            </div>
            
            <div style="margin-top: 20px; text-align: right;">
                <button type="submit" class="btn btn-primary">Create Rate</button>
            </div>
        </form>
    </div>
    
    <!-- Existing Rates -->
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px;">Existing Overtime Rates</h3>
        <?php if (count($rates) > 0): ?>
        <table class="data-table">
            <thead>
                <tr>
                    <th>Rate Name</th>
                    <th>Multiplier</th>
                    <th>Effective From</th>
                    <th>Effective To</th>
                    <th>Status</th>
                    <th>Created At</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rates as $rate): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($rate['rate_name']); ?></strong></td>
                    <td><?php echo number_format($rate['rate_multiplier'], 2); ?>x</td>
                    <td><?php echo formatDate($rate['effective_from']); ?></td>
                    <td><?php echo $rate['effective_to'] ? formatDate($rate['effective_to']) : 'Indefinite'; ?></td>
                    <td>
                        <span class="status-badge status-<?php echo $rate['is_active'] ? 'active' : 'inactive'; ?>">
                            <?php echo $rate['is_active'] ? 'Active' : 'Inactive'; ?>
                        </span>
                    </td>
                    <td><?php echo formatDateTime($rate['created_at']); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php else: ?>
        <div class="table-empty">
            <div class="table-empty-icon">⏱️</div>
            <div class="table-empty-message">No overtime rates configured</div>
        </div>
        <?php endif; ?>
    </div>
</div>

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

