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

<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h4>
                    Direct Material Costs
                    <button id="download-csv" class="btn btn-primary mb-3  float-end">Download CSV</button>
                    <button id="transfer-dm" class="btn btn-success mb-3 me-3 float-end">Transfer to Previous Month</button>
                </h4>
            </div>
            <div class="card-body">
                <?= alertMessage(); ?>
                <form action="update_cumulative_dm.php" method="POST">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr class="align-middle text-center">
                                <th>S.No.</th>
                                <th>Client Name</th>
                                <th>Project Name</th>
                                <th>Contract Value</th>
                                <th>Cumulative DM Previous Year</th>
                                <th>Cumulative DM Previous Month</th>
                                <th>Cumulative DM This Month</th>
                                <th>Enter Cumulative DM For This Month</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $no = 1;
                            $projects = linkALLDM('projects');
                            $totalPreviousMonth = 0;
                            $totalCurrentMonth = 0;
                            $totaldmPrevYear = 0;

                            if (mysqli_num_rows($projects) > 0) {
                                foreach ($projects as $projectItem) {
                                    $contractValue = $projectItem['contractValue'];
                                    $directMaterialcostPrev = $projectItem['directMaterialcostPrev'];
                                    $directMaterialcost = $projectItem['directMaterialcost'];
                                    $dmPrevYear = $projectItem['dmPrevYear'];

                                    // Calculate totals for Previous Month and Current Month
                                    $totalPreviousMonth += $directMaterialcostPrev;
                                    $totalCurrentMonth += $directMaterialcost;
                                    $totaldmPrevYear += $dmPrevYear;
                                    ?>
                                    <tr class="align-middle text-center text-xs">
                                        <td><?= $no; ?></td>
                                        <td><?= $projectItem['clientName']; ?></td>
                                        <td><?= $projectItem['projectName']; ?></td>
                                        <td><?= $contractValue; ?></td>
                                        <td><?= $dmPrevYear; ?></td>
                                        <td><?= $directMaterialcostPrev; ?></td>
                                        <td><?= $directMaterialcost; ?></td>
                                        <td>
                                            <input type="hidden" name="projectID[]" value="<?= $projectItem['projectID']; ?>">
                                            <input type="text" name="cumulative_dm[]" class="form-control"
                                                placeholder="Enter DM for This Month">
                                        </td>
                                    </tr>
                                    <?php
                                    $no++;
                                }
                            } else {
                                ?>
                                <tr>
                                    <td colspan="7">No record Found</td>
                                </tr>
                                <?php
                            }
                            ?>
                        </tbody>
                        <!-- Add footer rows for totals with background color -->
                        <tfoot>
                            <tr class="bg-secondary text-white">
                                <td class="align-middle text-center" colspan="4"><strong>Total</strong></td>
                                <td class="align-middle text-center text-xs"><strong><?= $totaldmPrevYear; ?></strong></td>
                                <td class="align-middle text-center text-xs"><strong><?= $totalPreviousMonth; ?></strong></td>
                                <td class="align-middle text-center text-xs"><strong><?= $totalCurrentMonth; ?></strong></td>
                                <td></td>
                            </tr>
                        </tfoot>
                        <?php
                        $reportingMonth = date('Y-m-01', strtotime('first day of previous month'));
                        $reportingMonthNumber = (int)date('n', strtotime($reportingMonth));
                        $totalDMmonth = ($reportingMonthNumber === 4)
                            ? $totalCurrentMonth
                            : ($totalCurrentMonth - $totalPreviousMonth);
                        // Store the calculated MIS income in the database
                        $insertQuery = "INSERT INTO mis_DM_cum (month, cumulative_DM_value, budget_DM_value) VALUES ('$reportingMonth', '$totalCurrentMonth', 0)
                                        ON DUPLICATE KEY UPDATE cumulative_DM_value = '$totalCurrentMonth'";

                        $result = mysqli_query($conn, $insertQuery);

                        if (!$result) {
                            die("Insert failed: " . mysqli_error($conn));
                        }
                        
                        // Store the calculated MIS income in the database
                        $insertQueryMonthly = "INSERT INTO mis_DM_monthly (month, monthly_DM_value) VALUES ('$reportingMonth', '$totalDMmonth')
                                        ON DUPLICATE KEY UPDATE monthly_DM_value = '$totalDMmonth'";

                        $resultMonthly = mysqli_query($conn, $insertQueryMonthly);

                        if (!$resultMonthly) {
                            die("Insert failed: " . mysqli_error($conn));
                        }
                        
                        
                        ?>
                    </table>
                    <button type="submit" class="btn btn-primary">Update Cumulative DM</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    // Function to transfer current month DM data to the previous month
    function transferDM() {
        if (confirm("Are you sure you want to transfer the current month DM data to the previous month? This will set the current month DM to 0.")) {
            // Make an AJAX request to the server to perform the transfer
            // Replace 'update_dm_transfer.php' with the actual URL to your transfer script
            fetch('update_dm_transfer.php', {
                method: 'POST',
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Reload the page to reflect the updated data
                        location.reload();
                    } else {
                        alert('Transfer failed. Please try again or contact support.');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred during the transfer.');
                });
        }
    }

    // Add click event listener to the transfer button
    document.getElementById('transfer-dm').addEventListener('click', transferDM);

    // 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 = 'cumulative_DM.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'); ?>