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

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

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

$siteId = getCurrentSiteId();
$selectedMonth = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$selectedYear = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');

// Check if locked
$isLocked = isDataLocked('overtime', $siteId, $selectedMonth, $selectedYear);
if ($isLocked && !hasAdminAccess()) {
    requireUnlocked('overtime', $siteId, $selectedMonth, $selectedYear);
}

$errors = [];
$formData = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'employee_id' => isset($_POST['employee_id']) ? (int)$_POST['employee_id'] : 0,
        'overtime_date' => $_POST['overtime_date'] ?? '',
        'overtime_hours' => isset($_POST['overtime_hours']) ? (float)$_POST['overtime_hours'] : 0,
        'remarks' => sanitize($_POST['remarks'] ?? ''),
    ];
    
    // Validation
    if ($formData['employee_id'] <= 0) {
        $errors[] = 'Please select an employee.';
    }
    
    if (empty($formData['overtime_date'])) {
        $errors[] = 'Overtime date is required.';
    }
    
    if ($formData['overtime_hours'] <= 0) {
        $errors[] = 'Overtime hours must be greater than 0.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Check if record already exists
            $stmt = $db->prepare("SELECT overtime_id FROM overtime_records WHERE employee_id = ? AND overtime_date = ?");
            $stmt->execute([$formData['employee_id'], $formData['overtime_date']]);
            if ($stmt->fetch()) {
                $errors[] = 'Overtime record already exists for this employee on this date.';
                $db->rollBack();
            } else {
                // Get employee's basic salary for OT calculation
                $stmt = $db->prepare("
                    SELECT ess.amount 
                    FROM employee_salary_structure ess
                    INNER JOIN salary_components sc ON ess.component_id = sc.component_id
                    WHERE ess.employee_id = ? AND sc.component_code = 'BASIC' 
                    AND ess.structure_status = 'active'
                    ORDER BY ess.effective_from DESC LIMIT 1
                ");
                $stmt->execute([$formData['employee_id']]);
                $basicSalary = $stmt->fetchColumn();
                
                if (!$basicSalary) {
                    $basicSalary = 0;
                }
                
                // Get OT rate
                $stmt = $db->prepare("
                    SELECT rate_multiplier FROM overtime_rates
                    WHERE site_id = ? AND is_active = 1 AND effective_from <= CURDATE()
                    AND (effective_to IS NULL OR effective_to >= CURDATE())
                    ORDER BY effective_from DESC LIMIT 1
                ");
                $stmt->execute([$siteId]);
                $otRate = $stmt->fetch();
                $otMultiplier = $otRate ? $otRate['rate_multiplier'] : getSetting('OVERTIME_RATE', 1.5);
                
                // Calculate OT rate per hour (Basic Salary / (Working Days * Working Hours))
                $workingDays = getSetting('WORKING_DAYS_PER_WEEK', 5) * 4; // Approximate monthly
                $workingHours = getSetting('WORKING_HOURS_PER_DAY', 8);
                $hourlyRate = $basicSalary / ($workingDays * $workingHours);
                $otRatePerHour = $hourlyRate * $otMultiplier;
                $otAmount = $formData['overtime_hours'] * $otRatePerHour;
                
                $month = (int)date('m', strtotime($formData['overtime_date']));
                $year = (int)date('Y', strtotime($formData['overtime_date']));
                
                // Insert overtime record
                $stmt = $db->prepare("
                    INSERT INTO overtime_records (
                        site_id, employee_id, overtime_date, overtime_hours,
                        overtime_rate, overtime_amount, remarks, month, year, created_by
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $siteId,
                    $formData['employee_id'],
                    $formData['overtime_date'],
                    $formData['overtime_hours'],
                    $otRatePerHour,
                    $otAmount,
                    $formData['remarks'],
                    $month,
                    $year,
                    getCurrentUserId()
                ]);
                
                $db->commit();
                
                logAudit('CREATE', 'overtime_records', $db->lastInsertId());
                
                redirect(BASE_URL . '/modules/overtime/list.php?month=' . $month . '&year=' . $year, 'Overtime record created successfully.');
            }
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error creating overtime: " . $e->getMessage());
            $errors[] = 'An error occurred while creating overtime record. Please try again.';
        }
    }
}

// Get 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">Add Overtime Record</h2>
        <a href="<?php echo BASE_URL; ?>/modules/overtime/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
           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" 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 ($formData['employee_id'] ?? 0) == $emp['employee_id'] ? 'selected' : ''; ?>>
                        <?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="overtime_date">Overtime Date *</label>
                <input type="date" id="overtime_date" name="overtime_date" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['overtime_date'] ?? date('Y-m-d')); ?>">
            </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">
                <small style="color: var(--text-secondary);">Enter hours (e.g., 2.5 for 2 hours 30 minutes)</small>
            </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"
                          placeholder="Enter any remarks..."><?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 $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
               class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Create Overtime Record</button>
        </div>
    </form>
</div>

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

