<?php

session_start();

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


require_once "config.php";


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


if(!$id){
    die("Invalid vendor");
}



// Vendor

$stmt=$pdo->prepare("
SELECT *
FROM vendors
WHERE id=?
");

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

$vendor=$stmt->fetch();


if(!$vendor){
    die("Vendor not found");
}




// Expenses

$stmt=$pdo->prepare("

SELECT

e.*,

c.category_name


FROM expenses e


LEFT JOIN expense_categories c

ON e.category_id=c.id


WHERE e.vendor_id=?


ORDER BY e.expense_date DESC


");


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

$expenses=$stmt->fetchAll();





$total=$pdo->prepare("

SELECT COALESCE(SUM(total),0)

FROM expenses

WHERE vendor_id=?

");


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

$totalAmount=$total->fetchColumn();


?>


<!DOCTYPE html>

<html>

<head>

<title>
Vendor Statement
</title>


<style>

body{

font-family:Arial;
margin:40px;

}


h1,h2{

text-align:center;

}



.info{

margin-bottom:20px;

}



table{

width:100%;
border-collapse:collapse;

}



th{

background:#065f46;
color:white;
padding:10px;

}



td{

padding:10px;
border:1px solid #ddd;

}



.total{

font-size:20px;
font-weight:bold;
text-align:right;

}



.print{

margin-top:30px;
text-align:center;

}


@media print{

.print{

display:none;

}

}


</style>


</head>


<body>



<h1>

Vendor Statement

</h1>


<h2>

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

</h2>




<div class="info">

<strong>
Contact:
</strong>

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

<br>


<strong>
Phone:
</strong>

<?=$vendor['phone']?>


<br>


<strong>
Email:
</strong>

<?=$vendor['email']?>


</div>





<p>

<strong>
Period:
</strong>

<?=date("d M Y")?>

</p>





<table>


<tr>

<th>Date</th>

<th>Category</th>

<th>Description</th>

<th>Payment</th>

<th>Amount</th>

</tr>



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


<tr>


<td>

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

</td>


<td>

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

</td>


<td>

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

</td>


<td>

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

</td>



<td>

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

</td>


</tr>


<?php } ?>


</table>




<p class="total">

Total Paid:

MWK <?=number_format($totalAmount)?>

</p>




<div class="print">

<button onclick="window.print()">

Print

</button>

</div>



<script>

window.onload=function(){

window.print();

}

</script>


</body>

</html>