<?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("ssssss", $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();
}

// === Edit Expense ===
if (isset($_POST['edit_expense_btn'])) {
    $expense_id      = intval($_POST['expense_id']);
    $paid_to         = inject_checker($connection, ucwords($_POST['edit_paid_to']));
    $paid_for        = inject_checker($connection, ucfirst($_POST['edit_paid_for']));
    $amount_paid     = inject_checker($connection, $_POST['edit_amount']);
    $phone           = inject_checker($connection, $_POST['edit_phone']);

    if (empty($paid_to) || empty($paid_for) || empty($amount_paid) || empty($phone)) {
        $_SESSION['msg'] = "No field should be empty";
        $_SESSION['type'] = "danger";
    } else {
        $stmt = $connection->prepare("UPDATE `expenses` SET `paid_to`=?, `paid_for`=?, `amount_paid`=?, `phone`=? WHERE `id`=?");
        $stmt->bind_param("ssssi", $paid_to, $paid_for, $amount_paid, $phone, $expense_id);

        if ($stmt->execute()) {
            $_SESSION['msg'] = "Expense updated successfully.";
            $_SESSION['type'] = "success";
        } else {
            $_SESSION['msg'] = "Failed to update expense.";
            $_SESSION['type'] = "danger";
        }
        $stmt->close();
    }

    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);
    if ($stmt->execute()) {
        $_SESSION['msg'] = "Expense approved successfully.";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Failed to approve expense.";
        $_SESSION['type'] = "danger";
    }
    $stmt->close();
    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);
    if ($stmt->execute()) {
        $_SESSION['msg'] = "Expense rejected.";
        $_SESSION['type'] = "warning";
    } else {
        $_SESSION['msg'] = "Failed to reject expense.";
        $_SESSION['type'] = "danger";
    }
    $stmt->close();
    header("Location: manage_expenses");
    exit();
}

// === Delete Expense ===
if (isset($_POST['delete_expense_btn'])) {
    $expense_id = intval($_POST['expense_id']);
    $stmt = $connection->prepare("DELETE FROM `expenses` WHERE `id` = ?");
    $stmt->bind_param("i", $expense_id);
    if ($stmt->execute()) {
        $_SESSION['msg'] = "Expense deleted successfully.";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Failed to delete expense.";
        $_SESSION['type'] = "danger";
    }
    $stmt->close();
    header("Location: manage_expenses");
    exit();
}
?>

<div class='page-title'>
	<div>
		<h1><i class='fa fa-money'></i> Manage Expenses</h1>
		<p>Record &amp; Manage 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" required />
				</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" required />
				</div>
				<br />

				<div class="input-group">
					<span class="input-group-addon">Amount Spent</span>
					<input type="number" name="expenses_amount" placeholder="How much did you pay?" class="form-control" required />
				</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" required />
				</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
	// Total approved
	$total_expenses_paid = 0;
	$q = mysqli_query($connection, "SELECT SUM(amount_paid) AS total FROM `expenses` WHERE `status` = 'approved'");
	if ($q && mysqli_num_rows($q) > 0) {
		$r = mysqli_fetch_assoc($q);
		$total_expenses_paid = number_format($r['total']);
	}

	$run_query = mysqli_query($connection, "SELECT * FROM `expenses` ORDER BY `id` DESC");

	if ($run_query && mysqli_num_rows($run_query) > 0):
		$i = 0;
	?>
	<div class='table-responsive'>
		<h3 class='text-center'>Expenses Records</h3>
		<table class='table table-bordered table-hover'>
			<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>ACTIONS</th>
				</tr>
			</thead>
			<tbody>
			<?php while ($result = mysqli_fetch_assoc($run_query)):
				$i++;
				$eid    = $result['id'];
				$status = strtolower($result['status']);
			?>
				<tr>
					<td><?= $i ?></td>
					<td><?= htmlspecialchars($result['paid_to']) ?></td>
					<td><?= htmlspecialchars($result['paid_for']) ?></td>
					<td><?= number_format($result['amount_paid']) ?></td>
					<td><?= htmlspecialchars($result['phone']) ?></td>
					<td><?= htmlspecialchars($result['date']) ?></td>
					<td class="<?= $status ?>"><?= ucfirst($status) ?></td>
					<td>
						<!-- Edit Button (triggers modal) -->
						<button type="button" class="btn btn-warning btn-xs"
							data-toggle="modal"
							data-target="#editModal"
							data-id="<?= $eid ?>"
							data-paid_to="<?= htmlspecialchars($result['paid_to']) ?>"
							data-paid_for="<?= htmlspecialchars($result['paid_for']) ?>"
							data-amount="<?= $result['amount_paid'] ?>"
							data-phone="<?= htmlspecialchars($result['phone']) ?>">
							<i class="fa fa-edit"></i> Edit
						</button>

						<?php if ($status === 'pending'): ?>
						<!-- Approve -->
						<form method="POST" style="display:inline;">
							<input type="hidden" name="expense_id" value="<?= $eid ?>" />
							<button type="submit" name="approve_expense_btn" class="btn btn-success btn-xs"
								onclick="return confirm('Approve this expense?')">
								<i class="fa fa-check"></i> Approve
							</button>
						</form>
						<!-- Reject -->
						<form method="POST" style="display:inline;">
							<input type="hidden" name="expense_id" value="<?= $eid ?>" />
							<button type="submit" name="reject_expense_btn" class="btn btn-default btn-xs"
								onclick="return confirm('Reject this expense?')">
								<i class="fa fa-times"></i> Reject
							</button>
						</form>
						<?php endif; ?>

						<!-- Delete -->
						<form method="POST" style="display:inline;">
							<input type="hidden" name="expense_id" value="<?= $eid ?>" />
							<button type="submit" name="delete_expense_btn" class="btn btn-danger btn-xs"
								onclick="return confirm('Are you sure you want to delete this expense? This cannot be undone.')">
								<i class="fa fa-trash"></i> Delete
							</button>
						</form>
					</td>
				</tr>
			<?php endwhile; ?>
			</tbody>
			<tfoot>
				<tr>
					<th colspan="3">Total Approved Expenses</th>
					<th>₦<?= $total_expenses_paid ?></th>
					<td colspan="4"></td>
				</tr>
			</tfoot>
		</table>
	</div>
	<?php else: ?>
		<h4 class='text-danger text-center'><b>No Expense Records Found</b></h4>
	<?php endif; ?>
</div>

<!-- ===== Edit Expense Modal ===== -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title" id="editModalLabel"><i class="fa fa-edit"></i> Edit Expense</h4>
      </div>
      <form method="POST" action="">
        <div class="modal-body">
          <input type="hidden" name="expense_id" id="edit_expense_id" />

          <div class="form-group">
            <label>Paid To</label>
            <input type="text" name="edit_paid_to" id="edit_paid_to" class="form-control" required />
          </div>
          <div class="form-group">
            <label>Paid For (Reason)</label>
            <input type="text" name="edit_paid_for" id="edit_paid_for" class="form-control" required />
          </div>
          <div class="form-group">
            <label>Amount (₦)</label>
            <input type="number" name="edit_amount" id="edit_amount" class="form-control" required />
          </div>
          <div class="form-group">
            <label>Phone Number</label>
            <input type="text" name="edit_phone" id="edit_phone" class="form-control" required />
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
          <button type="submit" name="edit_expense_btn" class="btn btn-primary">
            <i class="fa fa-save"></i> Save Changes
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
// Populate edit modal with row data
$('#editModal').on('show.bs.modal', function (event) {
    var btn = $(event.relatedTarget);
    $('#edit_expense_id').val(btn.data('id'));
    $('#edit_paid_to').val(btn.data('paid_to'));
    $('#edit_paid_for').val(btn.data('paid_for'));
    $('#edit_amount').val(btn.data('amount'));
    $('#edit_phone').val(btn.data('phone'));
});
</script>
