<?php
/**
 * Financial Dashboard
 * 
 * This dashboard displays key financial metrics for projects and clients,
 * including MIS income, project contributions, and labor/material costs.
 */

// Initialize
require_once('includes/header.php');

/**
 * =============================
 * DATE HANDLING UTILITIES
 * =============================
 */

/**
 * Get all date parameters needed for financial reporting
 * 
 * @return array Date parameters for financial reporting
 */
function getReportingDates() {
    // Current date information
    $currentDate = new DateTime();
    $currentYear = (int)$currentDate->format('Y');
    $currentMonth = (int)$currentDate->format('m');
    
    // Get reporting month (previous month)
    $reportingDate = clone $currentDate;
    $reportingDate->modify('-1 month');
    $reportingMonth = (int)$reportingDate->format('m');
    $reportingYear = (int)$reportingDate->format('Y');
    $reportingMonthStr = $reportingDate->format('Y-m-01');
    
    // Determine financial year based on reporting month
    $financialYearStart = $reportingMonth >= 4 ? $reportingYear : $reportingYear - 1;
    $financialYearEnd = $financialYearStart + 1;
    
    // Financial year boundaries
    $startMonth = "$financialYearStart-04-01";
    $endMonth = "$financialYearEnd-03-31";
    
    // March dates for completion comparison
    $marchPrevYear = "$financialYearStart-03-01";
    $marchCurrentYear = "$financialYearEnd-03-01";
    
    // Previous month for fallback
    $prevMonth = clone $reportingDate;
    $prevMonth->modify('-1 month');
    $prevMonthStr = $prevMonth->format('Y-m-01');
    
    return [
        'currentDate' => $currentDate,
        'reportingDate' => $reportingDate,
        'reportingMonthStr' => $reportingMonthStr,
        'reportingMonth' => $reportingMonth,
        'reportingYear' => $reportingYear,
        'financialYearStart' => $financialYearStart,
        'financialYearEnd' => $financialYearEnd,
        'startMonth' => $startMonth,
        'endMonth' => $endMonth,
        'marchPrevYear' => $marchPrevYear,
        'marchCurrentYear' => $marchCurrentYear,
        'prevMonthStr' => $prevMonthStr
    ];
}

/**
 * =============================
 * DATABASE FUNCTIONS
 * =============================
 */

/**
 * Execute a prepared statement and handle errors
 * 
 * @param mysqli $conn Database connection
 * @param string $query SQL query with placeholders
 * @param string $types Types of parameters
 * @param array $params Parameters to bind
 * @return mysqli_stmt|false Statement object or false on failure
 */
function executeQuery($conn, $query, $types = "", $params = []) {
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        error_log("Query preparation failed: " . $conn->error);
        return false;
    }
    
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    
    if (!$stmt->execute()) {
        error_log("Query execution failed: " . $stmt->error);
        return false;
    }
    
    return $stmt;
}

/**
 * Get a single value from the database
 *
 * @param mysqli $conn Database connection
 * @param string $query SQL query with placeholders
 * @param string $types Types of parameters
 * @param array $params Parameters to bind
 * @param string $default Default value if query fails
 * @return mixed The value or default if not found
 */
function getSingleValue($conn, $query, $types = "", $params = [], $default = 0) {
    $stmt = executeQuery($conn, $query, $types, $params);
    if (!$stmt) {
        return $default;
    }
    
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();
    
    return $row ? reset($row) : $default;
}

/**
 * Get financial metrics from the database
 * 
 * @param mysqli $conn Database connection
 * @param array $dates Date parameters for queries
 * @return array Financial metrics
 */
function getFinancialMetrics($conn, $dates) {
    // Get MIS Income metrics
    $misIncomeTotal = getSingleValue(
        $conn,
        "SELECT total_mis_income FROM mis_income_cum WHERE month = ?",
        "s",
        [$dates['reportingMonthStr']]
    );
    
    $monthlyMISIncome = getSingleValue(
        $conn,
        "SELECT monthly_mis_income FROM mis_income_monthly WHERE month = ?",
        "s",
        [$dates['reportingMonthStr']]
    );
    
    // Get direct labor metrics
    $totalDL = getSingleValue(
        $conn,
        "SELECT total_DL_value FROM mis_DL_cum WHERE month = ?",
        "s",
        [$dates['reportingMonthStr']]
    );
    
    $monthlyDL = getSingleValue(
        $conn,
        "SELECT monthly_DL_value FROM mis_DL_monthly WHERE month = ?",
        "s",
        [$dates['reportingMonthStr']]
    );
    
    // Get direct material metrics
    $totalCumulativeDM = getSingleValue(
        $conn,
        "SELECT cumulative_DM_value FROM mis_DM_cum WHERE month = ?",
        "s",
        [$dates['reportingMonthStr']]
    );
    
    $monthlyCumulativeDM = getSingleValue(
        $conn,
        "SELECT monthly_DM_value FROM mis_DM_monthly WHERE month = ?",
        "s",
        [$dates['reportingMonthStr']]
    );
    
    // Calculate contribution metrics
    $totalProjectContribution = $misIncomeTotal - $totalDL - $totalCumulativeDM;
    $projectContributionPercentage = ($misIncomeTotal > 0) 
        ? ($totalProjectContribution / $misIncomeTotal) * 100 
        : 0;
    
    $monthlyProjectContribution = $monthlyMISIncome - $monthlyDL - $monthlyCumulativeDM;
    $projectContributionPercentageMonthly = ($monthlyMISIncome > 0) 
        ? ($monthlyProjectContribution / $monthlyMISIncome) * 100 
        : 0;
    
    // Get order and receivable values
    $totalContractValue = getSingleValue(
        $conn,
        "SELECT SUM(contractAmt) AS total_contract_value FROM contracts"
    );
    
    $totalBilledValue = getSingleValue(
        $conn,
        "SELECT SUM(bd.billAmount) AS total_billed_value
         FROM ncbilldetails bd
         INNER JOIN ncmilestones m ON bd.ncmilestoneID = m.ncmilestoneID
         INNER JOIN contracts c ON m.contractID = c.contractID
         WHERE c.contractAmt >= 100"
    );
    
    $totalReceivedValue = getSingleValue(
        $conn,
        "SELECT SUM(bd.receivedAmt) AS total_received_value
         FROM ncbilldetails bd
         JOIN ncmilestones m ON bd.ncmilestoneID = m.ncmilestoneID
         JOIN contracts c ON m.contractID = c.contractID
         WHERE c.contractAmt > 100"
    );
    
    $totalOrderOnHand = $totalContractValue - $totalBilledValue;
    $receivableValue = $totalBilledValue - $totalReceivedValue;
    
    return [
        'misIncomeTotal' => $misIncomeTotal,
        'monthlyMISIncome' => $monthlyMISIncome,
        'totalDL' => $totalDL,
        'monthlyDL' => $monthlyDL,
        'totalCumulativeDM' => $totalCumulativeDM,
        'monthlyCumulativeDM' => $monthlyCumulativeDM,
        'totalProjectContribution' => $totalProjectContribution,
        'projectContributionPercentage' => $projectContributionPercentage,
        'monthlyProjectContribution' => $monthlyProjectContribution,
        'projectContributionPercentageMonthly' => $projectContributionPercentageMonthly,
        'totalOrderOnHand' => $totalOrderOnHand,
        'receivableValue' => $receivableValue
    ];
}

/**
 * Get project income data with milestone completion information
 * 
 * @param mysqli $conn Database connection
 * @param array $dates Date parameters for queries 
 * @return array Top projects by income and contribution
 */
function getProjectData($conn, $dates) {
    $query = "SELECT projects.contractValue, clients.clientName, projects.projectName, 
                     milestones.milestoneName, milestones.milestoneValue,
                     MAX(CASE WHEN DATE_FORMAT(date, '%Y-%m') = DATE_FORMAT(?, '%Y-%m') 
                         THEN perCompletion END) AS perCompletionMarch,
                     MAX(CASE WHEN DATE_FORMAT(date, '%Y-%m') = DATE_FORMAT(?, '%Y-%m') 
                         THEN perCompletion ELSE CASE WHEN DATE_FORMAT(date, '%Y-%m') = DATE_FORMAT(?, '%Y-%m') 
                         THEN perCompletion END END) AS perCompletionMar,
                     MAX(CASE WHEN DATE_FORMAT(date, '%Y-%m') = DATE_FORMAT(?, '%Y-%m') 
                         THEN perCompletion END) AS perCompletionFeb,
           SUM(users.employeeRate * (timesheet.hrs / 8)) AS CumulativeDL
    FROM milestones
    INNER JOIN projects ON milestones.projectID = projects.projectID
    INNER JOIN clients ON projects.clientID = clients.clientID
    LEFT JOIN perCompletion ON milestones.milestoneID = perCompletion.milestoneID
    LEFT JOIN timesheet ON milestones.milestoneID = timesheet.milestoneID
    LEFT JOIN users ON timesheet.userID = users.userID
              WHERE DATE_FORMAT(date, '%Y-%m') IN (DATE_FORMAT(?, '%Y-%m'), 
                                                  DATE_FORMAT(?, '%Y-%m'), 
                                                  DATE_FORMAT(?, '%Y-%m'))
    GROUP BY clients.clientName, projects.projectName, milestones.milestoneName
    ORDER BY clients.clientName ASC, projects.projectName ASC, milestones.milestoneName ASC";

    $stmt = executeQuery(
        $conn, 
        $query,
        "sssssss",
        [
            $dates['marchPrevYear'],
            $dates['marchCurrentYear'],
            $dates['prevMonthStr'],
            $dates['prevMonthStr'],
            $dates['marchPrevYear'],
            $dates['prevMonthStr'],
            $dates['marchCurrentYear']
        ]
    );
    
    if (!$stmt) {
        return [
            'projectTotalIncome' => [],
            'projectClientNames' => [],
            'clientTotalIncome' => []
        ];
    }
    
    $result = $stmt->get_result();
    
    // Initialize storage arrays
    $projectTotalIncome = [];
    $projectClientNames = [];
    $clientTotalIncome = [];
    
    // Process milestone data
    while ($row = $result->fetch_assoc()) {
    $projectName = $row['projectName'];
        $clientName = $row['clientName'];
    $milestoneValue = $row['milestoneValue'];
        $perCompletionMarch = $row['perCompletionMarch'] ?? 0;
    $perCompletionMar = $row['perCompletionMar'];
        $perCompletionFeb = $row['perCompletionFeb'];

        // Store client name for each project
    $projectClientNames[$projectName] = $clientName;

    if ($perCompletionMarch != 100) {
            // Calculate milestone income with proper fallback
        if ($perCompletionMar !== null) {
            $milestoneIncome = $milestoneValue * (($perCompletionMar - $perCompletionMarch) / 100);
        } else {
                // Fallback to February data if March data not available
            $milestoneIncome = $milestoneValue * (($perCompletionFeb - $perCompletionMarch) / 100);
        }

            // Add to project income totals
        if (!isset($projectTotalIncome[$projectName])) {
            $projectTotalIncome[$projectName] = 0;
        }
            $projectTotalIncome[$projectName] += $milestoneIncome;
            
            // Add to client income totals
            if (!isset($clientTotalIncome[$clientName])) {
                $clientTotalIncome[$clientName] = 0;
            }
            $clientTotalIncome[$clientName] += $milestoneIncome;
        }
    }
    
    $stmt->close();
    
    // Get cumulative project data
$queryCumulative = "SELECT clients.clientName, projects.projectName, 
                          SUM(users.employeeRate * (timesheet.hrs / 8)) AS CumulativeDL, 
                          projects.directMaterialcost AS CumulativeDM
                   FROM timesheet
                   INNER JOIN milestones ON timesheet.milestoneID = milestones.milestoneID
                   INNER JOIN projects ON milestones.projectID = projects.projectID
                   INNER JOIN clients ON projects.clientID = clients.clientID
                   INNER JOIN users ON timesheet.userID = users.userID
                         WHERE timesheet.tentryDate BETWEEN ? AND ?
                   GROUP BY clients.clientName, projects.projectName
                   ORDER BY CumulativeDL DESC";

    $stmtCumulative = executeQuery(
        $conn,
        $queryCumulative,
        "ss",
        [$dates['startMonth'], $dates['endMonth']]
    );
    
    if (!$stmtCumulative) {
        return [
            'projectTotalIncome' => $projectTotalIncome,
            'projectClientNames' => $projectClientNames,
            'clientTotalIncome' => $clientTotalIncome,
            'projectCumulative' => [],
            'projectTotalContribution' => []
        ];
    }
    
    $resultCumulative = $stmtCumulative->get_result();
    
    // Process cumulative data
    $projectCumulative = [];
    while ($rowCumulative = $resultCumulative->fetch_assoc()) {
    $projectName = $rowCumulative['projectName'];
    $cumulativeDL = $rowCumulative['CumulativeDL'];
    $cumulativeDM = $rowCumulative['CumulativeDM'];

    $projectCumulative[$projectName] = [
        'CumulativeDL' => $cumulativeDL,
        'CumulativeDM' => $cumulativeDM,
    ];
}

    $stmtCumulative->close();

    // Calculate contribution data
    $projectTotalContribution = [];
foreach ($projectTotalIncome as $projectName => $totalIncome) {
    if (isset($projectCumulative[$projectName])) {
        $cumulativeDL = $projectCumulative[$projectName]['CumulativeDL'];
        $cumulativeDM = $projectCumulative[$projectName]['CumulativeDM'];
        $totalContribution = $totalIncome - $cumulativeDL - $cumulativeDM;
            $contributionPercentage = ($totalIncome > 0) 
                ? ($totalContribution / $totalIncome) * 100 
                : 0;
            
        $projectTotalContribution[$projectName] = [
            'TotalContribution' => $totalContribution,
            'ContributionPercentage' => $contributionPercentage,
        ];
    } else {
        $projectTotalContribution[$projectName] = null;
    }
}

    // Sort data for charts
arsort($projectTotalIncome);
arsort($projectTotalContribution);
arsort($clientTotalIncome);

    return [
        'projectTotalIncome' => $projectTotalIncome,
        'projectClientNames' => $projectClientNames,
        'clientTotalIncome' => $clientTotalIncome,
        'projectCumulative' => $projectCumulative,
        'projectTotalContribution' => $projectTotalContribution
    ];
}

/**
 * =============================
 * MAIN EXECUTION
 * =============================
 */

// Get date parameters
$dates = getReportingDates();

// Get financial metrics
$metrics = getFinancialMetrics($conn, $dates);

// Get project and client data
$projectData = getProjectData($conn, $dates);

// Extract data for charts
$topProjectsIncome = array_slice($projectData['projectTotalIncome'], 0, 10, true);
$topProjectsContribution = array_slice($projectData['projectTotalContribution'], 0, 10, true);
$topClientsIncome = array_slice($projectData['clientTotalIncome'], 0, 10, true);

// Close the database connection
mysqli_close($conn);

/**
 * =============================
 * PRESENTATION / HTML OUTPUT
 * =============================
 */
?>

<div class="container">
    <div class="d-flex justify-content-end mt-2">
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#changePasswordModal">
            Change Password
        </button>
    </div>
</div>

<!-- Password Change Modal -->
<div class="modal fade" id="changePasswordModal" tabindex="-1" role="dialog" aria-labelledby="changePasswordModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="changePasswordModalLabel">Change Password</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="changePasswordForm">
                    <div class="form-group">
                        <label for="currentPassword">Current Password</label>
                        <input type="password" class="form-control" id="currentPassword" name="currentPassword" required>
                    </div>
                    <div class="form-group">
                        <label for="newPassword">New Password</label>
                        <input type="password" class="form-control" id="newPassword" name="newPassword" required>
                    </div>
                    <div class="form-group">
                        <label for="confirmPassword">Confirm New Password</label>
                        <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>
</div>

<h2>Welcome, <?php echo htmlspecialchars($_SESSION['fname']); ?>!</h2>

<!-- Add this right after your welcome heading -->
<div class="row mb-4">
    <div class="col-md-6">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">Reporting Period</h5>
                <div class="form-row align-items-center">
                    <div class="col-md-6">
                        <label for="reportingMonth">Select Month:</label>
                        <input type="month" id="reportingMonth" class="form-control" 
                               value="<?php echo $dates['reportingDate']->format('Y-m'); ?>" 
                               max="<?php echo (new DateTime('first day of this month'))->format('Y-m'); ?>">
                    </div>
                    <div class="col-md-6 mt-4">
                        <button id="updateDashboard" class="btn btn-primary">Update Dashboard</button>
                    </div>
                </div>
                <div id="updateStatus" class="mt-2 text-info"></div>
            </div>
        </div>
    </div>
</div>

<!-- Financial Metrics Cards -->
<div class="row align-middle text-center">
    <div class="col-md-4 mb-4">
        <div class="card card-body p-4">
            <p class="text-sm mb-0 text-capitalize font-weight-bold">Cumulative MIS Income</p>
            <h5 class="font-weight-bolder mb-0" id="misIncomeTotal">
                ₹<?php echo number_format($metrics['misIncomeTotal'] / 100000, 2); ?> Lakhs
            </h5>
        </div>
    </div>
    <div class="col-md-4 mb-4">
        <div class="card card-body p-4">
        <p class="text-sm mb-0 text-capitalize font-weight-bold">Cumulative Project Contribution</p>
            <h5 class="font-weight-bolder mb-0">
                ₹<?php echo number_format($metrics['totalProjectContribution'] / 100000, 2); ?> Lakhs
            </h5>
        </div>
    </div>
    <div class="col-md-4 mb-4">
        <div class="card card-body p-4">
        <p class="text-sm mb-0 text-capitalize font-weight-bold">Project Contribution %age</p>
            <h5 class="font-weight-bolder mb-0">
                <?php echo number_format($metrics['projectContributionPercentage'], 2); ?>%
            </h5>
        </div>
    </div>
    <div class="col-md-4 mb-4">
        <div class="card card-body p-4">
        <p class="text-sm mb-0 text-capitalize font-weight-bold">Monthly MIS Income (<span class="reporting-month"><?php echo $dates['reportingDate']->format('F Y'); ?></span>)</p>
            <h5 class="font-weight-bolder mb-0" id="monthlyMISIncome">
                ₹<?php echo number_format($metrics['monthlyMISIncome'] / 100000, 2); ?> Lakhs
            </h5>
        </div>
    </div>
    <div class="col-md-4 mb-4">
        <div class="card card-body p-4">
        <p class="text-sm mb-0 text-capitalize font-weight-bold">Monthly Project Contribution (<?php echo $dates['reportingDate']->format('F Y'); ?>)</p>
            <h5 class="font-weight-bolder mb-0" id="monthlyProjectContribution">
                ₹<?php echo number_format($metrics['monthlyProjectContribution'] / 100000, 2); ?> Lakhs
            </h5>
        </div>
    </div>
    <div class="col-md-4 mb-4">
        <div class="card card-body p-4">
        <p class="text-sm mb-0 text-capitalize font-weight-bold">Project Contribution %age (<?php echo $dates['reportingDate']->format('F Y'); ?>)</p>
            <h5 class="font-weight-bolder mb-0">
                <?php echo number_format($metrics['projectContributionPercentageMonthly'], 2); ?>%
            </h5>
        </div>
    </div>
    <div class="col-md-6 mb-4">
        <div class="card card-body p-4">
        <p class="text-sm mb-0 text-capitalize font-weight-bold">Cumulative RGL Value</p>
            <h5 class="font-weight-bolder mb-0">
                ₹<?php echo number_format($metrics['totalDL'] / 100000, 2); ?> Lakhs
            </h5>
        </div>
    </div>
    <div class="col-md-6 mb-4">
        <div class="card card-body p-4">
        <p class="text-sm mb-0 text-capitalize font-weight-bold">RGL Value (<?php echo $dates['reportingDate']->format('F Y'); ?>)</p>
            <h5 class="font-weight-bolder mb-0">
                ₹<?php echo number_format($metrics['monthlyDL'] / 100000, 2); ?> Lakhs
            </h5>
        </div>
    </div>
    <div class="col-md-6 mb-4">
        <div class="card card-body p-4">
        <p class="text-sm mb-0 text-capitalize font-weight-bold">Total Order On Hand</p>
            <h5 class="font-weight-bolder mb-0">
                ₹<?php echo number_format($metrics['totalOrderOnHand'] / 100000, 2); ?> Lakhs
            </h5>
        </div>
    </div>
    <div class="col-md-6 mb-4">
        <div class="card card-body p-4">
        <p class="text-sm mb-0 text-capitalize font-weight-bold">Receivable Value</p>
            <h5 class="font-weight-bolder mb-0">
                ₹<?php echo number_format($metrics['receivableValue'] / 100000, 2); ?> Lakhs
            </h5>
        </div>
    </div>
</div>

<!-- Chart Containers -->
<div class="row">
    <div class="col-md-6 mb-4">
        <div class="card card-body p-4">
            <div id='incomeChart'></div>
        </div>
    </div>
    <div class="col-md-6 mb-4">
        <div class="card card-body p-4">
            <div id='contributionChart'></div>
        </div>
    </div>
</div>

<!-- Client Income Chart Container -->
<div class="row">
    <div class="col-md-6 mb-4">
        <div class="card card-body p-4">
            <div id='clientIncomeChart'></div>
        </div>
    </div>
</div>

<!-- JavaScript for charts and password form -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script type="text/javascript">
    // Password Change Form Handler
    $(document).ready(function() {
        $('#changePasswordForm').on('submit', function(event) {
            event.preventDefault(); // Prevent default form submission

            const formData = {
                currentPassword: $('#currentPassword').val(),
                newPassword: $('#newPassword').val(),
                confirmPassword: $('#confirmPassword').val()
            };

            $.ajax({
                url: 'change_password.php',
                type: 'POST',
                data: formData,
                success: function(response) {
                    alert(response);
                    $('#changePasswordModal').modal('hide'); 
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error('Error:', textStatus, errorThrown);
                }
            });
        });
        
        // Initialize charts on page load
        initializeCharts();
        
        // Handle dashboard update button click
        $('#updateDashboard').click(function() {
            updateDashboardData();
        });
    });
    
    // Chart objects (global to allow updating)
    var incomeChart, contributionChart, clientIncomeChart;
    
    // Initialize Google Charts
    google.charts.load('current', { 'packages': ['corechart'] });
    google.charts.setOnLoadCallback(initializeCharts);
    
    // Initialize the charts with default data
    function initializeCharts() {
        drawTopProjectsByIncomeChart(<?php echo json_encode(prepareChartData($topProjectsIncome)); ?>);
        drawTopProjectsByContributionChart(<?php echo json_encode(prepareChartData($topProjectsContribution, 'TotalContribution')); ?>);
        drawTopClientsByIncomeChart(<?php echo json_encode(prepareChartData($topClientsIncome)); ?>);
    }
    
    // Update dashboard data via AJAX
    function updateDashboardData() {
        const selectedMonth = $('#reportingMonth').val();
        if (!selectedMonth) {
            $('#updateStatus').html('<span class="text-danger">Please select a valid month</span>');
            return;
        }
        
        // Show loading message
        $('#updateStatus').html('<span>Loading dashboard data...</span>');
        $('.card-body').css('opacity', '0.6');
        
        // Make AJAX request
        $.ajax({
            url: 'dashboard_data.php',
            type: 'GET',
            data: { month: selectedMonth },
            dataType: 'json',
            success: function(response) {
                if (response.error) {
                    $('#updateStatus').html('<span class="text-danger">' + response.error + '</span>');
                    return;
                }
                
                // Update metrics cards
                updateMetricsCards(response.metrics);
                
                // Update charts
                updateCharts(response.chartData);
                
                // Update status and reset opacity
                $('#updateStatus').html('<span class="text-success">Dashboard updated for ' + 
                    response.reportingPeriod + '</span>');
                $('.card-body').css('opacity', '1');
                
                // Update reporting period in cards
                $('.reporting-month').text(response.reportingPeriod);
            },
            error: function(xhr, status, error) {
                $('#updateStatus').html('<span class="text-danger">Error updating dashboard: ' + error + '</span>');
                $('.card-body').css('opacity', '1');
                console.error(xhr.responseText);
            }
        });
    }
    
    // Update metrics cards with new data
    function updateMetricsCards(metrics) {
        // Update each metric value
        $('#misIncomeTotal').text('₹' + formatNumber(metrics.misIncomeTotal / 100000, 2) + ' Lakhs');
        $('#totalProjectContribution').text('₹' + formatNumber(metrics.totalProjectContribution / 100000, 2) + ' Lakhs');
        $('#projectContributionPercentage').text(formatNumber(metrics.projectContributionPercentage, 2) + '%');
        $('#monthlyMISIncome').text('₹' + formatNumber(metrics.monthlyMISIncome / 100000, 2) + ' Lakhs');
        $('#monthlyProjectContribution').text('₹' + formatNumber(metrics.monthlyProjectContribution / 100000, 2) + ' Lakhs');
        $('#projectContributionPercentageMonthly').text(formatNumber(metrics.projectContributionPercentageMonthly, 2) + '%');
        $('#totalDL').text('₹' + formatNumber(metrics.totalDL / 100000, 2) + ' Lakhs');
        $('#monthlyDL').text('₹' + formatNumber(metrics.monthlyDL / 100000, 2) + ' Lakhs');
        $('#totalOrderOnHand').text('₹' + formatNumber(metrics.totalOrderOnHand / 100000, 2) + ' Lakhs');
        $('#receivableValue').text('₹' + formatNumber(metrics.receivableValue / 100000, 2) + ' Lakhs');
    }
    
    // Update all charts with new data
    function updateCharts(chartData) {
        drawTopProjectsByIncomeChart(chartData.topProjectsIncome);
        drawTopProjectsByContributionChart(chartData.topProjectsContribution);
        drawTopClientsByIncomeChart(chartData.topClientsIncome);
    }
    
    // Format numbers for display
    function formatNumber(number, decimals = 0) {
        return parseFloat(number).toLocaleString('en-IN', {
            minimumFractionDigits: decimals,
            maximumFractionDigits: decimals
        });
    }
    
    // Draw Project Income Chart
    function drawTopProjectsByIncomeChart(chartData) {
        var incomeData = new google.visualization.DataTable();
        incomeData.addColumn('string', 'Project Name');
        incomeData.addColumn('number', 'Project Total Income (in Lakhs)');
        incomeData.addColumn({type: 'string', role: 'annotation'});
        
        incomeData.addRows(chartData);

        var incomeOptions = {
            title: 'Top 10 Projects by Cumulative Project Income (in Lakhs)',
            width: 530,
            height: 400,
            legend: 'none',
            colors: ['#a7202a'],
            hAxis: {
                format: '#,##0.0L',
                viewWindowMode: 'maximized'
            },
            bar: { groupWidth: '85%' },
            annotations: {
                textStyle: { fontSize: 9 }
            }
        };

        if (!incomeChart) {
            incomeChart = new google.visualization.ColumnChart(document.getElementById('incomeChart'));
        }
        incomeChart.draw(incomeData, incomeOptions);
    }

    // Draw Project Contribution Chart
    function drawTopProjectsByContributionChart(chartData) {
        var contributionData = new google.visualization.DataTable();
        contributionData.addColumn('string', 'Project Name');
        contributionData.addColumn('number', 'Total Contribution (in Lakhs)');
        contributionData.addColumn({type: 'string', role: 'annotation'});
        
        contributionData.addRows(chartData);

        var contributionOptions = {
            title: 'Top 10 Projects by Total Contribution (in Lakhs)',
            width: 530,
            height: 400,
            legend: 'none',
            colors: ['#a7202a'],
            hAxis: {
                format: '#,##0.0L'
            },
            bar: { groupWidth: '85%' },
            annotations: {
                textStyle: { fontSize: 9 }
            }
        };

        if (!contributionChart) {
            contributionChart = new google.visualization.ColumnChart(document.getElementById('contributionChart'));
        }
        contributionChart.draw(contributionData, contributionOptions);
    }

    // Draw Client Income Chart
    function drawTopClientsByIncomeChart(chartData) {
        var clientIncomeData = new google.visualization.DataTable();
        clientIncomeData.addColumn('string', 'Client Name');
        clientIncomeData.addColumn('number', 'Total Client Income (in Lakhs)');
        clientIncomeData.addColumn({type: 'string', role: 'annotation'});
        
        clientIncomeData.addRows(chartData);

        var clientIncomeOptions = {
            title: 'Top 10 Clients by Total Client Income (in Lakhs)',
            width: 530,
            height: 400,
            legend: 'none',
            colors: ['#a7202a'],
            hAxis: {
                format: '#,##0.0L',
                viewWindowMode: 'maximized'
            },
            bar: { groupWidth: '85%' },
            annotations: {
                textStyle: { fontSize: 9 }
            }
        };

        if (!clientIncomeChart) {
            clientIncomeChart = new google.visualization.ColumnChart(document.getElementById('clientIncomeChart'));
        }
        clientIncomeChart.draw(clientIncomeData, clientIncomeOptions);
    }
</script>

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

<?php
/**
 * Format chart data for JSON encoding
 * 
 * @param array $data Input data array
 * @param string $valueKey Key for value extraction (for contributions)
 * @return array Formatted chart data array
 */
function prepareChartData($data, $valueKey = null) {
    $chartData = [];
    foreach ($data as $name => $value) {
        if ($valueKey && is_array($value)) {
            if (isset($value[$valueKey])) {
                $valueInLakhs = number_format($value[$valueKey] / 100000, 1);
                $chartData[] = [addslashes($name), floatval($valueInLakhs), $valueInLakhs . ' L'];
            }
        } else {
            $valueInLakhs = number_format($value / 100000, 1);
            $chartData[] = [addslashes($name), floatval($valueInLakhs), $valueInLakhs . ' L'];
        }
    }
    return $chartData;
}