<?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
include 'includes/config.php';

// Dates
$start_date = $_GET['start_date'] ?? date('Y-m-d');
$end_date   = $_GET['end_date'] ?? date('Y-m-d');

$totalSales = 0;
$totalQtySold = 0;
$totalPurchaseCost = 0;
$totalPurchaseValue = 0;
$grossProfit = 0;
$totalExpense = 0;

$where = "
    ss.invoice NOT LIKE '%Audit%' 
    AND ss.invoice NOT LIKE '%Open Stock%' 
    AND (c.name IS NULL OR c.name NOT LIKE '%Audit Sale%')
    AND DATE(ss.date_sale) BETWEEN :start_date AND :end_date
";

try {
    $sql = "
        SELECT 
            SUM(ss.sale_qty) AS total_qty,
            SUM((ss.sale_qty * ss.price) - ss.discount) AS total_sales,
            SUM(
                ss.sale_qty * (
                    SELECT COALESCE(AVG(pl.purchase_price), 0)
                    FROM purchase_lines pl
                    WHERE pl.product_id = ss.product_id
                )
            ) AS total_purchase_cost
        FROM stock_sale ss
        LEFT JOIN contacts c ON ss.customer_id = c.id
        WHERE $where
    ";

    $stmt = $conn->prepare($sql);
    $stmt->execute(['start_date' => $start_date, 'end_date' => $end_date]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    $totalSales        = (float)($row['total_sales'] ?? 0);
    $totalQtySold      = (float)($row['total_qty'] ?? 0);
    $totalPurchaseCost = (float)($row['total_purchase_cost'] ?? 0);

    $grossProfit = $totalSales - $totalPurchaseCost;

    $stmt_exp = $conn->prepare("
        SELECT SUM(amount) AS total_expense 
        FROM expense 
        WHERE DATE(date) BETWEEN :start_date AND :end_date
    ");
    $stmt_exp->execute(['start_date' => $start_date, 'end_date' => $end_date]);
    $row_exp = $stmt_exp->fetch(PDO::FETCH_ASSOC);
    $totalExpense = (float)($row_exp['total_expense'] ?? 0);

    $stmt_purchase = $conn->prepare("
        SELECT 
            SUM(quantity * purchase_price) AS total_purchase_value
        FROM purchase_lines
        WHERE DATE(purchase_date) BETWEEN :start_date AND :end_date
    ");
    $stmt_purchase->execute(['start_date' => $start_date, 'end_date' => $end_date]);
    $row_purchase = $stmt_purchase->fetch(PDO::FETCH_ASSOC);
    $totalPurchaseValue = (float)($row_purchase['total_purchase_value'] ?? 0);

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

$netProfit = $grossProfit - $totalExpense;

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>";
}
?>

<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">

<div class="container mt-4">
    <h3 class="mb-4 text-primary"><i class="bi bi-graph-up-arrow"></i> Profit & Loss Report</h3>

    <form method="get" class="row g-3 mb-4 bg-light p-3 rounded shadow-sm">
        <div class="col-md-5">
            <label for="start_date" class="form-label fw-semibold">Start Date</label>
            <input type="date" id="start_date" name="start_date" class="form-control"
                   value="<?php echo htmlspecialchars($start_date); ?>" required>
        </div>
        <div class="col-md-5">
            <label for="end_date" class="form-label fw-semibold">End Date</label>
            <input type="date" id="end_date" name="end_date" class="form-control"
                   value="<?php echo htmlspecialchars($end_date); ?>" required>
        </div>
        <div class="col-md-2 d-grid align-items-end">
            <button type="submit" class="btn btn-primary"><i class="bi bi-search"></i> Search</button>
        </div>
    </form>

    <div class="row g-4">
        <!-- Total Sales -->
        <div class="col-md-4">
            <div class="card p-4 shadow-sm border-start border-primary border-4">
                <h5>Total Sales</h5>
                <p class="fs-4 fw-bold"><?php echo number_format($totalSales, 2); ?> ₨</p>
                <small class="text-muted">After Discount</small>
            </div>
        </div>

        <!-- Total Quantity Sold -->
        <div class="col-md-4">
            <div class="card p-4 shadow-sm border-start border-success border-4">
                <h5>Total Quantity Sold</h5>
                <p class="fs-4 fw-bold"><?php echo number_format($totalQtySold); ?> Pieces</p>
            </div>
        </div>

        <!-- Purchase Cost of Sold Items -->
        <!-- <div class="col-md-4">
            <div class="card p-4 shadow-sm border-start border-warning border-4">
                <h5>Total Purchase Cost (Sold Items)</h5>
                <p class="fs-4 fw-bold"><?php echo number_format($totalPurchaseCost, 2); ?> ₨</p>
                <small class="text-muted">(Purchase Price × Quantity Sold)</small>
            </div>
        </div> -->

        <!-- Overall Purchase -->
        <div class="col-md-4">
            <div class="card p-4 shadow-sm border-start border-secondary border-4">
                <h5>Total Purchase (Overall)</h5>
                <p class="fs-4 fw-bold"><?php echo number_format($totalPurchaseValue, 2); ?> ₨</p>
                <small class="text-muted">From Purchase Records</small>
            </div>
        </div>

        <!-- Gross Profit -->
        <div class="col-md-4">
            <div class="card p-4 shadow-sm border-start border-info border-4">
                <h5>Gross Profit</h5>
                <p class="fs-4 fw-bold"><?php echo formatProfitLoss($grossProfit); ?></p>
            </div>
        </div>

        <!-- Total Expenses -->
        <div class="col-md-4">
            <div class="card p-4 shadow-sm border-start border-danger border-4">
                <h5>Total Expenses</h5>
                <p class="fs-4 fw-bold text-danger"><?php echo number_format($totalExpense, 2); ?> ₨</p>
            </div>
        </div>

        <!-- Net Profit / Loss -->
        <div class="col-md-4">
            <div class="card p-4 shadow-sm border-start border-success border-4">
                <h5>Net Profit / Loss</h5>
                <p class="fs-4 fw-bold"><?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>