<?php
session_start(); // Start the session to access session variables
require_once '../config/db.php';

// Check if user is logged in
if (!isset($_SESSION['username'])) {
    echo "<script>alert('You must be logged in to make a payment.'); window.location.href = 'login.php';</script>";
    exit();
}

$added_by = $_SESSION['username']; // Get the username from the session
$supply_id = $_POST['supply_id'];
$amount_paid = $_POST['amount_paid'];

// Insert payment into the supply_payments table
$sql = "INSERT INTO supply_payments (supply_id, amount_paid, payment_date, added_by) 
        VALUES (?, ?, NOW(), ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$supply_id, $amount_paid, $added_by]);

// Update total paid in the supplies table
$sql = "UPDATE supplies SET total_paid = total_paid + ? WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$amount_paid, $supply_id]);

// Redirect back to the supply details page with a success message
header("Location: view_supply.php?supply_id=$supply_id&success=Payment recorded successfully.");
exit();
?>
