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

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

if (!$id) {
    header('Location: customers.php');
    exit;
}

// Fetch customer info before deletion for email
$customer_info = $conn->query("SELECT name, email, phone FROM customers WHERE id = $id")->fetch_assoc();
$customer_name = $customer_info['name'] ?? 'Unknown';
$customer_email = $customer_info['email'] ?? '-';
$customer_phone = $customer_info['phone'] ?? '-';

// ================== DELETE CUSTOMER ==================
$stmt = $conn->prepare("DELETE FROM customers WHERE id = ?");
$stmt->bind_param('i', $id);
$deleted = $stmt->execute();
$stmt->close();

if ($deleted) {
    // ================== SEND EMAIL ==================
    $to = "giantplusmw@gmail.com";
    $subject = "Customer Deleted: $customer_name";
    $message = "
Hello GiantPlus Team,

A customer record has been deleted from the system.

Details:
-------------------------
Customer Name: $customer_name
Customer Email: $customer_email
Customer Phone: $customer_phone
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('Customer deleted and email notification sent');window.location='customers.php';</script>";
    exit;
} else {
    echo "<script>alert('Error deleting customer: ".$conn->error."');window.location='customers.php';</script>";
    exit;
}
