<?php

include("db/cn.php");
include("common/tx.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ob_start();
if (isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
}
ob_end_flush();

$saleRevenueData = [];
$saleCostData = [];
$expensesData = [];
$profitData = [];
$labels = [];  // To store dates for labels

$startDate = '';
$endDate = '';

if (isset($_POST['filter'])) {
    $startDate = $_POST['startDate'];
    $endDate = $_POST['endDate'];

    // Generate the list of dates between the start and end date
    $period = new DatePeriod(
        new DateTime($startDate),
        new DateInterval('P1D'),  // Daily interval
        (new DateTime($endDate))->modify('+1 day')
    );

    foreach ($period as $date) {
        $currentDate = $date->format('Y-m-d');
        $labels[] = $currentDate; // Add the date to labels

        // Initialize daily revenue, cost, expense, and refunded values
        $dailyRevenue = 0;
        $dailyCost = 0;
        $dailyExpense = 0;
        $dailyRefundedRevenue = 0;
        $dailyRefundedCost = 0;

        // Fetch and accumulate Sale Revenue for the current date
        $query = "SELECT order_id, discount_amount AS revenue 
                  FROM log_user_sales 
                  WHERE DATE(date_time) = '$currentDate' AND status = '' GROUP BY order_id";
        $result = mysqli_query($connection, $query);
        while ($row = mysqli_fetch_assoc($result)) {
            $dailyRevenue += $row['revenue'];
        }

        // Fetch and accumulate Sale Cost for the current date
        $query = "SELECT sale_cost AS cost 
                  FROM log_user_sales 
                  WHERE DATE(date_time) = '$currentDate' AND status = ''";
        $result = mysqli_query($connection, $query);
        while ($row = mysqli_fetch_assoc($result)) {
            $dailyCost += $row['cost'];
        }

        // Fetch and accumulate Refunded Revenue for the current date
        $query = "SELECT r_order_id, discount_amount AS refunded_revenue 
                  FROM log_user_sales 
                  WHERE DATE(date_time) = '$currentDate' AND status = 'refund' GROUP BY r_order_id";
        $result = mysqli_query($connection, $query);
        while ($row = mysqli_fetch_assoc($result)) {
            $dailyRefundedRevenue += $row['refunded_revenue'];
        }

        // Fetch and accumulate Refunded Sale Cost for the current date
        $query = "SELECT sale_cost AS refunded_cost 
                  FROM log_user_sales 
                  WHERE DATE(date_time) = '$currentDate' AND status = 'refund'";
        $result = mysqli_query($connection, $query);
        while ($row = mysqli_fetch_assoc($result)) {
            $dailyRefundedCost += $row['refunded_cost'];
        }

        // Fetch and accumulate Expenses for the current date
        $query = "SELECT amount AS expense 
                  FROM incash 
                  WHERE DATE(date_time) = '$currentDate'";
        $result = mysqli_query($connection, $query);
        while ($row = mysqli_fetch_assoc($result)) {
            $dailyExpense += (int)$row['expense'];
        }

        // Calculate Net Revenue and Net Cost by subtracting refunds
        $netRevenue = $dailyRevenue - $dailyRefundedRevenue;
        $netCost = $dailyCost - $dailyRefundedCost;

        // Store data in respective arrays
        $saleRevenueData[] = $netRevenue;
        $saleCostData[] = $netCost;
        $expensesData[] = $dailyExpense;

        // Calculate Net Profit for the current date
        $profitData[] = $netRevenue - ($netCost + $dailyExpense);
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title><?php echo $tx; ?></title>

    <!-- Custom fonts for this template-->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
   <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Custom styles for this template-->
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
        <link href="../css/sb-admin-2.css" rel="stylesheet">
    
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<style>


body {
    font-family: 'Quicksand', sans-serif;
    
}
		    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
.bg-gradient-primary{
    
	background:#0A4657;
	color:#fff;	
	
	}

.btn-primary{
	background:#0A4657;
	color:#fff;
	 border:1px #0A4657 solid;
	
	}  
.btn-primary:hover{
  
  background:#fff;
  border:1px #0A4657 solid;
	color:#0A4657;
	
	}	 
    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
	
	.fa-download:hover{
		color:#953E39;
		}
		
.text-primary{
	  	
		}
  </style>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

        <!-- Sidebar -->
        <?php
        include("common/sd.php");
		?>
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

                <!-- Topbar -->
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">

                    <!-- Sidebar Toggle (Topbar) -->
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>

                    <!-- Topbar Search -->
                    
  <?php include('common/log.php');  ?>

                    <!-- Topbar Navbar -->
                    
                </nav>
                <!-- End of Topbar -->

                <!-- Begin Page Content -->
          <div class="container-fluid mt-5">
        <div class="row">
        <div class="col-sm-5">
     <h3 style="color:#060606; font-weight:700;">Profit & Loss Report</h3>
        </div>
        <div class="col-sm-4"></div>
        <div class="col-sm-3">
             
        </div>
    </div>
    <br>
        <form method="post">
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="startDate">Start Date:</label>
                        <input type="date" class="form-control" name="startDate" value="<?php echo $startDate; ?>" required>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="endDate">End Date:</label>
                        <input type="date" class="form-control" name="endDate" value="<?php echo $endDate; ?>" required>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <br>
                        <button type="submit" class="btn btn-dark" name="filter">Filter</button>
                         <a href="report_pl.php"><button type="button" class="btn btn-dark"  ><i class="fas fa-sync-alt fa-1x"></i></button></a>
                        
                    </div>
                </div>
            </div>
        </form>

        <!-- Cards for Revenue, Cost, Expenses, and Profit -->
        <div class="row">
            <!-- Sales Revenue Card -->
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-primary shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-uppercase mb-1">Sales Revenue</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">Rs. <?php echo number_format(array_sum($saleRevenueData), 2); ?></div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-dollar-sign fa-2x text-primary"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Sales Cost Card -->
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-info shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-uppercase mb-1">Sales Cost</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">Rs. <?php echo number_format(array_sum($saleCostData), 2); ?></div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-dollar-sign fa-2x text-info"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Expenses Card -->
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-warning shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-uppercase mb-1">Expenses</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">Rs. <?php echo number_format(array_sum($expensesData), 2); ?></div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-dollar-sign fa-2x text-warning"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Net Profit Card -->
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-success shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-uppercase mb-1">Net Profit</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">Rs. <?php echo number_format(array_sum($profitData), 2); ?></div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-dollar-sign fa-2x text-success"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Graph -->
        <canvas id="profitLossChart"></canvas>

        <!-- Buttons for download -->
        <div class="mt-4">
            <button class="btn btn-dark" onclick="downloadCSV()">Download CSV Report</button>
            <button class="btn btn-dark" onclick="downloadGraph()">Download Graph as Image</button>
        </div>
    </div>


    
            
                <!-- /.container-fluid -->

            </div>
            <br><br>
            <!-- End of Main Content -->

            <!-- Footer -->
            <?php include("common/main_ft.php");  ?>
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <!-- End of Page Wrapper -->

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="">Logout</a>
                </div>
            </div>
        </div>
    </div>

    <script>
    var ctx = document.getElementById('profitLossChart').getContext('2d');
    var chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($labels); ?>, // Dates as labels
            datasets: [
                {
                    label: 'Sales Revenue',
                    backgroundColor: 'rgba(54, 162, 235, 0.2)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    data: <?php echo json_encode($saleRevenueData); ?>,
                    fill: false,
                    tension: 0.4
                },
                {
                    label: 'Sales Cost',
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    borderColor: 'rgba(75, 192, 192, 1)',
                    data: <?php echo json_encode($saleCostData); ?>,
                    fill: false,
                    tension: 0.4
                },
                {
                    label: 'Expenses',
                    backgroundColor: 'rgba(255, 206, 86, 0.2)',
                    borderColor: 'rgba(255, 206, 86, 1)',
                    data: <?php echo json_encode($expensesData); ?>,
                    fill: false,
                    tension: 0.4
                },
                {
                    label: 'Net Profit',
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    borderColor: 'rgba(75, 192, 192, 1)',
                    data: <?php echo json_encode($profitData); ?>,
                    fill: false,
                    tension: 0.4
                }
            ]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });

    // Function to download CSV report
    function downloadCSV() {
        var csvContent = "data:text/csv;charset=utf-8,";
        csvContent += "Date,Sales Revenue,Sales Cost,Expenses,Net Profit\n"; // Header
        var labels = <?php echo json_encode($labels); ?>;
        var saleRevenueData = <?php echo json_encode($saleRevenueData); ?>;
        var saleCostData = <?php echo json_encode($saleCostData); ?>;
        var expensesData = <?php echo json_encode($expensesData); ?>;
        var profitData = <?php echo json_encode($profitData); ?>;

        labels.forEach(function (label, index) {
            csvContent += label + "," + saleRevenueData[index] + "," + saleCostData[index] + "," + expensesData[index] + "," + profitData[index] + "\n";
        });

        var encodedUri = encodeURI(csvContent);
        var link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "sales_report.csv");
        document.body.appendChild(link); // Required for FF

        link.click();
    }

    // Function to download graph as image
    function downloadGraph() {
        var a = document.createElement('a');
        a.href = document.getElementById('profitLossChart').toDataURL('image/jpg');
        a.download = 'profit_loss_graph.jpg';
        a.click();
    }
</script>  
   <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
    <!-- Bootstrap core JavaScript-->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="../js/sb-admin-2.min.js"></script>

</body>

</html>