<?php
include 'includes/auth.php';
include 'db.php';

$user = $_SESSION['username'] ?? 'Unknown User'; // Who is deleting
$id = intval($_GET['id']);

if (!$id) {
    echo "<script>alert('Payment ID not specified!'); window.location='payments.php';</script>";
    exit;
}

// Fetch payment details before deletion
$payment = $conn->query("SELECT p.amount, p.type, g.name AS guest_name, g.phone 
                         FROM payments p 
                         LEFT JOIN guests g ON p.guest_id = g.id 
                         WHERE p.id = $id")->fetch_assoc();

if (!$payment) {
    echo "<script>alert('Payment not found!'); window.location='payments.php';</script>";
    exit;
}

// Delete the payment
$stmt = $conn->prepare("DELETE FROM payments WHERE id=?");
$stmt->bind_param("i", $id);
$deleted = $stmt->execute();
$stmt->close();

if ($deleted) {
    // ================== SEND EMAIL ==================
    $to = "giantplusmw@gmail.com";
    $subject = "Payment Deleted: {$payment['type']}";
    $message = "
Hello GiantPlus Team,

A payment has been deleted from the system.

Details:
-------------------------
Guest Name: {$payment['guest_name']}
Guest Phone: {$payment['phone']}
Payment Type: {$payment['type']}
Amount: ".number_format($payment['amount'],2)." MK
Deleted By: $user
Deleted On: ".date("Y-m-d H:i:s")."
-------------------------

This is an automated notification.

Regards,
Hotel Management System
";

    $headers = "From: cloud@gianterp.space\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

    mail($to, $subject, $message, $headers);

    echo "<script>alert('Payment deleted and email notification sent!'); window.location='payments.php';</script>";
    exit;
} else {
    echo "<script>alert('Error deleting payment: ".$conn->error."'); window.location='payments.php';</script>";
    exit;
}
