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

// Check if user is logged in
if (!isset($_SESSION['username'])) {
    echo "<script>alert('Please log in to record an owing.'); window.location.href = 'login.php';</script>";
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $person_name = $_POST['person_name'];
    $phone_number = $_POST['phone_number']; // Add this line
    $amount = $_POST['amount'];
    $owing_type = $_POST['owing_type'];
    $description = $_POST['description'];
    $due_date = $_POST['due_date'];
    $created_by = $_SESSION['username'];  // Retrieve username from session

    $sql = "INSERT INTO owings (person_name, phone_number, amount, owing_type, description, due_date, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)";
    $stmt = $pdo->prepare($sql);
    if ($stmt->execute([$person_name, $phone_number, $amount, $owing_type, $description, $due_date, $created_by])) {
        echo "<script>alert('Owing record saved successfully.'); window.location.href = 'owing_management.php';</script>";
    } else {
        echo "<script>alert('Failed to save owing record.');</script>";
    }
}
?>
