<?php include 'includes/header.php'; ?>
<?php include 'includes/sidebar.php'; ?>
<?php require 'includes/db_connect.php'; ?>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $subject = mysqli_real_escape_string($conn, $_POST['subject']);
    $summary = mysqli_real_escape_string($conn, $_POST['summary']);
    $type = mysqli_real_escape_string($conn, $_POST['type']);
    $status = 'Pending';
    $tracking_no = 'TRK' . strtoupper(uniqid());
    $reg_date = date('Y-m-d H:i:s');

    $sql = "INSERT INTO mails (tracking_no, subject, summary, type, status, reg_date) 
            VALUES ('$tracking_no', '$subject', '$summary', '$type', '$status', '$reg_date')";

    if ($conn->query($sql)) {
        $success = "Mail Added Successfully with Tracking No: $tracking_no";
    } else {
        $error = "Error adding mail: " . $conn->error;
    }
}
?>

<div class="container mt-4">
    <h4 class="text-orange">Add New Mail Entry</h4>

    <?php if (isset($success)) echo "<div class='alert alert-success'>$success</div>"; ?>
    <?php if (isset($error)) echo "<div class='alert alert-danger'>$error</div>"; ?>

    <form method="post" action="" class="mt-3">
        <div class="mb-3">
            <label class="form-label text-orange">Mail Subject</label>
            <input type="text" name="subject" class="form-control" required>
        </div>

        <div class="mb-3">
            <label class="form-label text-orange">Mail Summary</label>
            <textarea name="summary" class="form-control" rows="3" required></textarea>
        </div>

        <div class="mb-3">
            <label class="form-label text-orange">Mail Type</label>
            <select name="type" class="form-select" required>
                <option value="Incoming">Incoming</option>
                <option value="Outgoing">Outgoing</option>
            </select>
        </div>

        <button type="submit" class="btn btn-orange text-white">Add Mail</button>
    </form>
</div>

<?php include 'includes/footer.php'; ?>
