<?php
/**
 * Enterprise HRM ERP System - Edit Overtime Record
 */

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

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

$siteId = getCurrentSiteId();
$overtimeId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($overtimeId <= 0) {
    redirect(BASE_URL . '/modules/overtime/list.php', 'Invalid overtime ID.', 'error');
}

// Get overtime record with employee details
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT ot.*, e.employee_code, e.first_name, e.last_name, e.middle_name
        FROM overtime_records ot
        INNER JOIN employees e ON ot.employee_id = e.employee_id
        WHERE ot.overtime_id = ? AND ot.site_id = ?
    ");
    $stmt->execute([$overtimeId, $siteId]);
    $overtime = $stmt->fetch();
    
    if (!$overtime) {
        redirect(BASE_URL . '/modules/overtime/list.php', 'Overtime record not found.', 'error');
    }
    
    $formData = $overtime;
    
    // Check if locked
    $isLocked = isDataLocked('overtime', $siteId, $overtime['month'], $overtime['year']);
    if ($isLocked && !hasAdminAccess()) {
        requireUnlocked('overtime', $siteId, $overtime['month'], $overtime['year']);
    }
    
} catch (Exception $e) {
    error_log("Error loading overtime: " . $e->getMessage());
    redirect(BASE_URL . '/modules/overtime/list.php', 'Error loading overtime data.', 'error');
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'overtime_hours' => isset($_POST['overtime_hours']) ? (float)$_POST['overtime_hours'] : 0,
        'remarks' => sanitize($_POST['remarks'] ?? ''),
    ];
    
    // Validation
    if ($formData['overtime_hours'] <= 0) {
        $errors[] = 'Overtime hours must be greater than 0.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Recalculate OT amount
            $otAmount = $formData['overtime_hours'] * $overtime['overtime_rate'];
            
            // Update overtime record
            $stmt = $db->prepare("
                UPDATE overtime_records SET
                    overtime_hours = ?,
                    overtime_amount = ?,
                    remarks = ?,
                    updated_by = ?,
                    updated_at = NOW()
                WHERE overtime_id = ? AND site_id = ?
            ");
            $stmt->execute([
                $formData['overtime_hours'],
                $otAmount,
                $formData['remarks'],
                getCurrentUserId(),
                $overtimeId,
                $siteId
            ]);
            
            $db->commit();
            
            logAudit('UPDATE', 'overtime_records', $overtimeId);
            
            redirect(BASE_URL . '/modules/overtime/list.php?month=' . $overtime['month'] . '&year=' . $overtime['year'], 'Overtime record updated successfully.');
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error updating overtime: " . $e->getMessage());
            $errors[] = 'An error occurred while updating overtime record. Please try again.';
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Edit Overtime Record</h2>
        <a href="<?php echo BASE_URL; ?>/modules/overtime/list.php?month=<?php echo $overtime['month']; ?>&year=<?php echo $overtime['year']; ?>" 
           class="btn btn-secondary">Back to Overtime</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">Employee</label>
                <input type="text" class="form-control" value="<?php echo htmlspecialchars($formData['employee_code'] ?? 'N/A'); ?>" disabled>
            </div>
            
            <div class="form-group">
                <label class="form-label">Date</label>
                <input type="text" class="form-control" value="<?php echo formatDate($formData['overtime_date']); ?>" disabled>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="overtime_hours">Overtime Hours *</label>
                <input type="number" id="overtime_hours" name="overtime_hours" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['overtime_hours'] ?? ''); ?>"
                       min="0.5" max="24" step="0.5">
            </div>
            
            <div class="form-group">
                <label class="form-label">OT Rate (per hour)</label>
                <input type="text" class="form-control" value="<?php echo formatCurrency($formData['overtime_rate']); ?>" disabled>
            </div>
            
            <div class="form-group" style="grid-column: 1 / -1;">
                <label class="form-label" for="remarks">Remarks</label>
                <textarea id="remarks" name="remarks" class="form-control" rows="3"><?php echo htmlspecialchars($formData['remarks'] ?? ''); ?></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/overtime/list.php?month=<?php echo $overtime['month']; ?>&year=<?php echo $overtime['year']; ?>" 
               class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Update Overtime Record</button>
        </div>
    </form>
</div>

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

