<?php
include("db/cn.php");
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

        // Fetch Sale Revenue for the current date
        $query = "SELECT SUM(discount_amount) AS revenue 
                  FROM log_user_sales 
                  WHERE DATE(date_time) = '$currentDate'";
        $result = mysqli_query($connection, $query);
        $revenue = ($result && mysqli_num_rows($result) > 0) ? mysqli_fetch_assoc($result)['revenue'] : 0;
        $saleRevenueData[] = $revenue;

        // Fetch Sale Cost for the current date
        $query = "SELECT SUM(sale_cost) AS cost 
                  FROM log_user_sales 
                  WHERE DATE(date_time) = '$currentDate'";
        $result = mysqli_query($connection, $query);
        $cost = ($result && mysqli_num_rows($result) > 0) ? mysqli_fetch_assoc($result)['cost'] : 0;
        $saleCostData[] = $cost;

        // Fetch Expenses for the current date
        $query = "SELECT SUM(amount) AS expense 
                  FROM incash 
                  WHERE DATE(date_time) = '$currentDate'";
        $result = mysqli_query($connection, $query);
        $expense = ($result && mysqli_num_rows($result) > 0) ? mysqli_fetch_assoc($result)['expense'] : 0;
        $expensesData[] = $expense;

        // Calculate Net Profit for the current date
        $profitData[] = $revenue - ($cost + $expense);
    }
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Profit & Loss Report</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="css/custom_css.css" />
     <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<style>
 #table-container-wrapper {
    max-height: 460px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}


@media (max-width: 880px) {
    .col-4 {
        width: 33.33% !important;
    }
    .fa-wifi {
        display: none !important;
    }
    .col-6 {
        width: 50% !important;
    }
}

@media (min-width: 880px) {
    .sidebar {
        width: 100%;
        /* Change sidebar width to 100% on mobile */
        max-width: 120px; /* Set maximum width for the sidebar */
    }
}

@media (min-width: 880px) {
    .main-content {
        margin-left: ; /* Width of the sidebar */
    }
}

/* Added new class to control overlay */
.overlay {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.6);
    z-index: 999;
    display: none; /* Initially hidden */
} /* Custom styles for sidebar */
    .sidebar {
        width: 100px;
        background: linear-gradient(180deg, #3C2F23, #060606);
        position: fixed;
        bottom: 0;
        top: 60px;
        transition: transform 0.3s ease-in-out;
        transform: translateX(0);
        z-index: 1;
        height: 100%;
        border-radius: 0px;
		   transition: transform 0.3s ease-in-out, width 0.3s ease-in-out;
    }

    .sidebar.hide {
        transform: translateX(-100px);
        /* Move sidebar out of the viewport when it is hidden */
    }

    .sidebar .nav-item {
        padding: 10px 0;
        text-align: center;
        position: relative;
        font-size: 12px;
    }

    .sidebar .nav-link {
        color: #fff;
        position: relative;
        /* Ensure icon and text are positioned relative to the nav link */
        z-index: 2;
        /* Ensure the text and icon are above the hover background */
    }

    .sidebar .nav-link i {
        margin-bottom: 5px;
        /* Adjust the margin of the icon */
    }

    /* Custom styles for hover effect */
    .sidebar .nav-item:hover:after {
        background-color: #fff;
        content: '';
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        z-index: 1;
        /* Ensure the hover background is below the text and icon */
    }

    .sidebar .nav-item:hover .nav-link {
        color: #503F2E;
    }

    /* Custom styles for divider */
    .sidebar .nav-item:after {
        content: "";
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 1px;
        background-color: #fff;
        transition: height 0.3s ease-in-out;
        /* Transition effect for smooth animation */
    }

    /* Custom styles for header */
 .header {
		
       background: linear-gradient(100deg, #3C2F23, #060606);
        color: #fff;
        padding: 10px;
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 2;
        height: 69px;
        box-shadow: #FFF 2px 0px 0px 0px;
        /* Ensure header appears above sidebar */
    }

    .header .navbar-toggler {
        color: #fff;
    }

    .header .navbar-toggler-icon {
        color: #fff;
        /* Set the color of the toggle button to white */
    }

    .header .navbar-toggler.white {
        color: #fff !important;
        /* Ensure the toggle button is white */
    }

    .header .navbar-brand {
        color: #fff;
        /* Set navbar brand text color to white */
    }

    .header .nav-item .nav-link {
        color: #fff;
        /* Set nav link text color to white */
    }

.main-content {
    margin-top: 50px; /* Height of fixed header */
    margin-left: 70px; /* Initially, set margin-left to 0 */
    padding-top: 30px; /* Height of fixed header */
    transition: margin-left 0.3s ease-in-out; /* Add transition for smoother animation */
}


    /* Custom styles for search bar */
    .search-container {
        display: flex;
        align-items: center;
       width:100%;
        margin: 2px auto;


        float:left;
	}

/* Updated hide class to apply to the overlay */
.sidebar.hide, .overlay.hide {
    transform: translateX(-100%);
}

    .search-input {
        width: 100%;
        padding: 10px 30px 10px 10px;
        /* Adjust padding to accommodate the icon */
        border: 1px solid #ccc;
        border-radius: 20px;
        font-size: 16px;
    }

    .search-icon {
        position: relative;
        left: -25px;
        /* Adjust the position of the icon */
        color: #aaa;
    }

    .search-icon i {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    }    .btn-dark {
        background: #503F2E;
        color: #fff;
        border: 1px solid #503F2E;
    }

    .btn-dark:hover {
        background: #fff;
        color: #503F2E;
        border: 1px solid #503F2E;
    }

    .bg-dark2 {
        background: #503F2E;
        color: #fff;
    }


    .modal-content {
        animation: modal-animation 0.5s;
    }

    @keyframes modal-animation {
        from {
            opacity: 0;
            transform: scale(0.8);
        }

        to {
            opacity: 1;
            transform: scale(1);
        }
    }	
    		.card {
    transition: all 0.3s ease-in-out;
    padding:10px;
}

.card:hover {
    background: #503F2E;
    color: #fff;
    box-shadow: 0 0 15px rgba(60, 47, 35, 0.7); /* Soft glow effect with color #1A5319 and opacity */
    border-radius: 10px;
	border:1px solid #fff;
	
}
	
</style>
<body>

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

  <div class="main-content">
    <div class="container mt-5">
    <h3 style="width:405px; height:66px; text-align:center; background:#503F2E; color:#fff; padding:12px; border-radius:10px;">Profit & Loss Report</h3><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>
                        <a href="report_p.php"><button type="button" class="btn btn-dark"><i class="fas fa-arrow-left 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>
</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/png');
        a.download = 'profit_loss_graph.png';
        a.click();
    }
</script>

</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

</html>