<?php
// Include header
include('includes/header.php');

// Fetch cumulative salary data from salaries table for the current financial year (April to March)
$salariesQuery = "SELECT MONTHNAME(month) AS month, cum_salary, budget_salary FROM salaries WHERE month BETWEEN '2024-04-01' AND '2025-03-31'";
$salariesResult = mysqli_query($conn, $salariesQuery);

if (!$salariesResult) {
    die("Query failed: " . mysqli_error($conn));
}

$salariesData = [];
while ($row = mysqli_fetch_assoc($salariesResult)) {
    $salariesData[] = $row;
}

// Fetch cumulative fixed cost data from fixed_cost table for the current financial year (April to March)
$fixedCostQuery = "SELECT MONTHNAME(month) AS month, cum_fixed_cost, budget_fixed_cost FROM fixed_cost WHERE month BETWEEN '2024-04-01' AND '2025-03-31'";
$fixedCostResult = mysqli_query($conn, $fixedCostQuery);

if (!$fixedCostResult) {
    die("Query failed: " . mysqli_error($conn));
}

$fixedCostData = [];
while ($row = mysqli_fetch_assoc($fixedCostResult)) {
    $fixedCostData[] = $row;
}

// Fetch previous year actuals for salaries
$previousYearSalariesQuery = "SELECT MONTHNAME(month) AS month, cum_salary AS previous_year_actuals FROM salaries WHERE month BETWEEN '2023-04-01' AND '2024-03-31'";
$previousYearSalariesResult = mysqli_query($conn, $previousYearSalariesQuery);

if (!$previousYearSalariesResult) {
    die("Query failed: " . mysqli_error($conn));
}

$previousYearSalariesData = [];
while ($row = mysqli_fetch_assoc($previousYearSalariesResult)) {
    $previousYearSalariesData[$row['month']] = $row['previous_year_actuals'] / 100000; // Display in lakhs
}

// Fetch previous year actuals for fixed cost
$previousYearFixedCostQuery = "SELECT MONTHNAME(month) AS month, cum_fixed_cost AS previous_year_actuals FROM fixed_cost WHERE month BETWEEN '2023-04-01' AND '2024-03-31'";
$previousYearFixedCostResult = mysqli_query($conn, $previousYearFixedCostQuery);

if (!$previousYearFixedCostResult) {
    die("Query failed: " . mysqli_error($conn));
}

$previousYearFixedCostData = [];
while ($row = mysqli_fetch_assoc($previousYearFixedCostResult)) {
    $previousYearFixedCostData[$row['month']] = $row['previous_year_actuals'] / 100000; // Display in lakhs
}

// Merge data based on the month
$mergedData = [];
foreach ($salariesData as $salary) {
    $month = $salary['month'];
    $previousYearActuals = isset($previousYearSalariesData[$month]) ? $previousYearSalariesData[$month] : 0;
    $mergedData[$month] = [
        'month' => $month,
        'cum_salary' => $salary['cum_salary'] / 100000, // Display in lakhs
        'budget_salary' => $salary['budget_salary'] / 100000, // Display in lakhs
        'previous_year_actuals_salary' => $previousYearActuals,
        'cum_fixed_cost' => 0, // Default value for fixed cost, assuming it's not available for all months
        'budget_fixed_cost' => 0, // Default value for budget fixed cost
        'previous_year_actuals_fixed_cost' => 0 // Default value for previous year actuals fixed cost
    ];
}

foreach ($fixedCostData as $fixedCost) {
    $month = $fixedCost['month'];
    $previousYearActuals = isset($previousYearFixedCostData[$month]) ? $previousYearFixedCostData[$month] : 0;
    if (isset($mergedData[$month])) {
        $mergedData[$month]['cum_fixed_cost'] = $fixedCost['cum_fixed_cost'] / 100000; // Display in lakhs
        $mergedData[$month]['budget_fixed_cost'] = $fixedCost['budget_fixed_cost'] / 100000; // Display in lakhs
        $mergedData[$month]['previous_year_actuals_fixed_cost'] = $previousYearActuals; // Display in lakhs
    } else {
        $mergedData[$month] = [
            'month' => $month,
            'cum_salary' => 0, // Default value for salary, assuming it's not available for all months
            'budget_salary' => 0, // Default value for budget salary
            'previous_year_actuals_salary' => 0, // Default value for previous year actuals salary
            'cum_fixed_cost' => $fixedCost['cum_fixed_cost'] / 100000, // Display in lakhs
            'budget_fixed_cost' => $fixedCost['budget_fixed_cost'] / 100000, // Display in lakhs
            'previous_year_actuals_fixed_cost' => $previousYearActuals // Display in lakhs
        ];
    }
}

// Calculate totals
$totalCumSalary = $totalBudgetSalary = $totalPreviousYearActualsSalary = $totalCumFixedCost = $totalBudgetFixedCost = $totalPreviousYearActualsFixedCost = 0;

foreach ($mergedData as $monthData) {
    $totalCumSalary += $monthData['cum_salary'];
    $totalBudgetSalary += $monthData['budget_salary'];
    $totalPreviousYearActualsSalary += $monthData['previous_year_actuals_salary'];
    $totalCumFixedCost += $monthData['cum_fixed_cost'];
    $totalBudgetFixedCost += $monthData['budget_fixed_cost'];
    $totalPreviousYearActualsFixedCost += $monthData['previous_year_actuals_fixed_cost'];
}
?>

<?php
// Fetch the required data from the database (Salaries and Fixed Cost) as shown in your initial code...
// I assume the variables like $mergedData are already prepared and available.

// Table Rendering
?>

<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h4>Salaries and Fixed Costs</h4>
            </div>
            <div class="card-body">
                <table class="table table-bordered table-striped table-hover text-center table-responsive">
                    <thead class="align-middle text-center" style="background-color: #ccc;">
                        <tr class="align-middle text-center">
                            <th rowspan="2">Month</th>
                            <th colspan="2">Salaries (in Lakhs)</th>
                            <th colspan="2">Fixed Cost (in Lakhs)</th>
                        </tr>
                        <tr class="align-middle text-center">
                            <th>Actuals</th>
                            <th>Budgeted</th>
                            <th>Actuals</th>
                            <th>Budgeted</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($mergedData as $monthData): ?>
                            <tr class="align-middle text-center">
                                <!-- Month -->
                                <td><?= $monthData['month']; ?></td>

                                <!-- Salaries Actuals -->
                                <td>
                                    <span class="data" id="salary_actuals_<?= $monthData['month']; ?>"><?= number_format($monthData['cum_salary'], 2); ?></span>
                                    <input type="text" class="editField" id="input_salary_actuals_<?= $monthData['month']; ?>" value="<?= number_format($monthData['cum_salary'], 2); ?>" style="display:none;">
                                    
                                    <!-- Edit Button -->
                                    <button class="edit-btn" onclick="editData('salary_actuals', '<?= $monthData['month']; ?>')">
                                        <i class="fa fa-edit"></i>
                                    </button>

                                    <!-- Tick (Save) and Cross (Cancel) -->
                                    <button class="save-btn" id="save_salary_actuals_<?= $monthData['month']; ?>" style="display:none;" onclick="saveData('salary_actuals', '<?= $monthData['month']; ?>')">
                                        <i class="fa fa-check"></i>
                                    </button>
                                    <button class="cancel-btn" id="cancel_salary_actuals_<?= $monthData['month']; ?>" style="display:none;" onclick="cancelEdit('salary_actuals', '<?= $monthData['month']; ?>')">
                                        <i class="fa fa-times"></i>
                                    </button>
                                </td>

                                <!-- Salaries Budgeted -->
                                <td>
                                    <span class="data" id="salary_budgeted_<?= $monthData['month']; ?>"><?= number_format($monthData['budget_salary'], 2); ?></span>
                                    <input type="text" class="editField" id="input_salary_budgeted_<?= $monthData['month']; ?>" value="<?= number_format($monthData['budget_salary'], 2); ?>" style="display:none;">

                                    <!-- Edit Button -->
                                    <button class="edit-btn" onclick="editData('salary_budgeted', '<?= $monthData['month']; ?>')">
                                        <i class="fa fa-edit"></i>
                                    </button>

                                    <!-- Tick (Save) and Cross (Cancel) -->
                                    <button class="save-btn" id="save_salary_budgeted_<?= $monthData['month']; ?>" style="display:none;" onclick="saveData('salary_budgeted', '<?= $monthData['month']; ?>')">
                                        <i class="fa fa-check"></i>
                                    </button>
                                    <button class="cancel-btn" id="cancel_salary_budgeted_<?= $monthData['month']; ?>" style="display:none;" onclick="cancelEdit('salary_budgeted', '<?= $monthData['month']; ?>')">
                                        <i class="fa fa-times"></i>
                                    </button>
                                </td>

                                <!-- Fixed Cost Actuals -->
                                <td>
                                    <span class="data" id="fixed_actuals_<?= $monthData['month']; ?>"><?= number_format($monthData['cum_fixed_cost'], 2); ?></span>
                                    <input type="text" class="editField" id="input_fixed_actuals_<?= $monthData['month']; ?>" value="<?= number_format($monthData['cum_fixed_cost'], 2); ?>" style="display:none;">

                                    <!-- Edit Button -->
                                    <button class="edit-btn" onclick="editData('fixed_actuals', '<?= $monthData['month']; ?>')">
                                        <i class="fa fa-edit"></i>
                                    </button>

                                    <!-- Tick (Save) and Cross (Cancel) -->
                                    <button class="save-btn" id="save_fixed_actuals_<?= $monthData['month']; ?>" style="display:none;" onclick="saveData('fixed_actuals', '<?= $monthData['month']; ?>')">
                                        <i class="fa fa-check"></i>
                                    </button>
                                    <button class="cancel-btn" id="cancel_fixed_actuals_<?= $monthData['month']; ?>" style="display:none;" onclick="cancelEdit('fixed_actuals', '<?= $monthData['month']; ?>')">
                                        <i class="fa fa-times"></i>
                                    </button>
                                </td>

                                <!-- Fixed Cost Budgeted -->
                                <td>
                                    <span class="data" id="fixed_budgeted_<?= $monthData['month']; ?>"><?= number_format($monthData['budget_fixed_cost'], 2); ?></span>
                                    <input type="text" class="editField" id="input_fixed_budgeted_<?= $monthData['month']; ?>" value="<?= number_format($monthData['budget_fixed_cost'], 2); ?>" style="display:none;">

                                    <!-- Edit Button -->
                                    <button class="edit-btn" onclick="editData('fixed_budgeted', '<?= $monthData['month']; ?>')">
                                        <i class="fa fa-edit"></i>
                                    </button>

                                    <!-- Tick (Save) and Cross (Cancel) -->
                                    <button class="save-btn" id="save_fixed_budgeted_<?= $monthData['month']; ?>" style="display:none;" onclick="saveData('fixed_budgeted', '<?= $monthData['month']; ?>')">
                                        <i class="fa fa-check"></i>
                                    </button>
                                    <button class="cancel-btn" id="cancel_fixed_budgeted_<?= $monthData['month']; ?>" style="display:none;" onclick="cancelEdit('fixed_budgeted', '<?= $monthData['month']; ?>')">
                                        <i class="fa fa-times"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>


<div class="row mt-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h4>Enter Salaries & Fixed Costs</h4>
            </div>
            <div class="card-body">
                <form method="post" action="process_costs.php"> <!-- Assuming you have a separate script to process the entered costs -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="salaryActuals">Enter Salary Actuals:</label>
                                <input type="text" class="form-control" id="salaryActuals" name="salaryActuals" placeholder="Enter actual salary amount">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="salaryBudgeted">Enter Salary Budgeted:</label>
                                <input type="text" class="form-control" id="salaryBudgeted" name="salaryBudgeted" placeholder="Enter budgeted salary amount">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="fixedCostActuals">Enter Fixed Cost Actuals:</label>
                                <input type="text" class="form-control" id="fixedCostActuals" name="fixedCostActuals" placeholder="Enter actual fixed cost amount">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="fixedCostBudgeted">Enter Fixed Cost Budgeted:</label>
                                <input type="text" class="form-control" id="fixedCostBudgeted" name="fixedCostBudgeted" placeholder="Enter budgeted fixed cost amount">
                            </div>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>
</div>
<!-- Add this in the <head> or just before the closing </body> tag -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script>
        function editData(type, month) {
   // Toggle display between the span and input field
   let spanElement = document.getElementById(`${type}_${month}`);
   let inputElement = document.getElementById(`input_${type}_${month}`);
   let saveButton = document.getElementById(`save_${type}_${month}`);
   let cancelButton = document.getElementById(`cancel_${type}_${month}`);
   
   // Show input field and save/cancel buttons, hide span
   spanElement.style.display = "none";
   inputElement.style.display = "inline-block";
   saveButton.style.display = "inline-block";
   cancelButton.style.display = "inline-block";
   inputElement.focus();  // Automatically focus on the input field
}

function saveData(type, month) {
   let spanElement = document.getElementById(`${type}_${month}`);
   let inputElement = document.getElementById(`input_${type}_${month}`);
   let newValue = parseFloat(inputElement.value); // Parse the input as a float

   // Convert the value back to rupees (multiply by 100,000)
   let newValueInRupees = newValue * 100000;

   // Save the updated data via AJAX
   $.ajax({
      url: 'update_SnF.php',
      type: 'POST',
      data: {
         type: type,
         month: month,
         value: newValueInRupees  // Send the value in rupees
      },
      success: function(response) {
         if (response == 'success') {
            // Update the displayed value (in lakhs) and revert to non-edit mode
            spanElement.innerText = newValue.toFixed(2); // Display in lakhs
            cancelEdit(type, month); // Revert to display mode after saving
         } else {
            alert('Error updating data.');
         }
      },
      error: function() {
         alert('Failed to update data.');
      }
   });
}

function cancelEdit(type, month) {
   let spanElement = document.getElementById(`${type}_${month}`);
   let inputElement = document.getElementById(`input_${type}_${month}`);
   let saveButton = document.getElementById(`save_${type}_${month}`);
   let cancelButton = document.getElementById(`cancel_${type}_${month}`);

   // Hide the input field and save/cancel buttons, show the span
   spanElement.style.display = "inline-block";
   inputElement.style.display = "none";
   saveButton.style.display = "none";
   cancelButton.style.display = "none";
}



        // Function to trigger CSV download
        function downloadCSV() {
            const table = document.querySelector('.table');
            const rows = table.querySelectorAll('tr');
            const csv = [];

            // Generate CSV content
            rows.forEach((row, rowIndex) => {
                const rowData = [];
                row.querySelectorAll('td, th').forEach((cell, cellIndex) => {
                    // Wrap cell data in double quotes and escape existing double quotes
                    const cellData = cell.textContent.replace(/"/g, '""');
                    rowData.push(`"${cellData}"`);
                });

                // Include the header row if it's the first row
                if (rowIndex === 0) {
                    csv.push(rowData.join(','));
                } else {
                    csv.push(rowData.join(','));
                }
            });

            // Create a blob containing the CSV data
            const blob = new Blob([csv.join('\n')], { type: 'text/csv' });

            // Create a download link and trigger the download
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = 'costing_report.csv';
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // Add click event listener to the download button
        document.getElementById('download-csv').addEventListener('click', downloadCSV);
</script>
<?php include('includes/footer.php'); ?>
<style>
    .edit-btn, .save-btn, .cancel-btn {
   background: none;
   border: none;
   cursor: pointer;
   color: #007bff;
   margin-left: 5px;
}

.edit-btn:hover, .save-btn:hover, .cancel-btn:hover {
   color: #0056b3;
}

.save-btn, .cancel-btn {
   display: none;  /* These are initially hidden until the edit button is clicked */
}

.editField {
   width: 80px;  /* Adjust this based on your layout */
   display: inline-block;
}

</style>