<?php
/**
 * Tom's Java Jive - Delete Account API
 */

require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';

if (!CustomerAuth::isLoggedIn()) {
    redirect('/login.php');
}

$customer = CustomerAuth::getFullUser();

try {
    // Start transaction
    db()->query("START TRANSACTION");
    
    // Delete wallet transactions
    db()->query("DELETE FROM wallet_transactions WHERE customer_id = :id", ['id' => $customer['customer_id']]);
    
    // Delete reviews
    db()->query("DELETE FROM reviews WHERE customer_id = :id", ['id' => $customer['customer_id']]);
    
    // Delete wishlist
    db()->query("DELETE FROM wishlist WHERE customer_id = :id", ['id' => $customer['customer_id']]);
    
    // Anonymize orders (keep for records but remove personal info)
    db()->query(
        "UPDATE orders SET customer_name = 'Deleted User', customer_email = 'deleted@example.com', 
         shipping_address = NULL, billing_address = NULL WHERE customer_id = :id",
        ['id' => $customer['customer_id']]
    );
    
    // Remove from email subscribers
    db()->query("DELETE FROM email_subscribers WHERE email = :email", ['email' => $customer['email']]);
    
    // Delete customer
    db()->query("DELETE FROM customers WHERE customer_id = :id", ['id' => $customer['customer_id']]);
    
    db()->query("COMMIT");
    
    // Logout
    CustomerAuth::logout();
    
    setFlash('success', 'Your account has been deleted. We\'re sorry to see you go!');
    redirect('/');
    
} catch (Exception $e) {
    db()->query("ROLLBACK");
    setFlash('error', 'Failed to delete account. Please contact support.');
    redirect('/account/profile.php');
}
