<?php
session_start();
require_once '../../config/database.php';
require_once '../../customer/includes/notification_functions.php'; // Assuming notification functions are in the customer includes

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$database = new Database();
$db = $database->getConnection();
$action = $_POST['action'] ?? '';

if ($action == 'toggle_status') {
    $card_id = $_POST['card_id'];
    $status = $_POST['status'];
    $note = $_POST['note'] ?? '';

    try {
        // Update card status
        $stmt = $db->prepare("UPDATE cards SET status = ? WHERE id = ?");
        $stmt->execute([$status, $card_id]);
        
        // Get user ID for notification
        $stmt = $db->prepare("SELECT user_id, card_number FROM cards WHERE id = ?");
        $stmt->execute([$card_id]);
        $card = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Create a notification for the user
        $message = $status == 'active' ? 'Your card has been activated.' : 'Your card has been frozen.';
        if (!empty($note)) {
            $message .= ' Note: ' . $note;
        }
        
        createNotification($db, $card['user_id'], 'card_status', 'Card Status Update', $message, 'cards.php');
        
        // Log the action
        $stmt = $db->prepare("INSERT INTO admin_logs (admin_id, action, entity_type, entity_id, details) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            $_SESSION['admin_id'],
            'update_status',
            'card',
            $card_id,
            'Changed card status to ' . $status . '. Card number: ' . $card['card_number']
        ]);
        
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
    }
} elseif ($action == 'delete') {
    $card_id = $_POST['card_id'];
    $reason = $_POST['reason'];

    try {
        // Get card details before deletion for notification
        $stmt = $db->prepare("SELECT user_id, card_number FROM cards WHERE id = ?");
        $stmt->execute([$card_id]);
        $card = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$card) {
            echo json_encode(['success' => false, 'message' => 'Card not found.']);
            exit();
        }
        
        // Delete the card
        $stmt = $db->prepare("DELETE FROM cards WHERE id = ?");
        $stmt->execute([$card_id]);
        
        // Create a notification for the user
        createNotification(
            $db, 
            $card['user_id'], 
            'card_deleted', 
            'Card Deleted', 
            'Your card ending in ' . substr($card['card_number'], -4) . ' has been deleted. Reason: ' . $reason, 
            'cards.php'
        );
        
        // Log the action
        $stmt = $db->prepare("INSERT INTO admin_logs (admin_id, action, entity_type, entity_id, details) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            $_SESSION['admin_id'],
            'delete',
            'card',
            $card_id,
            'Deleted card. Card number: ' . $card['card_number'] . '. Reason: ' . $reason
        ]);
        
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
    }
} elseif ($action == 'create') {
    $user_id = $_POST['user_id'];
    $card_type = $_POST['card_type'];
    $daily_limit = $_POST['daily_limit'];
    
    try {
        // Generate card details
        $card_number = generateCardNumber($card_type);
        $expiry_date = date('m/y', strtotime('+3 years'));
        $cvv = generateCVV();
        
        // Insert new card
        $stmt = $db->prepare("
            INSERT INTO cards (user_id, card_number, card_type, expiry_date, cvv, daily_limit, status) 
            VALUES (?, ?, ?, ?, ?, ?, 'active')
        ");
        $stmt->execute([$user_id, $card_number, $card_type, $expiry_date, $cvv, $daily_limit]);
        
        // Get user details for notification
        $stmt = $db->prepare("SELECT first_name, last_name FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Create a notification for the user
        createNotification(
            $db, 
            $user_id, 
            'card_created', 
            'New Card Created', 
            'A new ' . $card_type . ' card has been created for your account. The card details are available in your cards section.', 
            'cards.php'
        );
        
        // Log the action
        $stmt = $db->prepare("INSERT INTO admin_logs (admin_id, action, entity_type, entity_id, details) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            $_SESSION['admin_id'],
            'create',
            'card',
            $db->lastInsertId(),
            'Created new ' . $card_type . ' card for ' . $user['first_name'] . ' ' . $user['last_name'] . '. Card number: ' . $card_number
        ]);
        
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
}

/**
 * Generate a random card number based on card type
 * 
 * @param string $cardType The type of card (Visa, Mastercard, etc.)
 * @return string The generated card number
 */
function generateCardNumber($cardType) {
    // Define card prefixes based on type
    $prefixes = [
        'Visa' => '4',
        'Mastercard' => '5',
        'American Express' => '3',
        'Discover' => '6'
    ];
    
    $prefix = $prefixes[$cardType] ?? '4'; // Default to Visa if type not found
    
    // Generate random digits
    $length = ($cardType == 'American Express') ? 15 : 16;
    $randomDigits = '';
    for ($i = 0; $i < $length - strlen($prefix); $i++) {
        $randomDigits .= mt_rand(0, 9);
    }
    
    // Format the card number with spaces
    $cardNumber = $prefix . $randomDigits;
    if ($cardType == 'American Express') {
        $cardNumber = substr($cardNumber, 0, 4) . ' ' . substr($cardNumber, 4, 6) . ' ' . substr($cardNumber, 10);
    } else {
        $cardNumber = substr($cardNumber, 0, 4) . ' ' . substr($cardNumber, 4, 4) . ' ' . substr($cardNumber, 8, 4) . ' ' . substr($cardNumber, 12);
    }
    
    return $cardNumber;
}

/**
 * Generate a random CVV
 * 
 * @return string The generated CVV
 */
function generateCVV() {
    return str_pad(mt_rand(0, 999), 3, '0', STR_PAD_LEFT);
}
?>
