<?php
if (session_status() === PHP_SESSION_NONE) session_start();

// === Submit Expense ===
if (isset($_POST['expenses_btn'])) {
    $expenses_paid_to = inject_checker($connection, ucwords($_POST['expenses_paid_to']));
    $expenses_paid_for = inject_checker($connection, ucfirst($_POST['expenses_paid_for']));
    $expenses_amount = inject_checker($connection, $_POST['expenses_amount']);
    $expenses_phone = inject_checker($connection, $_POST['expenses_phone']);
    $status = 'pending';
    $date = date('Y-m-d');

    if (empty($expenses_paid_to) || empty($expenses_paid_for) || empty($expenses_amount) || empty($expenses_phone)) {
        $_SESSION['msg'] = "No field should be empty";
        $_SESSION['type'] = "danger";
    } else {
        $query = "INSERT INTO `expenses` (`paid_to`, `paid_for`, `amount_paid`, `phone`, `date`, `status`) 
                  VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = $connection->prepare($query);
        $stmt->bind_param("sssdss", $expenses_paid_to, $expenses_paid_for, $expenses_amount, $expenses_phone, $date, $status);

        if ($stmt->execute()) {
            $_SESSION['msg'] = "Expense submitted for approval.";
            $_SESSION['type'] = "success";
        } else {
            $_SESSION['msg'] = "Failed to submit expense.";
            $_SESSION['type'] = "danger";
        }
    }

    header("Location: manage_expenses");
    exit();
}

// === Approve Expense ===
if (isset($_POST['approve_expense_btn'])) {
    $expense_id = intval($_POST['expense_id']);
    $stmt = $connection->prepare("UPDATE `expenses` SET `status` = 'approved' WHERE `id` = ?");
    $stmt->bind_param("i", $expense_id);
    $stmt->execute();

    $_SESSION['msg'] = "Expense approved successfully.";
    $_SESSION['type'] = "success";
    header("Location: manage_expenses");
    exit();
}

// === Reject Expense ===
if (isset($_POST['reject_expense_btn'])) {
    $expense_id = intval($_POST['expense_id']);
    $stmt = $connection->prepare("UPDATE `expenses` SET `status` = 'rejected' WHERE `id` = ?");
    $stmt->bind_param("i", $expense_id);
    $stmt->execute();

    $_SESSION['msg'] = "Expense rejected.";
    $_SESSION['type'] = "warning";
    header("Location: manage_expenses");
    exit();
}
?>



<div class='page-title'>
	<div>
		<h1><i class='fa fa-money'></i> Manage Expenses</h1>
		<p>Record Expenses</p>
	</div>	
</div>

<div class='card'>
    <div class="panel panel-primary">
		<div class="panel-heading">
			<h4 class="text-center">Submit Expense for Approval</h4>
		</div>
		<div class="panel-body">
			<form method="POST" action="">
				<div class="input-group">
					<span class="input-group-addon">Paid to</span>
					<input type="text" name="expenses_paid_to" placeholder="Who did you pay?" class="form-control" />
				</div>
				<br />

				<div class="input-group">
					<span class="input-group-addon">Paid for</span>
					<input type="text" name="expenses_paid_for" placeholder="What are you paying for?" class="form-control" />
				</div>
				<br />

				<div class="input-group">
					<span class="input-group-addon">Amount Spent</span>
					<input type="text" name="expenses_amount" placeholder="How much did you pay?" class="form-control" />
				</div>
				<br />

				<div class="input-group">
					<span class="input-group-addon">Phone Number</span>
					<input type="text" name="expenses_phone" placeholder="Enter Phone Number of who you paid" class="form-control" />
				</div>
				<br />

				<input type="submit" name="expenses_btn" value="Submit for Approval" class="btn btn-primary" />
			</form>
		</div>
	</div>

    <style>
		.pending {
			color: orange;
			font-weight: bold;
		}
		.approved {
			color: green;
			font-weight: bold;
		}
		.rejected {
			color: red;
			font-weight: bold;
		}	
	</style>
	<?php
	$query = "SELECT sum(amount_paid) AS total FROM `expenses` WHERE `status` = 'approved'";
	$run_query = mysqli_query($connection, $query);

	$total_expenses_paid = 0;
	if (mysqli_num_rows($run_query) > 0) {
		$result = mysqli_fetch_assoc($run_query);
		$total_expenses_paid = number_format($result['total']);
	}

	$query = "SELECT * FROM `expenses`";
	$run_query = mysqli_query($connection, $query);

	if (mysqli_num_rows($run_query) > 0) {
		$i = 0;
		echo "
			<div class='table-responsive'>
				<h3 class='text-center'>View Expenses Records</h3>
				<table class='table'>
					<thead>
						<tr class='bg-primary'>
							<th>S/N</th>
							<th>RECEIVER</th>
							<th>REASON</th>
							<th>AMOUNT</th>
							<th>PHONE</th>
							<th>DATE</th>
							<th>STATUS</th>
							<th>DATE</th>
						</tr>
					</thead>
		";
		while ($result = mysqli_fetch_assoc($run_query)) {
			$i++;
			$expenses_id = $result['id'];
			$receiver = $result['paid_to'];
			$reason = $result['paid_for'];
			$amount_spent = number_format($result['amount_paid']);
			$receiver_phone = $result['phone'];
			$date_spent = $result['date'];
			$status = ucfirst($result['status']); // Show status (Pending, Approved, Rejected)
			$date = $result['date'];

			echo "
				<tbody>
					<tr>
						<td>{$i}</td>
						<td>{$receiver}</td>
						<td>{$reason}</td>
						<td>{$amount_spent}</td>
						<td>{$receiver_phone}</td>
						<td>{$date_spent}</td>
						<td class='" . strtolower($status) . "'>{$status}</td>
						<td>{$date}</td>
					</tr>
				</tbody>
			";
		}
		echo "
					<tfooter>
						<tr>
							<th colspan='3'>Total Approved Expenses</th>
							<th>{$total_expenses_paid}</th>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
						</tr>
					</tfooter>
				</table>
			</div>
		";
	} else {
		echo "<h4 class='text-danger'><b>No Records</b></h4>";
	}
	?>
</div>
