<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

include_once __DIR__ . "/config/database.php";

include_once __DIR__ . "/includes/header.php";
include_once __DIR__ . "/includes/sidebar.php";
?>

<div class="overlay" id="overlay"></div>

<div class="main-content">

<?php include_once __DIR__ . "/includes/topbar.php"; ?>

<?php

// ================= TODAY SALES =================

$todaySales=0;
$q=mysqli_query($conn,"
SELECT IFNULL(SUM(total),0) total
FROM sales
WHERE DATE(created_at)=CURDATE()
");

if($r=mysqli_fetch_assoc($q)){
    $todaySales=$r['total'];
}


// ================= WEEK SALES =================

$weekSales=0;
$q=mysqli_query($conn,"
SELECT IFNULL(SUM(total),0) total
FROM sales
WHERE YEARWEEK(created_at,1)=YEARWEEK(CURDATE(),1)
");

if($r=mysqli_fetch_assoc($q)){
    $weekSales=$r['total'];
}


// ================= MONTH SALES =================

$monthSales=0;
$q=mysqli_query($conn,"
SELECT IFNULL(SUM(total),0) total
FROM sales
WHERE MONTH(created_at)=MONTH(CURDATE())
AND YEAR(created_at)=YEAR(CURDATE())
");

if($r=mysqli_fetch_assoc($q)){
    $monthSales=$r['total'];
}


// ================= TOTAL REVENUE =================

$revenue=0;

$q=mysqli_query($conn,"
SELECT IFNULL(SUM(total),0) total
FROM sales
");

if($r=mysqli_fetch_assoc($q)){
    $revenue=$r['total'];
}


// ================= EXPENSES =================

$totalExpense=0;

$q=mysqli_query($conn,"
SELECT IFNULL(SUM(amount),0) total
FROM expenses
");

if($r=mysqli_fetch_assoc($q)){
    $totalExpense=$r['total'];
}


// ================= PROFIT =================

$profit=$revenue-$totalExpense;


// ================= TOTAL ORDERS =================

$totalOrders=0;

$q=mysqli_query($conn,"
SELECT COUNT(*) total
FROM sales
");

if($r=mysqli_fetch_assoc($q)){
$totalOrders=$r['total'];
}


// ================= LOW STOCK =================

$lowStock=0;

$q=mysqli_query($conn,"
SELECT COUNT(*) total
FROM products
WHERE stock<=10
");

if($r=mysqli_fetch_assoc($q)){
$lowStock=$r['total'];
}

?>

<div class="container-fluid mt-4">

<div class="row g-4">

<div class="col-xl-3 col-lg-4 col-md-6 col-12">

<div class="card shadow border-0 rounded-4 dashboard-card bg-primary text-white">

<div class="card-body">

<div class="d-flex justify-content-between align-items-center">

<div>

<h6 class="mb-2">Today's Sales</h6>

<h3 class="fw-bold">

₹<?=number_format($todaySales,2)?>

</h3>

</div>

<i class="fas fa-sack-dollar fa-3x opacity-75"></i>

</div>

</div>

</div>

</div>



<div class="col-xl-3 col-lg-4 col-md-6 col-12">

<div class="card shadow border-0 rounded-4 dashboard-card bg-success text-white">

<div class="card-body">

<div class="d-flex justify-content-between align-items-center">

<div>

<h6 class="mb-2">Weekly Sales</h6>

<h3 class="fw-bold">

₹<?=number_format($weekSales,2)?>

</h3>

</div>

<i class="fas fa-chart-line fa-3x opacity-75"></i>

</div>

</div>

</div>

</div>



<div class="col-xl-3 col-lg-4 col-md-6 col-12">

<div class="card shadow border-0 rounded-4 dashboard-card bg-warning text-dark">

<div class="card-body">

<div class="d-flex justify-content-between align-items-center">

<div>

<h6 class="mb-2">Monthly Sales</h6>

<h3 class="fw-bold">

₹<?=number_format($monthSales,2)?>

</h3>

</div>

<i class="fas fa-calendar-alt fa-3x"></i>

</div>

</div>

</div>

</div>



<div class="col-xl-3 col-lg-4 col-md-6 col-12">

<div class="card shadow border-0 rounded-4 dashboard-card bg-danger text-white">

<div class="card-body">

<div class="d-flex justify-content-between align-items-center">

<div>

<h6 class="mb-2">Revenue</h6>

<h3 class="fw-bold">

₹<?=number_format($revenue,2)?>

</h3>

</div>

<i class="fas fa-wallet fa-3x opacity-75"></i>

</div>

</div>

</div>

</div>



<div class="col-xl-4 col-lg-4 col-md-6 col-12">

<div class="card shadow rounded-4 border-0">

<div class="card-body">

<h6 class="text-muted">

Profit

</h6>

<h2 class="fw-bold text-success">

₹<?=number_format($profit,2)?>

</h2>

</div>

</div>

</div>



<div class="col-xl-4 col-lg-4 col-md-6 col-12">

<div class="card shadow rounded-4 border-0">

<div class="card-body">

<h6 class="text-muted">

Orders

</h6>

<h2 class="fw-bold text-primary">

<?=$totalOrders?>

</h2>

</div>

</div>

</div>



<div class="col-xl-4 col-lg-4 col-md-12 col-12">

<div class="card shadow rounded-4 border-0">

<div class="card-body">

<h6 class="text-muted">

Low Stock Products

</h6>

<h2 class="fw-bold text-danger">

<?=$lowStock?>

</h2>

</div>

</div>

</div>

</div>

<div class="row mt-4">
    <div class="col-lg-8 col-md-12 mb-4">

    <div class="card shadow border-0 rounded-4 h-100">

        <div class="card-header bg-white border-0 py-3">
            <h5 class="mb-0 fw-bold">
                <i class="fas fa-chart-line text-primary me-2"></i>
                Monthly Sales Overview
            </h5>
        </div>

        <div class="card-body">

<?php

$months = [];
$salesAmount = [];

for($i=1;$i<=12;$i++){

    $months[] = date("M", mktime(0,0,0,$i,1));

    $total = 0;

    $sql = mysqli_query($conn,"
        SELECT IFNULL(SUM(total),0) total
        FROM sales
        WHERE MONTH(created_at)='$i'
        AND YEAR(created_at)=YEAR(CURDATE())
    ");

    if($row=mysqli_fetch_assoc($sql)){
        $total = $row['total'];
    }

    $salesAmount[] = $total;

}

?>

<div class="chart-container">
    <canvas id="salesChart"></canvas>
</div>

        </div>

    </div>

</div>



<div class="col-lg-4 col-md-12 mb-4">

<div class="card shadow border-0 rounded-4 h-100">

<div class="card-header bg-white border-0 py-3">

<h5 class="fw-bold mb-0">

<i class="fas fa-triangle-exclamation text-danger me-2"></i>

Low Stock Alert

</h5>

</div>

<div class="card-body table-responsive">

<table class="table table-hover align-middle">

<thead>

<tr>

<th>Product</th>
<th>Stock</th>

</tr>

</thead>

<tbody>

<?php

$q=mysqli_query($conn,"
SELECT product_name,stock
FROM products
WHERE stock<=10
ORDER BY stock ASC
LIMIT 8
");

if(mysqli_num_rows($q)>0){

while($row=mysqli_fetch_assoc($q)){

?>

<tr>

<td><?=htmlspecialchars($row['product_name'])?></td>

<td>

<span class="badge bg-danger">

<?=$row['stock']?>

</span>

</td>

</tr>

<?php

}

}else{

?>

<tr>

<td colspan="2" class="text-center text-success">

No Low Stock Products

</td>

</tr>

<?php } ?>

</tbody>

</table>

</div>

</div>

</div>

</div>



<div class="row">

<div class="col-lg-6 mb-4">

<div class="card shadow border-0 rounded-4">

<div class="card-header bg-white border-0">

<h5 class="fw-bold mb-0">

<i class="fas fa-fire text-warning me-2"></i>

Best Selling Products

</h5>

</div>

<div class="card-body table-responsive">

<table class="table table-hover">

<thead>

<tr>

<th>#</th>
<th>Product</th>
<th>Sold</th>

</tr>

</thead>

<tbody>

<?php

$q=mysqli_query($conn,"
SELECT
products.product_name,
SUM(sale_items.quantity) qty
FROM sale_items
INNER JOIN products
ON products.id=sale_items.product_id
GROUP BY sale_items.product_id
ORDER BY qty DESC
LIMIT 8
");

$i=1;

if(mysqli_num_rows($q)>0){

while($row=mysqli_fetch_assoc($q)){

?>

<tr>

<td><?=$i++?></td>

<td><?=htmlspecialchars($row['product_name'])?></td>

<td>

<span class="badge bg-success">

<?=$row['qty']?>

</span>

</td>

</tr>

<?php

}

}else{

?>

<tr>

<td colspan="3" class="text-center">

No Sales Found

</td>

</tr>

<?php } ?>

</tbody>

</table>

</div>

</div>

</div>
<div class="col-lg-6 mb-4">

    <div class="card shadow border-0 rounded-4">

        <div class="card-header bg-white border-0">

            <h5 class="fw-bold mb-0">
                <i class="fas fa-users text-primary me-2"></i>
                Top Customers
            </h5>

        </div>

        <div class="card-body table-responsive">

            <table class="table table-hover align-middle">

                <thead>

                <tr>
                    <th>#</th>
                    <th>Customer</th>
                    <th>Total Purchase</th>
                </tr>

                </thead>

                <tbody>

                <?php

                $customer=mysqli_query($conn,"
                SELECT
                customers.customer_name,
                SUM(sales.total) total_purchase
                FROM sales
                INNER JOIN customers
                ON customers.id=sales.customer_id
                GROUP BY sales.customer_id
                ORDER BY total_purchase DESC
                LIMIT 8
                ");

                $i=1;

                if(mysqli_num_rows($customer)>0){

                    while($row=mysqli_fetch_assoc($customer)){

                ?>

                <tr>

                    <td><?=$i++?></td>

                    <td><?=htmlspecialchars($row['customer_name'])?></td>

                    <td class="fw-bold text-success">
                        ₹<?=number_format($row['total_purchase'],2)?>
                    </td>

                </tr>

                <?php

                    }

                }else{

                ?>

                <tr>

                    <td colspan="3" class="text-center text-muted">
                        No Customer Found
                    </td>

                </tr>

                <?php } ?>

                </tbody>

            </table>

        </div>

    </div>

</div>

</div>



<div class="row">

<div class="col-12">

<div class="card shadow border-0 rounded-4">

<div class="card-header bg-white border-0">

<h5 class="fw-bold mb-0">
<i class="fas fa-receipt me-2 text-success"></i>
Recent Transactions
</h5>

</div>

<div class="card-body table-responsive">

<table class="table table-hover align-middle">

<thead>

<tr>

<th>Invoice</th>
<th>Customer</th>
<th>Payment</th>
<th>Total</th>
<th>Date</th>

</tr>

</thead>

<tbody>

<?php

$sales=mysqli_query($conn,"
SELECT
sales.*,
customers.customer_name
FROM sales
LEFT JOIN customers
ON customers.id=sales.customer_id
ORDER BY sales.id DESC
LIMIT 10
");

if(mysqli_num_rows($sales)>0){

while($row=mysqli_fetch_assoc($sales)){

?>

<tr>

<td>
<?=htmlspecialchars($row['invoice_no'])?>
</td>

<td>
<?=htmlspecialchars($row['customer_name'])?>
</td>

<td>

<span class="badge bg-primary">

<?=htmlspecialchars($row['payment_method'])?>

</span>

</td>

<td class="fw-bold text-success">

₹<?=number_format($row['total'],2)?>

</td>

<td>

<?=date("d M Y",strtotime($row['created_at']))?>

</td>

</tr>

<?php

}

}else{

?>

<tr>

<td colspan="5" class="text-center">

No Transactions Available

</td>

</tr>

<?php } ?>

</tbody>

</table>

</div>

</div>

</div>

</div>

</div>

<script>

const ctx=document.getElementById("salesChart");

if(ctx){

new Chart(ctx,{

type:"line",

data:{

labels:<?=json_encode($months)?>,

datasets:[{

label:"Monthly Sales",

data:<?=json_encode($salesAmount)?>,

fill:true,

tension:.4,

borderWidth:3,

backgroundColor:"rgba(13,110,253,.15)",

borderColor:"#0d6efd",

pointRadius:4

}]

},

options:{

responsive:true,

maintainAspectRatio:false,

plugins:{
legend:{
display:true
}
},

scales:{
y:{
beginAtZero:true
}
}

}

});

}

</script>

<?php
include_once __DIR__ . "/includes/footer.php";
?>