<?php
/**
 * Enterprise HRM ERP System - Create Fortnight Period
 * Excel-like Period Creation with Month/Year and Fortnight Options
 */

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

$pageTitle = 'Create Fortnight Period';
$currentModule = 'fortnight';

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

// Validate
if ($selectedMonth < 1 || $selectedMonth > 12) $selectedMonth = (int)date('m');
if ($selectedYear < 2020 || $selectedYear > 2100) $selectedYear = (int)date('Y');

$errors = [];
$success = false;

// Handle period creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_period'])) {
    try {
        $db = getDB();
        $db->beginTransaction();
        
        $periodType = $_POST['period_type'] ?? 'fortnight';
        $startDate = $_POST['start_date'] ?? '';
        $endDate = $_POST['end_date'] ?? '';
        $periodName = $_POST['period_name'] ?? '';
        
        if (empty($startDate) || empty($endDate)) {
            throw new Exception('Start date and end date are required.');
        }
        
        $startDateObj = new DateTime($startDate);
        $endDateObj = new DateTime($endDate);
        
        if ($endDateObj < $startDateObj) {
            throw new Exception('End date must be after start date.');
        }
        
        // Calculate month and year from start date
        $month = (int)$startDateObj->format('m');
        $year = (int)$startDateObj->format('Y');
        
        // Check if period already exists for this date range
        $stmt = $db->prepare("
            SELECT period_id FROM fortnight_periods 
            WHERE site_id = ? AND (
                (date <= ? AND period_date >= ?) OR
                (date <= ? AND period_date >= ?) OR
                (date >= ? AND period_date <= ?)
            )
        ");
        $stmt->execute([$siteId, $startDate, $startDate, $endDate, $endDate, $startDate, $endDate]);
        $existing = $stmt->fetch();
        
        if ($existing) {
            throw new Exception('A period already exists for this date range.');
        }
        
        // Generate period name if not provided
        if (empty($periodName)) {
            if ($periodType === 'fortnight') {
                $periodName = 'Fortnight: ' . $startDateObj->format('d-M-y') . ' to ' . $endDateObj->format('d-M-y');
            } else {
                $periodName = $startDateObj->format('F Y');
            }
        }
        
        // Insert period
        $stmt = $db->prepare("
            INSERT INTO fortnight_periods (period_name, date, period_date, month, year, site_id)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$periodName, $startDate, $endDate, $month, $year, $siteId]);
        
        $periodId = $db->lastInsertId();
        
        $db->commit();
        $success = true;
        logAudit('CREATE', 'fortnight_periods', $periodId);
        
        // Redirect to list with new period
        header("Location: " . BASE_URL . "/modules/fortnight/list.php?period_id={$periodId}&month={$month}&year={$year}&created=1");
        exit;
        
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        error_log("Error creating period: " . $e->getMessage());
        $errors[] = $e->getMessage();
    }
}

// Get existing periods for the month to show what's already created
$existingPeriods = [];
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT *, date as start_date, period_date as end_date FROM fortnight_periods
        WHERE site_id = ? AND month = ? AND year = ?
        ORDER BY date ASC
    ");
    $stmt->execute([$siteId, $selectedMonth, $selectedYear]);
    $existingPeriods = $stmt->fetchAll();
} catch (Exception $e) {
    error_log("Error fetching periods: " . $e->getMessage());
}

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

<style>
.card {
    max-width: 800px;
    margin: 20px auto;
}

.form-group {
    margin-bottom: 20px;
}

.form-label {
    display: block;
    margin-bottom: 8px;
    font-weight: bold;
    color: #333;
}

.form-control {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

.period-type-selector {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
}

.period-type-option {
    flex: 1;
    padding: 15px;
    border: 2px solid #ddd;
    border-radius: 8px;
    cursor: pointer;
    text-align: center;
    transition: all 0.3s;
}

.period-type-option:hover {
    border-color: #4a90e2;
    background: #f0f7ff;
}

.period-type-option.active {
    border-color: #4a90e2;
    background: #e3f2fd;
    font-weight: bold;
}

.date-range-preview {
    margin-top: 15px;
    padding: 15px;
    background: #f0f7ff;
    border-left: 4px solid #4a90e2;
    border-radius: 4px;
}

.existing-periods {
    margin-top: 30px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
}

.existing-periods h3 {
    margin-top: 0;
    margin-bottom: 15px;
}

.period-item {
    padding: 10px;
    margin-bottom: 8px;
    background: white;
    border: 1px solid #ddd;
    border-radius: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.period-item.locked {
    background: #fff3cd;
    border-color: #ffc107;
}
</style>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Create Fortnight Period</h2>
        <a href="<?php echo BASE_URL; ?>/modules/fortnight/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
           class="btn btn-secondary">Back to List</a>
    </div>
    
    <div class="card-body">
        <?php if ($success): ?>
        <div class="alert alert-success">
            Period created successfully!
        </div>
        <?php endif; ?>
        
        <?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; ?>
        
        <!-- Month/Year Selector -->
        <div style="display: flex; gap: 15px; margin-bottom: 30px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
            <div class="form-group" style="flex: 1; margin-bottom: 0;">
                <label class="form-label">Month</label>
                <select id="monthSelect" class="form-control" onchange="updateMonthYear()">
                    <?php for ($m = 1; $m <= 12; $m++): ?>
                    <option value="<?php echo $m; ?>" <?php echo $selectedMonth == $m ? 'selected' : ''; ?>>
                        <?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>
                    </option>
                    <?php endfor; ?>
                </select>
            </div>
            <div class="form-group" style="flex: 1; margin-bottom: 0;">
                <label class="form-label">Year</label>
                <select id="yearSelect" class="form-control" onchange="updateMonthYear()">
                    <?php for ($y = date('Y') - 5; $y <= date('Y') + 5; $y++): ?>
                    <option value="<?php echo $y; ?>" <?php echo $selectedYear == $y ? 'selected' : ''; ?>>
                        <?php echo $y; ?>
                    </option>
                    <?php endfor; ?>
                </select>
            </div>
        </div>
        
        <form method="POST" id="createPeriodForm">
            <input type="hidden" name="create_period" value="1">
            <input type="hidden" name="period_type" id="periodType" value="<?php echo htmlspecialchars($periodType); ?>">
            
            <!-- Period Type Selector -->
            <div class="period-type-selector">
                <div class="period-type-option <?php echo $periodType === 'fortnight' ? 'active' : ''; ?>" 
                     onclick="selectPeriodType('fortnight')">
                    <h3 style="margin: 0 0 10px 0;">📅 Fortnight (14 Days)</h3>
                    <p style="margin: 0; color: #666; font-size: 14px;">Create a 14-day period</p>
                </div>
                <div class="period-type-option <?php echo $periodType === 'month' ? 'active' : ''; ?>" 
                     onclick="selectPeriodType('month')">
                    <h3 style="margin: 0 0 10px 0;">📆 Full Month</h3>
                    <p style="margin: 0; color: #666; font-size: 14px;">Create a full month period</p>
                </div>
            </div>
            
            <!-- Period Name -->
            <div class="form-group">
                <label class="form-label">Period Name (Optional - Auto-generated if empty)</label>
                <input type="text" name="period_name" class="form-control" id="periodName" 
                       placeholder="Leave empty for auto-generation">
            </div>
            
            <!-- Date Range -->
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                <div class="form-group">
                    <label class="form-label">Start Date *</label>
                    <input type="date" name="start_date" id="startDate" class="form-control" 
                           value="<?php echo date('Y-m-d'); ?>" required onchange="updateDateRange()">
                </div>
                <div class="form-group">
                    <label class="form-label">End Date *</label>
                    <input type="date" name="end_date" id="endDate" class="form-control" 
                           value="<?php echo date('Y-m-d', strtotime('+13 days')); ?>" required onchange="updateDateRange()">
                </div>
            </div>
            
            <!-- Quick Options -->
            <div style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                <label class="form-label" style="margin-bottom: 10px;">Quick Options:</label>
                <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                    <button type="button" class="btn btn-sm btn-secondary" onclick="setFirstFortnight()">
                        First Fortnight (1-15)
                    </button>
                    <button type="button" class="btn btn-sm btn-secondary" onclick="setSecondFortnight()">
                        Second Fortnight (16-31)
                    </button>
                    <button type="button" class="btn btn-sm btn-secondary" onclick="setFullMonth()">
                        Full Month
                    </button>
                    <button type="button" class="btn btn-sm btn-secondary" onclick="setCurrentFortnight()">
                        Current Fortnight
                    </button>
                </div>
            </div>
            
            <!-- Date Range Preview -->
            <div class="date-range-preview" id="datePreview" style="display: none;">
                <strong>Period Preview:</strong>
                <div id="previewText" style="margin-top: 5px;"></div>
            </div>
            
            <div style="margin-top: 30px; display: flex; gap: 10px;">
                <button type="submit" class="btn btn-primary">Create Period</button>
                <a href="<?php echo BASE_URL; ?>/modules/fortnight/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
                   class="btn btn-secondary">Cancel</a>
            </div>
        </form>
        
        <!-- Existing Periods -->
        <?php if (!empty($existingPeriods)): ?>
        <div class="existing-periods">
            <h3>Existing Periods for <?php echo date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?></h3>
            <?php foreach ($existingPeriods as $p): ?>
            <div class="period-item <?php echo $p['is_locked'] ? 'locked' : ''; ?>">
                <div>
                    <strong><?php echo htmlspecialchars($p['period_name']); ?></strong>
                    <div style="font-size: 12px; color: #666; margin-top: 5px;">
                        <?php echo date('d-M-y', strtotime($p['start_date'])); ?> to 
                        <?php echo date('d-M-y', strtotime($p['end_date'])); ?>
                        <?php if ($p['is_locked']): ?>
                        <span style="margin-left: 10px; color: #ff9800;">🔒 Locked</span>
                        <?php endif; ?>
                    </div>
                </div>
                <a href="<?php echo BASE_URL; ?>/modules/fortnight/list.php?period_id=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
                   class="btn btn-sm btn-primary">View</a>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
function selectPeriodType(type) {
    document.getElementById('periodType').value = type;
    document.querySelectorAll('.period-type-option').forEach(el => el.classList.remove('active'));
    event.target.closest('.period-type-option').classList.add('active');
    updateDateRange();
}

function updateMonthYear() {
    const month = document.getElementById('monthSelect').value;
    const year = document.getElementById('yearSelect').value;
    window.location.href = '?month=' + month + '&year=' + year + '&type=' + document.getElementById('periodType').value;
}

function updateDateRange() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    const preview = document.getElementById('datePreview');
    const previewText = document.getElementById('previewText');
    
    if (startDate && endDate) {
        const start = new Date(startDate);
        const end = new Date(endDate);
        const days = Math.ceil((end - start) / (1000 * 60 * 60 * 24)) + 1;
        
        previewText.innerHTML = `
            <strong>${formatDate(start)}</strong> to <strong>${formatDate(end)}</strong><br>
            <span style="color: #666;">Duration: ${days} day${days !== 1 ? 's' : ''}</span>
        `;
        preview.style.display = 'block';
    } else {
        preview.style.display = 'none';
    }
}

function formatDate(date) {
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    return date.getDate() + '-' + months[date.getMonth()] + '-' + date.getFullYear().toString().slice(-2);
}

function setFirstFortnight() {
    const month = parseInt(document.getElementById('monthSelect').value);
    const year = parseInt(document.getElementById('yearSelect').value);
    const startDate = new Date(year, month - 1, 1);
    const endDate = new Date(year, month - 1, 15);
    
    document.getElementById('startDate').value = formatDateInput(startDate);
    document.getElementById('endDate').value = formatDateInput(endDate);
    document.getElementById('periodType').value = 'fortnight';
    updateDateRange();
}

function setSecondFortnight() {
    const month = parseInt(document.getElementById('monthSelect').value);
    const year = parseInt(document.getElementById('yearSelect').value);
    const startDate = new Date(year, month - 1, 16);
    const endDate = new Date(year, month, 0); // Last day of month
    
    document.getElementById('startDate').value = formatDateInput(startDate);
    document.getElementById('endDate').value = formatDateInput(endDate);
    document.getElementById('periodType').value = 'fortnight';
    updateDateRange();
}

function setFullMonth() {
    const month = parseInt(document.getElementById('monthSelect').value);
    const year = parseInt(document.getElementById('yearSelect').value);
    const startDate = new Date(year, month - 1, 1);
    const endDate = new Date(year, month, 0); // Last day of month
    
    document.getElementById('startDate').value = formatDateInput(startDate);
    document.getElementById('endDate').value = formatDateInput(endDate);
    document.getElementById('periodType').value = 'month';
    updateDateRange();
}

function setCurrentFortnight() {
    const today = new Date();
    const day = today.getDate();
    let startDate, endDate;
    
    if (day <= 15) {
        startDate = new Date(today.getFullYear(), today.getMonth(), 1);
        endDate = new Date(today.getFullYear(), today.getMonth(), 15);
    } else {
        startDate = new Date(today.getFullYear(), today.getMonth(), 16);
        endDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    }
    
    document.getElementById('startDate').value = formatDateInput(startDate);
    document.getElementById('endDate').value = formatDateInput(endDate);
    document.getElementById('periodType').value = 'fortnight';
    updateDateRange();
}

function formatDateInput(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

// Initialize
document.addEventListener('DOMContentLoaded', function() {
    updateDateRange();
});
</script>

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