<?php
/**
 * Enterprise HRM ERP System - DFC Fix Column Count Mismatch
 * This script checks actual table structure and fixes INSERT statement mismatch
 */

require_once __DIR__ . '/../../includes/init.php';

if (!hasAdminAccess()) {
    die('Access denied. Admin privileges required.');
}

$db = getDB();
$dbname = $db->query("SELECT DATABASE()")->fetchColumn();

// Get actual columns from table
$stmt = $db->prepare("
    SELECT COLUMN_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'dfc_entries'
    AND COLUMN_NAME NOT IN ('entry_id', 'created_at', 'updated_at')
    ORDER BY ORDINAL_POSITION
");
$stmt->execute([$dbname]);
$actualColumns = $stmt->fetchAll(PDO::FETCH_COLUMN);

// Expected columns from INSERT statement
$expectedColumns = [
    'period_id', 'entry_date', 'cash_sale_net', 'catering_btc_regular', 'catering_btc_extra',
    'total_food_sale', 'housekeeping_lumpsum', 'laundry', 'total_sale',
    'cash_purchase', 'catering_cost', 'total_food_cost', 'food_cost_percent',
    'housekeeping_cost', 'housekeeping_cost_percent', 'manpower_days', 'manpower_cost',
    'manpower_cost_percent', 'manpower_cost_per_sale', 'odc_cost', 'odc_cost_2', 'cylinder_quantity',
    'cylinder_rate', 'total_cylinder_cost', 'cylinder_cost_percent', 'cylinder_cost_per_sale',
    'expected_food_cost', 'variation_amount', 'variation_type', 'additional_cost', 'total_cost', 'sr_no'
];

echo "Expected columns (32): " . count($expectedColumns) . "\n";
echo "Actual columns: " . count($actualColumns) . "\n\n";

echo "Expected: " . implode(', ', $expectedColumns) . "\n\n";
echo "Actual: " . implode(', ', $actualColumns) . "\n\n";

$missing = array_diff($expectedColumns, $actualColumns);
$extra = array_diff($actualColumns, $expectedColumns);

if (!empty($missing)) {
    echo "MISSING: " . implode(', ', $missing) . "\n";
}

if (!empty($extra)) {
    echo "EXTRA (should be removed): " . implode(', ', $extra) . "\n";
}

if (in_array('credit_sale', $extra)) {
    echo "\n=== FIXING: Removing credit_sale column ===\n";
    try {
        $db->exec("ALTER TABLE dfc_entries DROP COLUMN credit_sale");
        echo "✓ Removed credit_sale column\n";
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage() . "\n";
    }
}

echo "\n=== DONE ===\n";
