<?php

session_start();


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

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

}


require_once "config.php";




// SAVE EXPENSE
// SAVE EXPENSE

if(isset($_POST['save'])){


$date=$_POST['expense_date'];

$category=$_POST['category_id'];

$vendor=$_POST['vendor_id'];

$description=$_POST['description'];

$total=$_POST['total'];

$payment=$_POST['payment_method'];

$item=$_POST['item_id'] ?? null;




// INSERT EXPENSE

$stmt=$pdo->prepare("

INSERT INTO expenses

(
expense_date,
category_id,
vendor_id,
item_id,
description,
total,
payment_method,
created_by

)

VALUES

(?,?,?,?,?,?,?,?)

");



$stmt->execute([

$date,
$category,
$vendor,
$item,
$description,
$total,
$payment,
$_SESSION['user_id']

]);





// =============================
// GET INSERTED EXPENSE DETAILS
// =============================


$expense_id=$pdo->lastInsertId();



$stmt=$pdo->prepare("

SELECT

e.*,

c.category_name,

v.vendor_name,

i.item_name


FROM expenses e


LEFT JOIN expense_categories c

ON e.category_id=c.id


LEFT JOIN vendors v

ON e.vendor_id=v.id


LEFT JOIN expense_items i

ON e.item_id=i.id


WHERE e.id=?

");


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


$expense=$stmt->fetch();





// =============================
// GET SETTINGS
// =============================


$stmt=$pdo->query("

SELECT *

FROM settings

LIMIT 1

");


$settings=$stmt->fetch();



$companyName=$settings['company_name'] ?? "Expense System";

$companyEmail=$settings['email'] ?? "";

$address=$settings['address'] ?? "";

$phone=$settings['phone'] ?? "";

$currency=$settings['currency'] ?? "MWK";





// =============================
// EMAIL RECIPIENTS
// =============================


$emails=[];



if(!empty($companyEmail)){

    $emails[]=$companyEmail;

}



$emails[]="giantplusmw@gmail.com";






// =============================
// EMAIL CONTENT
// =============================


$subject="New Expense Added - ".$companyName;



$message="

<html>

<head>

<style>


body{

font-family:Arial,Helvetica,sans-serif;

background:#f4f7f9;

padding:20px;

}


.container{

max-width:650px;

margin:auto;

background:white;

border-radius:12px;

overflow:hidden;

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

}



.header{

background:#059669;

color:white;

padding:25px;

text-align:center;

}



.content{

padding:25px;

}



table{

width:100%;

border-collapse:collapse;

}



td{

padding:12px;

border-bottom:1px solid #eee;

}



.label{

font-weight:bold;

color:#065f46;

}



.amount{

font-size:20px;

font-weight:bold;

color:#059669;

}



.footer{

background:#f8fafc;

padding:20px;

text-align:center;

font-size:12px;

color:#64748b;

}


</style>

</head>


<body>



<div class='container'>



<div class='header'>


<h2>
New Expense Created
</h2>


<p>
".$companyName."
</p>


</div>




<div class='content'>


<p>
A new expense has been recorded in the system.
</p>




<table>



<tr>

<td class='label'>
Expense Date
</td>

<td>
".$expense['expense_date']."
</td>

</tr>



<tr>

<td class='label'>
Category
</td>

<td>
".$expense['category_name']."
</td>

</tr>




<tr>

<td class='label'>
Vendor
</td>

<td>
".($expense['vendor_name'] ?? 'No Vendor')."
</td>

</tr>




<tr>

<td class='label'>
Item
</td>

<td>
".($expense['item_name'] ?? 'N/A')."
</td>

</tr>




<tr>

<td class='label'>
Description
</td>

<td>
".htmlspecialchars($expense['description'])."
</td>

</tr>




<tr>

<td class='label'>
Amount
</td>


<td class='amount'>

".$currency." ".number_format($expense['total'])."

</td>

</tr>




<tr>

<td class='label'>
Payment Method
</td>


<td>
".$expense['payment_method']."
</td>

</tr>




<tr>

<td class='label'>
Created By
</td>


<td>

User ID ".$_SESSION['user_id']."

</td>

</tr>



</table>



</div>




<div class='footer'>


<strong>

".$companyName."

</strong>


<br>


".$address."


<br>


".$phone."


<br>


".$companyEmail."



<br><br>


Automated Expense Management Notification


</div>



</div>



</body>


</html>

";






// =============================
// EMAIL HEADERS
// =============================


$headers="MIME-Version: 1.0\r\n";

$headers.="Content-type:text/html;charset=UTF-8\r\n";


if(!empty($companyEmail)){


$headers.="From: ".$companyName." <".$companyEmail.">\r\n";


}else{


$headers.="From: noreply@yourdomain.com\r\n";


}





// =============================
// SEND EMAIL
// =============================


foreach($emails as $email){


mail(

$email,

$subject,

$message,

$headers

);


}





$_SESSION['success']="Expense added successfully";


header("Location: expenses.php");

exit;


}





// CATEGORIES


$categories=$pdo->query("

SELECT *

FROM expense_categories

WHERE status=1

ORDER BY category_name

")->fetchAll();






// VENDORS


$vendors=$pdo->query("

SELECT *

FROM vendors

WHERE status=1

ORDER BY vendor_name

")->fetchAll();



// ITEMS

$items=$pdo->query("

SELECT *

FROM expense_items

WHERE status=1

ORDER BY item_name

")->fetchAll();

?>

<!DOCTYPE html>

<html>

<head>


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


<title>
Add Expense
</title>



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


<link rel="stylesheet" href="assets/css/sidebar.css">


<link rel="stylesheet"

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



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

justify-content:space-between;

align-items:center;

margin-bottom:20px;

}





.mobile-btn{

display:none;

font-size:25px;

cursor:pointer;

color:#065f46;

}



.toggle{

font-size:25px;

cursor:pointer;

color:#059669;

}




.card{

background:white;

padding:25px;

border-radius:18px;

max-width:750px;

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

}




body.dark .card{

background:#1f2937;

}




.title{

display:flex;

gap:10px;

align-items:center;

color:#065f46;

margin-bottom:20px;

}





.form-grid{

display:grid;

grid-template-columns:1fr 1fr;

gap:15px;

}





.form-group{

margin-bottom:15px;

}




.full{

grid-column:1/-1;

}





label{

font-weight:600;

font-size:14px;

display:block;

margin-bottom:6px;

}



input,
select,
textarea{


width:100%;

padding:12px;

border-radius:10px;

border:1px solid #ddd;

outline:none;

}




textarea{

height:120px;

resize:none;

}




.buttons{

display:flex;

gap:10px;

margin-top:20px;

}




.btn{

background:#059669;

color:white;

border:none;

padding:12px 22px;

border-radius:10px;

cursor:pointer;

}




.back{

background:#64748b;

color:white;

padding:12px 22px;

border-radius:10px;

text-decoration:none;

}





.overlay{

display:none;

position:fixed;

inset:0;

background:#0008;

z-index:999;

}




.overlay.show{

display:block;

}





@media(max-width:768px){



.content{

margin-left:0;

padding:15px;

}





.mobile-btn{

display:block;

}





.sidebar{

left:-260px;

}



.sidebar.active{

left:0;

}




.form-grid{

grid-template-columns:1fr;

}




.buttons{

flex-direction:column;

}




.btn,
.back{

width:100%;

text-align:center;

}



}




</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-plus-circle"></i>

Add Expense

</h2>





<i class="fa fa-moon toggle"
onclick="theme()"></i>




</div>






<div class="card">



<div class="title">

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

<h3>
Expense Details
</h3>

</div>






<form method="POST">





<div class="form-grid">





<div class="form-group">


<label>
Expense Date
</label>


<input type="date"

name="expense_date"

value="<?=date('Y-m-d')?>"

required>


</div>







<div class="form-group">


<label>
Amount
</label>


<input type="number"

name="total"

placeholder="Enter amount"

required>


</div>







<div class="form-group">


<label>
Category
</label>


<select name="category_id" required>


<option value="">
Select Category
</option>



<?php foreach($categories as $c){ ?>


<option value="<?=$c['id']?>">

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

</option>


<?php } ?>



</select>


</div>








<div class="form-group">


<label>
Vendor
</label>



<select id="vendor" name="vendor_id">

<option value="">
Select Vendor
</option>

<?php foreach($vendors as $v){ ?>

<option value="<?=$v['id']?>">
<?=$v['vendor_name']?>
</option>

<?php } ?>

</select>


</div>




<div class="form-group">


<label>
Expense Item / Asset
</label>


<select name="item_id">


<option value="">
No Item
</option>


<?php foreach($items as $i){ ?>


<option value="<?=$i['id']?>">

<?=$i['item_name']?> 

<?php if($i['registration_no']){ ?>

(<?=$i['registration_no']?>)

<?php } ?>


</option>


<?php } ?>


</select>


</div>


<div class="form-group">


<label>
Payment Method
</label>



<select name="payment_method" required>


<option value="">
Select Payment
</option>


<option>
Cash
</option>


<option>
Bank
</option>


<option>
Mobile Money
</option>


<option>
Card
</option>



</select>



</div>








<div class="form-group full">


<label>
Description
</label>



<textarea name="description"

placeholder="Expense description"></textarea>


</div>




</div>







<div class="buttons">


<button class="btn"
name="save">


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

Save Expense


</button>


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

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

Back

</a>



</div>





</form>



</div>



</div>







<script>


function openMenu(){

document.getElementById("sidebar")
.classList.add("active");


document.getElementById("overlay")
.classList.add("show");

}




function closeMenu(){

document.getElementById("sidebar")
.classList.remove("active");


document.getElementById("overlay")
.classList.remove("show");

}





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


}


document.getElementById("noVendor").onclick=function(){

let vendor=document.getElementById("vendor");

if(this.checked){

vendor.disabled=true;
vendor.value="";

}else{

vendor.disabled=false;

}

}
</script>




</body>

</html>