<?php
include 'includes/config.php';
session_start();

if (!$_SESSION['email']) {
    header('location:login.php');
}
?><!doctype html>
<html lang="en">

<!-- Mirrored from templates.iqonic.design/vito/html/main/data-table.html by HTTrack Website Copier/3.x [XR&CO'2014], Wed, 21 Aug 2024 10:45:18 GMT -->

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>View Profit/Loss Report</title>
    <!-- Favicon -->
    <link rel="shortcut icon" href="images/favicon.ico" />
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Typography CSS -->
    <link rel="stylesheet" href="css/typography.css">
    <!-- Style CSS -->
    <link rel="stylesheet" href="css/style.css">
    <!-- Responsive CSS -->
    <link rel="stylesheet" href="css/responsive.css">
    <style>
        ion-icon {
            font-size: 20px;
            margin-bottom: -5px;
        }
    </style>
</head>

<body>
    <!-- loader Start -->
    <div id="loading">
        <div id="loading-center">
        </div>
    </div>
    <!-- loader END -->
    <!-- Wrapper Start -->
    <div class="wrapper">
        <!-- Sidebar  -->
        <?php
        include 'includes/sidebar.php';
        ?>
        <!-- TOP Nav Bar -->
        <?php include 'includes/header.php'; ?>
        <!-- TOP Nav Bar END -->
        <!-- Page Content  -->
        <div id="content-page" class="content-page">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-md-12">
                        <h3 class="card-title">Profit / Loss Report</h3>
                    </div>
                    <div class="col-md-12">
<?php
// Dates
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d');
$end_date   = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');

$totalSales = 0;
$grossProfit = 0;

try {
    $params = [
        'start_date' => $start_date,
        'end_date'   => $end_date
    ];

    // Get all sales within date range, now including discount column
$sql = "
    SELECT s.product_id, s.sale_qty, s.price, s.discount, s.date_sale,
           (SELECT pl.purchase_price
            FROM purchase_lines pl
            WHERE pl.product_id = s.product_id
            ORDER BY pl.purchase_date DESC
            LIMIT 1
           ) AS purchase_price
    FROM stock_sale s
    WHERE s.date_sale BETWEEN :start_date AND :end_date
      AND s.customer_id IN (SELECT id FROM contacts)
";


    $stmt = $conn->prepare($sql);
    $stmt->execute($params);

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $saleQty = (float)$row['sale_qty'];
        $salePrice = (float)$row['price'];
        $discount = isset($row['discount']) ? (float)$row['discount'] : 0; // fallback 0 if discount missing
        $purchasePrice = (float)$row['purchase_price'];

        // Calculate sale line total after discount
        $lineTotalSale = ($saleQty * $salePrice) - $discount;
        $lineTotalCost = $saleQty * $purchasePrice;
        $lineProfit    = $lineTotalSale - $lineTotalCost;

        $totalSales += $lineTotalSale;
        $grossProfit += $lineProfit;
    }

} catch (PDOException $e) {
    echo "Query Error: " . $e->getMessage();
    exit;
}

// Net profit = Gross profit (adjust if needed)
$netProfit = $grossProfit;

function formatProfitLoss($amount) {
    $label = ($amount >= 0) ? 'Profit' : 'Loss';
    $class = ($amount >= 0) ? 'text-success' : 'text-danger';
    return "<span class='$class'><strong>$label:</strong> " . number_format(abs($amount), 2) . " ₨</span>";
}
?>


<!-- Bootstrap + Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">

<!-- Date Filter -->
<div class="container mt-4">
    <form method="get" class="row g-3 align-items-center mb-4">
        <div class="col-md-5">
            <label for="start_date" class="form-label fw-semibold">Start Date</label>
            <div class="input-group">
                <span class="input-group-text"><i class="bi bi-calendar-date"></i></span>
                <input type="date" id="start_date" name="start_date" class="form-control"
                       value="<?php echo htmlspecialchars($start_date); ?>" required>
            </div>
        </div>

        <div class="col-md-5">
            <label for="end_date" class="form-label fw-semibold">End Date</label>
            <div class="input-group">
                <span class="input-group-text"><i class="bi bi-calendar-date"></i></span>
                <input type="date" id="end_date" name="end_date" class="form-control"
                       value="<?php echo htmlspecialchars($end_date); ?>" required>
            </div>
        </div>

        <div class="col-md-2 d-grid">
            <label class="form-label invisible">Submit</label>
            <button type="submit" class="btn btn-primary">Search</button>
        </div>
    </form>

    <!-- Display Results -->
    <div class="row">
        <div class="col-sm-6">
            <div class="card p-4 shadow">
                <h5>Total Sales<br><small>(Exc. Tax/Discount)</small></h5>
                <p class="fs-4"><?php echo number_format($totalSales, 2); ?> ₨</p>
            </div>
        </div>

        <div class="col-sm-6">
            <div class="card p-4 shadow">
                <h5>Profit / Loss</h5>
                <p class="fs-4"><?php echo formatProfitLoss($grossProfit); ?></p>
                <p class="fs-5 text-muted">Net: <?php echo formatProfitLoss($netProfit); ?></p>
            </div>
        </div>
    </div>
</div>
                    
             
                               
                               
                                
                             
                               
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
    </div>
    <!-- Wrapper END -->
    <!-- Footer -->
    <?php include 'includes/footer.php'; ?>
    <nav class="iq-float-menu">
        <input type="checkbox" href="#" class="iq-float-menu-open" name="menu-open" id="menu-open" />
        <label class="iq-float-menu-open-button" for="menu-open">
            <span class="lines line-1"></span>
            <span class="lines line-2"></span>
            <span class="lines line-3"></span>
        </label>
        <button class="iq-float-menu-item bg-info" data-toggle="tooltip" data-placement="top" title="Direction Mode"
            data-mode="rtl"><i class="ri-text-direction-r"></i></button>
        <button class="iq-float-menu-item bg-danger" data-toggle="tooltip" data-placement="top" title="Color Mode"
            id="dark-mode" data-active="true"><i class="ri-sun-line"></i></button>
        <button class="iq-float-menu-item bg-warning" data-toggle="tooltip" data-placement="top" title="Comming Soon"><i
                class="ri-palette-line"></i></button>
    </nav>
    <!-- Footer END -->
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="js/jquery.min.js"></script>
    <!-- Rtl and Darkmode -->
    <script src="js/rtl.js"></script>
    <script src="js/customizer.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <!-- Appear JavaScript -->
    <script src="js/jquery.appear.js"></script>
    <!-- Countdown JavaScript -->
    <script src="js/countdown.min.js"></script>
    <!-- Counterup JavaScript -->
    <script src="js/waypoints.min.js"></script>
    <script src="js/jquery.counterup.min.js"></script>
    <!-- Wow JavaScript -->
    <script src="js/wow.min.js"></script>
    <!-- Apexcharts JavaScript -->
    <script src="js/apexcharts.js"></script>
    <!-- Slick JavaScript -->
    <script src="js/slick.min.js"></script>
    <!-- Select2 JavaScript -->
    <script src="js/select2.min.js"></script>
    <!-- Owl Carousel JavaScript -->
    <script src="js/owl.carousel.min.js"></script>
    <!-- Magnific Popup JavaScript -->
    <script src="js/jquery.magnific-popup.min.js"></script>
    <!-- Smooth Scrollbar JavaScript -->
    <script src="js/smooth-scrollbar.js"></script>
    <!-- lottie JavaScript -->
    <script src="js/lottie.js"></script>
    <!-- Chart Custom JavaScript -->
    <script src="js/chart-custom.js"></script>
    <!-- Custom JavaScript -->
    <script src="js/custom.js"></script>
</body>

<!-- Mirrored from templates.iqonic.design/vito/html/main/data-table.html by HTTrack Website Copier/3.x [XR&CO'2014], Wed, 21 Aug 2024 10:45:18 GMT -->

</html>