<?php

session_start();


if(!isset($_SESSION['user_id'])){

    header("Location: login.php");
    exit;

}


require_once "config.php";



$id=$_GET['id'] ?? 0;



if(!$id){

    header("Location: vendors.php");
    exit;

}




// ==============================
// VENDOR DETAILS
// ==============================


$stmt=$pdo->prepare("

SELECT *

FROM vendors

WHERE id=?

");


$stmt->execute([$id]);


$vendor=$stmt->fetch();



if(!$vendor){

    die("Vendor not found");

}






// ==============================
// SUMMARY STATISTICS
// ==============================


$stmt=$pdo->prepare("

SELECT


COUNT(expenses.id) AS records,


COALESCE(SUM(expenses.total),0) AS total,


COALESCE(AVG(expenses.total),0) AS average,


COALESCE(MAX(expenses.total),0) AS highest,


COALESCE(MIN(expenses.total),0) AS lowest



FROM expenses


WHERE expenses.vendor_id=?



");


$stmt->execute([$id]);


$summary=$stmt->fetch(PDO::FETCH_ASSOC);







// ==============================
// CURRENT MONTH SPENDING
// ==============================


$stmt=$pdo->prepare("

SELECT

COALESCE(SUM(total),0)

FROM expenses


WHERE vendor_id=?


AND MONTH(expense_date)=MONTH(CURRENT_DATE())


AND YEAR(expense_date)=YEAR(CURRENT_DATE())


");


$stmt->execute([$id]);


$thisMonth=$stmt->fetchColumn();







// ==============================
// CURRENT YEAR SPENDING
// ==============================


$stmt=$pdo->prepare("

SELECT

COALESCE(SUM(total),0)


FROM expenses


WHERE vendor_id=?


AND YEAR(expense_date)=YEAR(CURRENT_DATE())


");


$stmt->execute([$id]);


$thisYear=$stmt->fetchColumn();







// ==============================
// LAST TRANSACTION
// ==============================


$stmt=$pdo->prepare("

SELECT MAX(expense_date)

FROM expenses

WHERE vendor_id=?

");


$stmt->execute([$id]);


$lastExpense=$stmt->fetchColumn();







// ==============================
// MONTHLY CHART
// ==============================


$stmt=$pdo->prepare("

SELECT


MONTHNAME(expense_date) AS month,


MONTH(expense_date) AS month_no,


SUM(total) amount



FROM expenses



WHERE vendor_id=?



GROUP BY MONTH(expense_date)



ORDER BY month_no



");


$stmt->execute([$id]);


$monthly=$stmt->fetchAll();







// ==============================
// CATEGORY BREAKDOWN
// ==============================


$stmt=$pdo->prepare("

SELECT


COALESCE(c.category_name,'Unknown') category,


SUM(e.total) amount



FROM expenses e



LEFT JOIN expense_categories c


ON e.category_id=c.id



WHERE e.vendor_id=?



GROUP BY e.category_id



ORDER BY amount DESC



");


$stmt->execute([$id]);


$categories=$stmt->fetchAll();







// ==============================
// PAYMENT METHOD ANALYSIS
// ==============================


$stmt=$pdo->prepare("

SELECT


payment_method,


SUM(total) amount



FROM expenses



WHERE vendor_id=?



GROUP BY payment_method



");


$stmt->execute([$id]);


$payments=$stmt->fetchAll();








// ==============================
// EXPENSE HISTORY
// ==============================


$search=$_GET['search'] ?? '';



$sql="

SELECT


e.*,


c.category_name



FROM expenses e



LEFT JOIN expense_categories c


ON e.category_id=c.id



WHERE e.vendor_id=?



";


$params=[$id];



if($search!=""){


$sql.="

AND

(

e.description LIKE ?

OR c.category_name LIKE ?

OR e.payment_method LIKE ?

)

";


$params[]="%$search%";
$params[]="%$search%";
$params[]="%$search%";


}



$sql.=" ORDER BY e.expense_date DESC";




$stmt=$pdo->prepare($sql);


$stmt->execute($params);


$expenses=$stmt->fetchAll();



?>
<!DOCTYPE html>

<html>

<head>


<meta name="viewport" content="width=device-width,initial-scale=1">


<title>

<?=htmlspecialchars($vendor['vendor_name'])?>

Statement

</title>



<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">


<link rel="stylesheet"

href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">


<link rel="stylesheet"

href="assets/css/sidebar.css">



<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>




<style>


*{

margin:0;
padding:0;
box-sizing:border-box;
font-family:Poppins;

}



body{

background:#f4f7f9;

transition:.3s;

}




body.dark{

background:#111827;
color:white;

}




.content{

margin-left:260px;

padding:25px;

}




.topbar{

display:flex;

align-items:center;

justify-content:space-between;

margin-bottom:20px;

}




.mobile-btn{

display:none;

font-size:25px;

cursor:pointer;

color:#059669;

}




.toggle{

font-size:24px;

cursor:pointer;

color:#059669;

}





.btn{

background:#059669;

color:white;

padding:10px 18px;

border-radius:10px;

text-decoration:none;

display:inline-flex;

align-items:center;

gap:8px;

}



.gray{

background:#64748b;

}





.header-box{


background:white;

padding:25px;

border-radius:18px;

box-shadow:0 5px 20px #0002;

margin-bottom:20px;


}




body.dark .header-box{

background:#1f2937;

}





.vendor-header{


display:flex;

justify-content:space-between;

align-items:center;

flex-wrap:wrap;

gap:15px;


}



.vendor-icon{


width:70px;

height:70px;

border-radius:50%;

background:#ecfdf5;

color:#059669;

display:flex;

align-items:center;

justify-content:center;

font-size:30px;


}





.vendor-info{


display:flex;

align-items:center;

gap:15px;


}





.info-grid{


display:grid;

grid-template-columns:

repeat(auto-fit,minmax(180px,1fr));


gap:15px;

margin-top:20px;


}




.info{


background:#ecfdf5;

padding:15px;

border-radius:12px;


}



.info strong{


display:block;

color:#065f46;


}





.cards{


display:grid;


grid-template-columns:

repeat(auto-fit,minmax(180px,1fr));


gap:15px;


}




.card{


background:white;

padding:18px;

border-radius:15px;

box-shadow:0 5px 20px #0002;


}




body.dark .card{

background:#1f2937;

}




.icon{


height:45px;

width:45px;


background:#ecfdf5;


color:#059669;


border-radius:12px;


display:flex;


align-items:center;


justify-content:center;


font-size:20px;


}





.number{


font-size:22px;

font-weight:bold;

color:#059669;


margin-top:10px;


}




.chart-grid{


display:grid;


grid-template-columns:

repeat(auto-fit,minmax(350px,1fr));


gap:20px;

margin-top:20px;


}





.box{


background:white;


padding:20px;


border-radius:18px;


box-shadow:0 5px 20px #0002;


margin-top:20px;


}




body.dark .box{

background:#1f2937;

}





@media(max-width:768px){



.content{

margin-left:0;

padding:15px;

}



.mobile-btn{

display:block;

}



.cards{


grid-template-columns:repeat(2,1fr);


}



.chart-grid{

grid-template-columns:1fr;

}



.vendor-header{

display:block;

}



.sidebar{

left:-260px;

}



.sidebar.active{

left:0;

}



}



</style>


</head>




<body>



<?php include "sidebar.php"; ?>



<div class="content">





<div class="topbar">


<i class="fa fa-bars mobile-btn"

onclick="openMenu()">

</i>



<h2>

<i class="fa fa-building"></i>

Vendor Statement

</h2>




<i class="fa fa-moon toggle"

onclick="theme()">

</i>



</div>








<!-- VENDOR PROFILE -->


<div class="header-box">


<div class="vendor-header">


<div class="vendor-info">


<div class="vendor-icon">

<i class="fa fa-building"></i>

</div>



<div>


<h2>

<?=htmlspecialchars($vendor['vendor_name'])?>

</h2>


<p>

Expense Account Statement

</p>


</div>


</div>




<a href="javascript:history.back()" 

class="btn gray">


<i class="fa fa-arrow-left"></i>

Back

</a>



</div>







<div class="info-grid">


<div class="info">

<strong>

Contact Person

</strong>

<?=htmlspecialchars($vendor['contact_person'] ?? '-')?>

</div>




<div class="info">

<strong>

Phone

</strong>

<?=htmlspecialchars($vendor['phone'] ?? '-')?>

</div>





<div class="info">

<strong>

Email

</strong>

<?=htmlspecialchars($vendor['email'] ?? '-')?>

</div>




<div class="info">

<strong>

Last Transaction

</strong>

<?=$lastExpense ?? '-'?>

</div>



</div>


</div>









<!-- SUMMARY CARDS -->


<div class="cards">



<div class="card">


<div class="icon">

<i class="fa fa-money-bill"></i>

</div>


<p>Total Paid</p>


<div class="number">

MWK <?=number_format($summary['total'])?>

</div>


</div>






<div class="card">


<div class="icon">

<i class="fa fa-file"></i>

</div>


<p>Transactions</p>


<div class="number">

<?=$summary['records']?>

</div>


</div>






<div class="card">


<div class="icon">

<i class="fa fa-chart-line"></i>

</div>


<p>Average</p>


<div class="number">

MWK <?=number_format($summary['average'])?>

</div>


</div>






<div class="card">


<div class="icon">

<i class="fa fa-arrow-up"></i>

</div>


<p>Highest Payment</p>


<div class="number">

MWK <?=number_format($summary['highest'])?>

</div>


</div>






<div class="card">


<div class="icon">

<i class="fa fa-calendar"></i>

</div>


<p>This Month</p>


<div class="number">

MWK <?=number_format($thisMonth)?>

</div>


</div>





</div>








<!-- CHARTS -->


<div class="chart-grid">



<div class="box">


<h3>

<i class="fa fa-chart-line"></i>

Monthly Spending

</h3>


<br>


<canvas id="monthlyChart"></canvas>



</div>






<div class="box">


<h3>

<i class="fa fa-layer-group"></i>

Categories

</h3>


<br>


<canvas id="categoryChart"></canvas>


</div>





<div class="box">


<h3>

<i class="fa fa-credit-card"></i>

Payment Methods

</h3>


<br>


<canvas id="paymentChart"></canvas>


</div>




</div>

<!-- EXPENSE HISTORY -->


<div class="box">



<div style="
display:flex;
justify-content:space-between;
align-items:center;
flex-wrap:wrap;
gap:10px;
">



<h3>

<i class="fa fa-history"></i>

Expense History

</h3>





<div>


<a class="btn"

href="export_vendor_pdf.php?vendor=<?=$id?>"

target="_blank">

<i class="fa fa-file-pdf"></i>

PDF

</a>





<a class="btn"

href="export_vendor_excel.php?vendor=<?=$id?>"

target="_blank">

<i class="fa fa-file-excel"></i>

Excel

</a>





<a class="btn"

href="print_vendor_statement.php?id=<?=$id?>"

target="_blank">

<i class="fa fa-print"></i>

Print

</a>




</div>


</div>






<br>






<form>


<input type="hidden"

name="id"

value="<?=$id?>">



<input

name="search"

value="<?=htmlspecialchars($search)?>"

placeholder="Search expense description, category or payment..."

style="

width:100%;

padding:12px;

border-radius:10px;

border:1px solid #ddd;

">



<br><br>


<button class="btn">

<i class="fa fa-search"></i>

Search

</button>


</form>







<br>




<div style="overflow:auto;">



<table style="width:100%;border-collapse:collapse;">



<thead>


<tr>


<th style="
background:#065f46;
color:white;
padding:12px;
">

Date

</th>



<th style="
background:#065f46;
color:white;
padding:12px;
">

Category

</th>



<th style="
background:#065f46;
color:white;
padding:12px;
">

Description

</th>




<th style="
background:#065f46;
color:white;
padding:12px;
">

Payment

</th>




<th style="
background:#065f46;
color:white;
padding:12px;
">

Amount

</th>


</tr>


</thead>





<tbody>


<?php foreach($expenses as $e){ ?>


<tr>



<td style="padding:12px;border-bottom:1px solid #ddd;">

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

</td>





<td style="padding:12px;border-bottom:1px solid #ddd;">

<?=htmlspecialchars(
$e['category_name'] ?? 'Unknown'
)?>

</td>






<td style="padding:12px;border-bottom:1px solid #ddd;">

<?=htmlspecialchars(
$e['description']
)?>

</td>






<td style="padding:12px;border-bottom:1px solid #ddd;">

<span style="
background:#dcfce7;
padding:5px 12px;
border-radius:20px;
">

<?=$e['payment_method']?>

</span>

</td>






<td style="
padding:12px;
border-bottom:1px solid #ddd;
font-weight:bold;
">


MWK <?=number_format($e['total'])?>


</td>



</tr>


<?php } ?>



</tbody>


</table>



</div>


</div>







</div>









<script>


// ==========================
// MOBILE MENU
// ==========================


function openMenu(){


document.getElementById("sidebar")

.classList.add("active");


}






// ==========================
// DARK MODE
// ==========================


function theme(){


document.body.classList.toggle("dark");


localStorage.setItem(

"dark",

document.body.classList.contains("dark")

);


}



if(localStorage.getItem("dark")=="true"){


document.body.classList.add("dark");


}








// ==========================
// MONTHLY CHART
// ==========================


new Chart(

document.getElementById("monthlyChart"),

{


type:"line",


data:{


labels:

<?=json_encode(array_column($monthly,'month'))?>,


datasets:[{


label:"Amount",


data:

<?=json_encode(array_column($monthly,'amount'))?>


}]


}


}

);









// ==========================
// CATEGORY CHART
// ==========================


new Chart(

document.getElementById("categoryChart"),

{


type:"doughnut",


data:{


labels:

<?=json_encode(array_column($categories,'category'))?>,


datasets:[{


data:

<?=json_encode(array_column($categories,'amount'))?>


}]


}



}

);









// ==========================
// PAYMENT CHART
// ==========================


new Chart(

document.getElementById("paymentChart"),


{


type:"pie",


data:{


labels:

<?=json_encode(array_column($payments,'payment_method'))?>,


datasets:[{


data:

<?=json_encode(array_column($payments,'amount'))?>


}]


}



}

);



</script>






</body>

</html>