<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

session_boot();
require_login();

$conn = require __DIR__ . '/../../app/config/database.php';
require_admin($conn);

$id = (int)($_GET['id'] ?? 0);
if (!$id) redirect('customers.php');

/* Load user */
$st = $conn->prepare("SELECT email FROM users WHERE id=? LIMIT 1");
$st->bind_param("i", $id);
$st->execute();
$u = $st->get_result()->fetch_assoc();
if (!$u) redirect('customers.php');

$archivedEmail = "deleted+{$id}@" . parse_url('http://astrabank.local', PHP_URL_HOST);
$conn->begin_transaction();

try {
  $st = $conn->prepare("
    UPDATE users
    SET banned='yes',
        status='suspended',
        email=?,
        full_name=CONCAT(full_name,' (DELETED)')
    WHERE id=?
  ");
  $st->bind_param("si", $archivedEmail, $id);
  $st->execute();

  flash('msg', 'Customer deleted (archived safely).');
  $conn->commit();
} catch (Throwable $e) {
  $conn->rollback();
  flash('err', $e->getMessage());
}

redirect('customers.php');
