<?php
/**
 * Enterprise HRM ERP System - Create Payroll Period
 */

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

$pageTitle = 'Create Payroll Period';
$currentModule = 'payroll';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'period_code' => sanitize($_POST['period_code'] ?? ''),
        'period_name' => sanitize($_POST['period_name'] ?? ''),
        'start_date' => $_POST['start_date'] ?? '',
        'end_date' => $_POST['end_date'] ?? '',
        'pay_date' => $_POST['pay_date'] ?? '',
    ];
    
    // Validation
    if (empty($formData['period_name'])) {
        $errors[] = 'Period name is required.';
    }
    
    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($formData['pay_date'])) {
        $errors[] = 'Pay date is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $userId = getCurrentUserId();
            
            // Generate period code if not provided
            if (empty($formData['period_code'])) {
                $year = date('Y', strtotime($formData['start_date']));
                $month = date('m', strtotime($formData['start_date']));
                $formData['period_code'] = "PAY{$year}{$month}";
            }
            
            $sql = "
                INSERT INTO payroll_periods (
                    site_id, period_code, period_name, start_date, end_date, pay_date, period_status, created_by
                ) VALUES (?, ?, ?, ?, ?, ?, 'draft', ?)
            ";
            
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $siteId,
                $formData['period_code'],
                $formData['period_name'],
                $formData['start_date'],
                $formData['end_date'],
                $formData['pay_date'],
                $userId
            ]);
            
            redirect(BASE_URL . '/modules/payroll/list.php', 'Payroll period created successfully.');
            
        } catch (Exception $e) {
            error_log("Error creating payroll period: " . $e->getMessage());
            $errors[] = 'An error occurred while creating payroll period. Please try again.';
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Create Payroll Period</h2>
        <a href="<?php echo BASE_URL; ?>/modules/payroll/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="payrollForm">
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
            <div class="form-group">
                <label class="form-label" for="period_code">Period Code</label>
                <input type="text" id="period_code" name="period_code" class="form-control"
                       value="<?php echo htmlspecialchars($formData['period_code'] ?? ''); ?>"
                       placeholder="Auto-generated if left empty">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="period_name">Period Name *</label>
                <input type="text" id="period_name" name="period_name" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['period_name'] ?? ''); ?>"
                       placeholder="e.g., January 2024">
            </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">
                <label class="form-label" for="pay_date">Pay Date *</label>
                <input type="date" id="pay_date" name="pay_date" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['pay_date'] ?? ''); ?>">
            </div>
        </div>
        
        <div style="margin-top: 30px; text-align: right;">
            <a href="<?php echo BASE_URL; ?>/modules/payroll/list.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Create Payroll Period</button>
        </div>
    </form>
</div>

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

