<?php

require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

// $zdb = $_SESSION["zdbyear_" . $dbname];
// mysqli_select_db($conn, $zdb);
$admin = $_SESSION["admin_" . $dbname];

if (isset($_REQUEST["vouchdt"])) {

    $vouchdt = $_REQUEST["vouchdt"];

    $ctr = 0;
    $tqty = 0;
    $tamount = 0;
    $getdet = mysqli_query($conn, "SELECT a.*,date_format(a.`vouchdt`, '%d-%m-%Y') AS mydt, b.name
                                          FROM `expentry_pe` a
                                          LEFT JOIN accmast_pe b ON a.expense = b.accode
                                          WHERE `vouchdt`='$vouchdt' ORDER BY vouchno") or die(mysqli_error($conn));

    if (mysqli_num_rows($getdet) > 0) {
        while ($fetdet = mysqli_fetch_array($getdet)) {
            
            $ctr++;

            $paidbyOptions = [
                'R' => 'Credit',
                'C' => 'Cash',
                'U' => 'UPI'
            ];

            $paidbyValue = $fetdet['paidby'] ?? ''; // Get current value
            $pdby = isset($paidbyOptions[$paidbyValue]) ? $paidbyOptions[$paidbyValue] : '';

            // Row background color based on paidby
            $rowColor = '';
            switch ($paidbyValue) {
                case 'C':
                    $rowColor = 'background-color: #fcf6bd;';
                    break;  // Light Red (Cash)
                case 'R':
                    $rowColor = 'background-color: #d1ecf1;';
                    break;  // Light Blue (Credit)
                case 'U':
                    $rowColor = 'background-color: #e4c1f9;';
                    break;  // Light Green (UPI)
            }


            echo "<tr class='tabital clickable-row' style='$rowColor' data-href='expheadentry.php?mode=edit&vouchno=$fetdet[vouchno]'>";
            echo "<td class='text-center'>$ctr</td>";
            echo "<td class='text-center'>$fetdet[mydt]</td>";
            echo "<td>$fetdet[name]</td>";
            echo "<td class='text-right'>$fetdet[amount]</td>";
            echo "<td class='text-center'>$pdby</td>";
            echo "<td>$fetdet[payee]</td>";
            echo "</tr>";
            
            $tqty = $tqty + $fetdet['qty'];
            $tamount = $tamount + $fetdet['amount'];
        }

        echo "<tr class='tabital' style='color:red;'>";
        echo "<td></td>";
        echo "<td></td>";
        echo "<td class='text-right'><b>Total</b></td>";
        echo "<td class='text-right'> <b>" . number_format($tamount, 2) . "</b> </td>";
        echo "<td></td>";
        echo "<td></td>";
    } else {
        echo "<tr><td colspan='8' style='text-align:center;'>No Record Found</td></tr>";
    }
} else {
    echo "<tr><td colspan='8' style='text-align:center;'>ERROR: Missing parameters</td></tr>";
}
?>