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

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

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

// Fetch sale details before archiving
$sale = $conn->query("SELECT s.id, s.customer_id, s.total_amount, c.name AS customer_name, c.phone AS customer_phone
                      FROM sales s
                      LEFT JOIN customers c ON s.customer_id = c.id
                      WHERE s.id = $sale_id")->fetch_assoc();

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

// Archive the sale
$stmt = $conn->prepare("UPDATE sales SET archived=1 WHERE id=?");
$stmt->bind_param("i", $sale_id);
$archived = $stmt->execute();
$stmt->close();

if ($archived) {
    // ================== SEND EMAIL ==================
    $to = "giantplusmw@gmail.com";
    $subject = "Sale Archived: Sale ID {$sale['id']}";
    $message = "
Hello GiantPlus Team,

A sale has been archived in the system.

Details:
-------------------------
Sale ID: {$sale['id']}
Customer Name: {$sale['customer_name']}
Customer Phone: {$sale['customer_phone']}
Total Amount: ".number_format($sale['total_amount'],2)." MK
Archived By: $user
Archived On: ".date("Y-m-d H:i:s")."
-------------------------

This is an automated notification.

Regards,
Sales 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('Sale archived and email notification sent!'); window.location='sales.php';</script>";
    exit;
} else {
    echo "<script>alert('Error archiving sale: ".$conn->error."'); window.location='sales.php';</script>";
    exit;
}
