<?php
/**
 * Enterprise HRM ERP System - Apply for Leave
 */

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

$pageTitle = 'Apply for Leave';
$currentModule = 'leave';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'employee_id' => isset($_POST['employee_id']) ? (int)$_POST['employee_id'] : 0,
        'leave_type_id' => isset($_POST['leave_type_id']) ? (int)$_POST['leave_type_id'] : 0,
        'start_date' => $_POST['start_date'] ?? '',
        'end_date' => $_POST['end_date'] ?? '',
        'reason' => sanitize($_POST['reason'] ?? ''),
    ];
    
    // Validation
    if (empty($formData['employee_id'])) {
        $errors[] = 'Please select an employee.';
    }
    
    if (empty($formData['leave_type_id'])) {
        $errors[] = 'Please select leave type.';
    }
    
    if (empty($formData['start_date']) || empty($formData['end_date'])) {
        $errors[] = 'Start date and end date are required.';
    }
    
    if (!empty($formData['start_date']) && !empty($formData['end_date'])) {
        if ($formData['start_date'] > $formData['end_date']) {
            $errors[] = 'End date must be after start date.';
        }
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $userId = getCurrentUserId();
            
            // Calculate total days
            $totalDays = calculateDays($formData['start_date'], $formData['end_date']);
            
            $sql = "
                INSERT INTO leave_applications (
                    site_id, employee_id, leave_type_id, start_date, end_date,
                    total_days, reason, application_status, applied_by
                ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?)
            ";
            
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $siteId,
                $formData['employee_id'],
                $formData['leave_type_id'],
                $formData['start_date'],
                $formData['end_date'],
                $totalDays,
                $formData['reason'] ?: null,
                $userId
            ]);
            
            redirect(BASE_URL . '/modules/leave/list.php', 'Leave application submitted successfully.');
            
        } catch (Exception $e) {
            error_log("Error creating leave application: " . $e->getMessage());
            $errors[] = 'An error occurred while submitting leave application. Please try again.';
        }
    }
}

// Get employees and leave types
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT employee_id, employee_code, 
               CONCAT(first_name, ' ', COALESCE(middle_name, ''), ' ', last_name) as full_name
        FROM employees 
        WHERE site_id = ? AND employment_status = 'active'
        ORDER BY employee_code
    ");
    $stmt->execute([$siteId]);
    $employees = $stmt->fetchAll();
    
    $stmt = $db->prepare("
        SELECT leave_type_id, leave_type_name, max_days_per_year
        FROM leave_types 
        WHERE site_id = ? AND leave_type_status = 'active'
        ORDER BY leave_type_name
    ");
    $stmt->execute([$siteId]);
    $leaveTypes = $stmt->fetchAll();
} catch (Exception $e) {
    error_log("Error loading data: " . $e->getMessage());
    $employees = [];
    $leaveTypes = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Apply for Leave</h2>
        <a href="<?php echo BASE_URL; ?>/modules/leave/list.php" class="btn btn-secondary">Back to List</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" id="leaveForm">
        <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'] . ' - ' . $emp['full_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="leave_type_id">Leave Type *</label>
                <select id="leave_type_id" name="leave_type_id" class="form-control" required>
                    <option value="">Select Leave Type</option>
                    <?php foreach ($leaveTypes as $type): ?>
                    <option value="<?php echo $type['leave_type_id']; ?>" 
                            <?php echo ($formData['leave_type_id'] ?? 0) == $type['leave_type_id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($type['leave_type_name']); ?>
                        <?php if ($type['max_days_per_year'] > 0): ?>
                            (Max: <?php echo $type['max_days_per_year']; ?> days/year)
                        <?php endif; ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="start_date">Start Date *</label>
                <input type="date" id="start_date" name="start_date" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['start_date'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="end_date">End Date *</label>
                <input type="date" id="end_date" name="end_date" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['end_date'] ?? ''); ?>">
            </div>
            
            <div class="form-group" style="grid-column: 1 / -1;">
                <label class="form-label" for="reason">Reason</label>
                <textarea id="reason" name="reason" class="form-control" rows="4"><?php echo htmlspecialchars($formData['reason'] ?? ''); ?></textarea>
            </div>
        </div>
        
        <div style="margin-top: 30px; text-align: right;">
            <a href="<?php echo BASE_URL; ?>/modules/leave/list.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Submit Leave Application</button>
        </div>
    </form>
</div>

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

