<?php
session_start();
include "header.php";
include "db.php";

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$staff_id = $_SESSION['user_id'];
$error = '';
$success = '';

$get_office = $conn->prepare("SELECT office_name FROM staff WHERE staff_id = ?");
$get_office->bind_param("i", $staff_id);
$get_office->execute();
$get_office->bind_result($office_name);
$get_office->fetch();
$get_office->close();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $date = date('Y-m-d');
    $customer_name = !empty($_POST['customer_name']) ? mysqli_real_escape_string($conn, $_POST['customer_name']) : NULL;
    $item_name = mysqli_real_escape_string($conn, $_POST['item_name']);
    $description = !empty($_POST['description']) ? mysqli_real_escape_string($conn, $_POST['description']) : NULL;
    $amount_payable = floatval($_POST['amount_payable']);
    $amount_paid = floatval($_POST['amount_paid']);
    $balance = $amount_payable - $amount_paid;

    $sql = "INSERT INTO sales (staff_id, office_name, sale_date, customer_name, item_name, description, amount_payable, amount_paid, balance) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("isssssddd", $staff_id, $office_name, $date, $customer_name, $item_name, $description, $amount_payable, $amount_paid, $balance);

    if ($stmt->execute()) {
        $success = "Sales entry added successfully.";
    } else {
        $error = "Error: " . $stmt->error;
    }
    $stmt->close();
}
    

?>

<div class="container mt-4">
    <h2>Add Sales</h2>
    <a href="dashboard.php" class="btn btn-secondary mb-3">Back to Dashboard</a>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <form method="post" class="needs-validation" novalidate>
        <div class="mb-3">
            <label for="customer_name" class="form-label">Customer Name (optional)</label>
            <input type="text" class="form-control" id="customer_name" name="customer_name">
        </div>

        <div class="mb-3">
            <label for="item_name" class="form-label">Item Name *</label>
            <input type="text" class="form-control" id="item_name" name="item_name" required>
            <div class="invalid-feedback">Please enter item name.</div>
        </div>

        <div class="mb-3">
            <label for="description" class="form-label">Description (optional)</label>
            <textarea class="form-control" id="description" name="description"></textarea>
        </div>

        <div class="mb-3">
            <label for="amount_payable" class="form-label">Amount Payable *</label>
            <input type="number" step="0.01" class="form-control" id="amount_payable" name="amount_payable" required oninput="updateBalance()">
            <div class="invalid-feedback">Please enter amount payable.</div>
        </div>

        <div class="mb-3">
            <label for="amount_paid" class="form-label">Amount Paid *</label>
            <input type="number" step="0.01" class="form-control" id="amount_paid" name="amount_paid" required oninput="updateBalance()">
            <div class="invalid-feedback">Please enter amount paid.</div>
        </div>

        <div class="mb-3">
            <label for="balance" class="form-label">Balance</label>
            <input type="text" readonly class="form-control" id="balance" name="balance" value="0.00">
        </div>

        <button type="submit" class="btn btn-primary" onclick="return confirm('Are you sure you want to add this sales record?');">Save Sales</button>
    </form>
</div>

<script>
function updateBalance(){
    let payable = parseFloat(document.getElementById("amount_payable").value) || 0;
    let paid = parseFloat(document.getElementById("amount_paid").value) || 0;
    document.getElementById("balance").value = (payable - paid).toFixed(2);
}

// Bootstrap validation example
(() => {
  'use strict'
  const forms = document.querySelectorAll('.needs-validation')
  Array.from(forms).forEach(form => {
    form.addEventListener('submit', event => {
      if (!form.checkValidity()) {
        event.preventDefault()
        event.stopPropagation()
      }
      form.classList.add('was-validated')
    }, false)
  })
})();
</script>

<?php include "footer.php"; ?>
