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

// Make sure no output before headers
$guest_id = intval($_GET['guest_id'] ?? 0);
$type     = $_GET['type'] ?? '';
$user     = $_SESSION['username'] ?? 'Unknown User'; // Who is deleting

if (!$guest_id || !$type) {
    header("Location: payments.php?msg=" . urlencode("Invalid parameters."));
    exit;
}

// ================== CHECK IF ANY PAYMENTS EXIST ==================
$stmt = $conn->prepare("SELECT SUM(amount) as total_paid FROM payments WHERE guest_id=? AND type=?");
$stmt->bind_param("is", $guest_id, $type);
$stmt->execute();
$paid = $stmt->get_result()->fetch_assoc()['total_paid'] ?? 0;

if ($paid > 0) {
    header("Location: payments.php?guest_id=$guest_id&msg=" . urlencode("Cannot remove charge '$type'. Payments have already been made (".number_format($paid,2)." MK)."));
    exit;
}

// ================== CHECK IF ALREADY REMOVED ==================
$check_stmt = $conn->prepare("SELECT id FROM guest_removed_charges WHERE guest_id=? AND type=?");
$check_stmt->bind_param("is", $guest_id, $type);
$check_stmt->execute();
$check_res = $check_stmt->get_result();

if ($check_res->num_rows > 0) {
    header("Location: payments.php?guest_id=$guest_id&msg=" . urlencode("Charge '$type' already removed"));
    exit;
}

// ================== REMOVE CHARGE ==================
$insert_stmt = $conn->prepare("INSERT INTO guest_removed_charges (guest_id, type) VALUES (?, ?)");
$insert_stmt->bind_param("is", $guest_id, $type);

if ($insert_stmt->execute()) {

    // ================== SEND EMAIL ==================
    $guest_info = $conn->query("SELECT name, phone FROM guests WHERE id=$guest_id")->fetch_assoc();
    $guest_name = $guest_info['name'] ?? 'Unknown Guest';
    $guest_phone = $guest_info['phone'] ?? '-';

    $to = "giantplusmw@gmail.com";
    $subject = "Guest Charge Removed: $type";
    $message = "
    Hello GiantPlus Team,

    A charge has been removed from a guest's account.

    Details:
    -------------------------
    Guest Name: $guest_name
    Guest Phone: $guest_phone
    Charge Type: $type
    Amount Paid Before Removal: ".number_format($paid,2)." MK
    Removed By: $user
    Removed 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);

    header("Location: payments.php?guest_id=$guest_id&msg=" . urlencode("Charge '$type' removed successfully"));
    exit;

} else {
    header("Location: payments.php?guest_id=$guest_id&msg=" . urlencode("Error removing charge: " . $insert_stmt->error));
    exit;
}
