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

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

$pageTitle = 'Add SSA Record';
$currentModule = 'dfc';

$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('dfc', $siteId, $selectedMonth, $selectedYear);
if ($isLocked && !hasAdminAccess()) {
    requireUnlocked('dfc', $siteId, $selectedMonth, $selectedYear);
}

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

// Get benchmark from settings
$benchmarkPercent = getSetting('DFC_BENCHMARK_PERCENT', 30);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'dfc_date' => $_POST['dfc_date'] ?? '',
        'catering_btc_sale' => isset($_POST['catering_btc_sale']) ? (float)$_POST['catering_btc_sale'] : 0,
        'total_sale' => isset($_POST['total_sale']) ? (float)$_POST['total_sale'] : 0,
        'food_cost' => isset($_POST['food_cost']) ? (float)$_POST['food_cost'] : 0,
        'manpower_cost' => isset($_POST['manpower_cost']) ? (float)$_POST['manpower_cost'] : 0,
        'cylinder_cost' => isset($_POST['cylinder_cost']) ? (float)$_POST['cylinder_cost'] : 0,
    ];
    
    // Validation
    if (empty($formData['dfc_date'])) {
        $errors[] = 'DFC date is required.';
    }
    
    if ($formData['total_sale'] <= 0) {
        $errors[] = 'Total sale must be greater than 0.';
    }
    
    if (empty($errors)) {
        // Auto-calculate percentages and variation
        $foodCostPercent = $formData['total_sale'] > 0 ? ($formData['food_cost'] / $formData['total_sale']) * 100 : 0;
        $manpowerCostPercent = $formData['total_sale'] > 0 ? ($formData['manpower_cost'] / $formData['total_sale']) * 100 : 0;
        $cylinderCostPercent = $formData['total_sale'] > 0 ? ($formData['cylinder_cost'] / $formData['total_sale']) * 100 : 0;
        
        // Calculate variation (positive = over budget, negative = under budget)
        $expectedFoodCost = ($formData['total_sale'] * $benchmarkPercent) / 100;
        $variationAmount = $formData['food_cost'] - $expectedFoodCost;
        $variationType = $variationAmount >= 0 ? 'positive' : 'negative';
        
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Check if record already exists
            $stmt = $db->prepare("SELECT dfc_id FROM dfc_records WHERE site_id = ? AND dfc_date = ?");
            $stmt->execute([$siteId, $formData['dfc_date']]);
            if ($stmt->fetch()) {
                $errors[] = 'DFC record already exists for this date.';
                $db->rollBack();
            } else {
                $month = (int)date('m', strtotime($formData['dfc_date']));
                $year = (int)date('Y', strtotime($formData['dfc_date']));
                
                // Insert DFC record
                $stmt = $db->prepare("
                    INSERT INTO dfc_records (
                        site_id, dfc_date, catering_btc_sale, total_sale,
                        food_cost, food_cost_percent,
                        manpower_cost, manpower_cost_percent,
                        cylinder_cost, cylinder_cost_percent,
                        benchmark_percent, variation_amount, variation_type,
                        month, year, created_by
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $siteId,
                    $formData['dfc_date'],
                    $formData['catering_btc_sale'],
                    $formData['total_sale'],
                    $formData['food_cost'],
                    $foodCostPercent,
                    $formData['manpower_cost'],
                    $manpowerCostPercent,
                    $formData['cylinder_cost'],
                    $cylinderCostPercent,
                    $benchmarkPercent,
                    abs($variationAmount),
                    $variationType,
                    $month,
                    $year,
                    getCurrentUserId()
                ]);
                
                $db->commit();
                
                logAudit('CREATE', 'dfc_records', $db->lastInsertId());
                
                redirect(BASE_URL . '/modules/dfc/list.php?month=' . $month . '&year=' . $year, 'DFC record created successfully.');
            }
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error creating DFC: " . $e->getMessage());
            $errors[] = 'An error occurred while creating DFC record. Please try again.';
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Add DFC Record</h2>
        <a href="<?php echo BASE_URL; ?>/modules/dfc/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
           class="btn btn-secondary">Back to DFC</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="dfc_date">DFC Date *</label>
                <input type="date" id="dfc_date" name="dfc_date" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['dfc_date'] ?? date('Y-m-d')); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="catering_btc_sale">Catering BTC Sale</label>
                <input type="number" id="catering_btc_sale" name="catering_btc_sale" class="form-control"
                       value="<?php echo htmlspecialchars($formData['catering_btc_sale'] ?? '0'); ?>"
                       min="0" step="0.01" onchange="calculateDFC()">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="total_sale">Total Sale *</label>
                <input type="number" id="total_sale" name="total_sale" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['total_sale'] ?? '0'); ?>"
                       min="0.01" step="0.01" onchange="calculateDFC()">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="food_cost">Food Cost *</label>
                <input type="number" id="food_cost" name="food_cost" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['food_cost'] ?? '0'); ?>"
                       min="0" step="0.01" onchange="calculateDFC()">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="manpower_cost">Manpower Cost</label>
                <input type="number" id="manpower_cost" name="manpower_cost" class="form-control"
                       value="<?php echo htmlspecialchars($formData['manpower_cost'] ?? '0'); ?>"
                       min="0" step="0.01" onchange="calculateDFC()">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="cylinder_cost">Cylinder Cost</label>
                <input type="number" id="cylinder_cost" name="cylinder_cost" class="form-control"
                       value="<?php echo htmlspecialchars($formData['cylinder_cost'] ?? '0'); ?>"
                       min="0" step="0.01" onchange="calculateDFC()">
            </div>
        </div>
        
        <!-- Auto-calculated values -->
        <div style="margin-top: 30px; padding: 20px; background: #f9fafb; border-radius: 8px;">
            <h3 style="margin-bottom: 15px;">Auto-Calculated Values</h3>
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px;">
                <div>
                    <label class="form-label">Food Cost %</label>
                    <div id="food_cost_percent" style="padding: 10px; background: white; border: 1px solid var(--border-color); border-radius: 6px; font-weight: 600;">
                        0.00%
                    </div>
                </div>
                <div>
                    <label class="form-label">Benchmark %</label>
                    <div style="padding: 10px; background: white; border: 1px solid var(--border-color); border-radius: 6px; font-weight: 600;">
                        <?php echo number_format($benchmarkPercent, 2); ?>%
                    </div>
                </div>
                <div>
                    <label class="form-label">Variation</label>
                    <div id="variation_amount" style="padding: 10px; background: white; border: 1px solid var(--border-color); border-radius: 6px; font-weight: 600;">
                        ₹0.00
                    </div>
                </div>
            </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/dfc/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
               class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Create DFC Record</button>
        </div>
    </form>
</div>

<script>
function calculateDFC() {
    const totalSale = parseFloat(document.getElementById('total_sale').value) || 0;
    const foodCost = parseFloat(document.getElementById('food_cost').value) || 0;
    const benchmarkPercent = <?php echo $benchmarkPercent; ?>;
    
    if (totalSale > 0) {
        const foodCostPercent = (foodCost / totalSale) * 100;
        document.getElementById('food_cost_percent').textContent = foodCostPercent.toFixed(2) + '%';
        document.getElementById('food_cost_percent').style.color = foodCostPercent > benchmarkPercent ? '#ef4444' : '#10b981';
        
        const expectedFoodCost = (totalSale * benchmarkPercent) / 100;
        const variation = foodCost - expectedFoodCost;
        const variationEl = document.getElementById('variation_amount');
        variationEl.textContent = (variation >= 0 ? '+' : '-') + '₹' + Math.abs(variation).toFixed(2);
        variationEl.style.color = variation >= 0 ? '#ef4444' : '#10b981';
    } else {
        document.getElementById('food_cost_percent').textContent = '0.00%';
        document.getElementById('variation_amount').textContent = '₹0.00';
    }
}

// Initialize
calculateDFC();
</script>

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

