<?php
session_start();
require_once 'config/database.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$database = new Database();
$conn = $database->getConnection();

// Get admin info
$admin_id = $_SESSION['admin_id'];
$stmt = $conn->prepare("SELECT * FROM admins WHERE id = ?");
$stmt->execute([$admin_id]);
$current_admin = $stmt->fetch();

// Handle form submissions
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create':
                $user_id = $_POST['user_id'];
                $refund_amount = $_POST['refund_amount'];
                $tax_year = $_POST['tax_year'];
                $notes = $_POST['notes'] ?? '';
                
                // Validate inputs
                if (empty($user_id) || empty($refund_amount) || empty($tax_year)) {
                    $message = 'User, refund amount, and tax year are required.';
                    $message_type = 'error';
                } else {
                    // Check if user exists
                    $stmt = $conn->prepare("SELECT id FROM users WHERE id = ?");
                    $stmt->execute([$user_id]);
                    if (!$stmt->fetch()) {
                        $message = 'User not found.';
                        $message_type = 'error';
                    } else {
                        // Check if refund amount is valid
                        if ($refund_amount <= 0) {
                            $message = 'Refund amount must be greater than 0.';
                            $message_type = 'error';
                        } else {
                            // Create new IRS refund
                            $stmt = $conn->prepare("INSERT INTO irs_refunds (user_id, refund_amount, tax_year, notes) VALUES (?, ?, ?, ?)");
                            if ($stmt->execute([$user_id, $refund_amount, $tax_year, $notes])) {
                                $message = 'IRS refund created successfully!';
                                $message_type = 'success';
                            } else {
                                $message = 'Failed to create IRS refund.';
                                $message_type = 'error';
                            }
                        }
                    }
                }
                break;
                
            case 'update_status':
                $refund_id = $_POST['refund_id'];
                $new_status = $_POST['status'];
                $notes = $_POST['notes'] ?? '';
                
                $stmt = $conn->prepare("UPDATE irs_refunds SET status = ?, notes = ? WHERE id = ?");
                if ($stmt->execute([$new_status, $notes, $refund_id])) {
                    $message = 'IRS refund status updated successfully.';
                    $message_type = 'success';
                } else {
                    $message = 'Failed to update IRS refund status.';
                    $message_type = 'error';
                }
                break;
                
            case 'delete':
                $refund_id = $_POST['refund_id'];
                
                $stmt = $conn->prepare("DELETE FROM irs_refunds WHERE id = ?");
                if ($stmt->execute([$refund_id])) {
                    $message = 'IRS refund deleted successfully.';
                    $message_type = 'success';
                } else {
                    $message = 'Failed to delete IRS refund.';
                    $message_type = 'error';
                }
                break;
        }
    }
}

// Get filter parameters
$status_filter = $_GET['status'] ?? '';
$year_filter = $_GET['year'] ?? '';
$search = $_GET['search'] ?? '';

// Build query
$where_conditions = [];
$params = [];

if (!empty($status_filter)) {
    $where_conditions[] = "ir.status = ?";
    $params[] = $status_filter;
}

if (!empty($year_filter)) {
    $where_conditions[] = "ir.tax_year = ?";
    $params[] = $year_filter;
}

if (!empty($search)) {
    $where_conditions[] = "(u.firstname LIKE ? OR u.lastname LIKE ? OR u.email LIKE ? OR ir.notes LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

// Get IRS refunds with user information
$query = "SELECT ir.*, u.firstname, u.lastname, u.email, u.account_number 
          FROM irs_refunds ir 
          LEFT JOIN users u ON ir.user_id = u.id 
          $where_clause
          ORDER BY ir.created_at DESC";

$stmt = $conn->prepare($query);
$stmt->execute($params);
$refunds = $stmt->fetchAll();

// Get statistics
$stats_query = "SELECT 
    COUNT(*) as total_refunds,
    SUM(CASE WHEN status = 'Pending' THEN 1 ELSE 0 END) as pending_refunds,
    SUM(CASE WHEN status = 'Processing' THEN 1 ELSE 0 END) as processing_refunds,
    SUM(CASE WHEN status = 'Completed' THEN 1 ELSE 0 END) as completed_refunds,
    SUM(CASE WHEN status = 'Rejected' THEN 1 ELSE 0 END) as rejected_refunds,
    SUM(refund_amount) as total_refund_amount,
    SUM(CASE WHEN status = 'Completed' THEN refund_amount ELSE 0 END) as completed_refund_amount,
    AVG(refund_amount) as average_refund_amount
    FROM irs_refunds";

$stats_stmt = $conn->query($stats_query);
$stats = $stats_stmt->fetch();

// Get all users for the create form
$users_stmt = $conn->query("SELECT id, firstname, lastname, email FROM users ORDER BY firstname, lastname");
$users = $users_stmt->fetchAll();

// Get available tax years
$current_year = date('Y');
$tax_years = [];
for ($year = $current_year - 5; $year <= $current_year; $year++) {
    $tax_years[] = $year;
}

$database->closeConnection();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TrustBeam Credit - IRS Refunds</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        
        .modal-content {
            background-color: #fff;
            margin: 2% auto;
            padding: 20px;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            position: relative;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        
        .close:hover {
            color: #000;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .form-group textarea {
            height: 80px;
            resize: vertical;
        }
        
        .btn-group {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }
        
        .btn-primary {
            background-color: #007bff;
            color: white;
        }
        
        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }
        
        .btn-success {
            background-color: #28a745;
            color: white;
        }
        
        .btn-warning {
            background-color: #ffc107;
            color: #212529;
        }
        
        .btn-danger {
            background-color: #dc3545;
            color: white;
        }
        
        .btn-info {
            background-color: #17a2b8;
            color: white;
        }
        
        .btn-sm {
            padding: 5px 10px;
            font-size: 12px;
        }
        
        .alert {
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 4px;
        }
        
        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            color: white;
        }
        
        .stat-icon.pending { background: linear-gradient(135deg, #ffc107, #ff8f00); }
        .stat-icon.processing { background: linear-gradient(135deg, #17a2b8, #20c997); }
        .stat-icon.completed { background: linear-gradient(135deg, #28a745, #20c997); }
        .stat-icon.rejected { background: linear-gradient(135deg, #dc3545, #fd7e14); }
        .stat-icon.total { background: linear-gradient(135deg, #6f42c1, #e83e8c); }
        .stat-icon.amount { background: linear-gradient(135deg, #fd7e14, #ffc107); }
        .stat-icon.average { background: linear-gradient(135deg, #20c997, #17a2b8); }
        
        .stat-content h3 {
            margin: 0;
            font-size: 24px;
            color: #333;
        }
        
        .stat-content p {
            margin: 5px 0 0 0;
            color: #666;
            font-size: 14px;
        }
        
        .table-container {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .table-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
        }
        
        .table-header h3 {
            margin: 0;
            font-size: 24px;
        }
        
        .table-header p {
            margin: 5px 0 0 0;
            opacity: 0.9;
        }
        
        .filters {
            padding: 20px;
            border-bottom: 1px solid #eee;
            background: #f8f9fa;
        }
        
        .filters form {
            display: flex;
            gap: 15px;
            align-items: end;
            flex-wrap: wrap;
        }
        
        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }
        
        .filter-group label {
            font-size: 12px;
            font-weight: 600;
            color: #666;
        }
        
        .filter-group input,
        .filter-group select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #495057;
        }
        
        tr:hover {
            background-color: #f8f9fa;
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .status-processing {
            background-color: #d1ecf1;
            color: #0c5460;
        }
        
        .status-completed {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status-rejected {
            background-color: #f8d7da;
            color: #721c24;
        }
        
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        
        .refund-amount {
            font-weight: 600;
            color: #28a745;
        }
        
        .user-info {
            display: flex;
            flex-direction: column;
        }
        
        .user-name {
            font-weight: 600;
            color: #333;
        }
        
        .user-email {
            font-size: 12px;
            color: #666;
        }
        
        .tax-year {
            font-weight: 600;
            color: #007bff;
        }
        
        .notes-text {
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .amount-display {
            font-size: 18px;
            font-weight: 700;
            color: #28a745;
        }
        
        @media (max-width: 768px) {
            .filters form {
                flex-direction: column;
                align-items: stretch;
            }
            
            .filter-group {
                width: 100%;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .action-buttons {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <!-- Header -->
        <header class="admin-header">
            <div class="header-left">
                <h1 class="logo">TrustBeam Credit</h1>
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="search-bar">
                    <i class="fas fa-search"></i>
                    <input type="text" placeholder="Search...">
                </div>
            </div>
            <div class="header-right">
                <div class="admin-profile">
                    <span>Welcome, <?php echo htmlspecialchars($current_admin['username']); ?></span>
                    <div class="profile-dropdown">
                        <i class="fas fa-user"></i>
                        <div class="dropdown-content">
                            <a href="profile.php">Profile</a>
                            <a href="logout.php">Logout</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- Sidebar -->
        <aside class="admin-sidebar" id="sidebar">
            <div class="sidebar-header">
                <h3>Admin Manager</h3>
                <p>Admin</p>
            </div>
            <nav class="sidebar-nav">
                <ul>
                    <li>
                        <a href="index.php">
                            <i class="fas fa-home"></i>
                            <span>Dashboard</span>
                        </a>
                    </li>
                    <li>
                        <a href="users.php">
                            <i class="fas fa-users"></i>
                            <span>Manage Users</span>
                        </a>
                    </li>
                    <li>
                        <a href="create-user.php">
                            <i class="fas fa-user-plus"></i>
                            <span>Create New User</span>
                        </a>
                    </li>
                    <li>
                        <a href="applications.php">
                            <i class="fas fa-user-friends"></i>
                            <span>New User Application(s)</span>
                        </a>
                    </li>
                    <li>
                        <a href="transactions.php">
                            <i class="fas fa-exchange-alt"></i>
                            <span>Transfer Transactions</span>
                        </a>
                    </li>
                    <li>
                        <a href="deposits.php">
                            <i class="fas fa-arrow-down"></i>
                            <span>Users Deposits</span>
                        </a>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-cog"></i>
                            <span>Loan Applications</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="loans.php">View All</a></li>
                            <li><a href="loans.php?status=pending">Pending</a></li>
                            <li><a href="loans.php?status=approved">Approved</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-credit-card"></i>
                            <span>Virtual Cards</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="cards.php">Manage Cards</a></li>
                            <li><a href="cards.php?status=active">Active</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu active">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-file-invoice-dollar"></i>
                            <span>IRS Refunds</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="refunds.php" class="active">View All</a></li>
                            <li><a href="refunds.php?status=pending">Pending</a></li>
                        </ul>
                    </li>
                    <li>
                        <a href="email.php">
                            <i class="fas fa-envelope"></i>
                            <span>Email Services</span>
                        </a>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-user-shield"></i>
                            <span>Administrator(s)</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="admins.php">View All</a></li>
                            <li><a href="create-admin.php">Add New</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-cog"></i>
                            <span>Settings</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="settings.php">General</a></li>
                            <li><a href="security.php">Security</a></li>
                        </ul>
                    </li>
                </ul>
            </nav>
        </aside>

        <!-- Main Content -->
        <main class="admin-main">
            <div class="dashboard-header">
                <h2>IRS Refunds Management</h2>
                <p>Manage IRS tax refunds for users</p>
            </div>

            <!-- Messages -->
            <?php if ($message): ?>
                <div class="alert alert-<?php echo $message_type; ?>">
                    <?php echo htmlspecialchars($message); ?>
                </div>
            <?php endif; ?>

            <!-- Statistics Cards -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon total">
                        <i class="fas fa-file-invoice-dollar"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['total_refunds']); ?></h3>
                        <p>Total Refunds</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon pending">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['pending_refunds']); ?></h3>
                        <p>Pending</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon processing">
                        <i class="fas fa-spinner"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['processing_refunds']); ?></h3>
                        <p>Processing</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon completed">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['completed_refunds']); ?></h3>
                        <p>Completed</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon rejected">
                        <i class="fas fa-times-circle"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['rejected_refunds']); ?></h3>
                        <p>Rejected</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon amount">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                    <div class="stat-content">
                        <h3>$<?php echo number_format($stats['total_refund_amount'], 2); ?></h3>
                        <p>Total Amount</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon average">
                        <i class="fas fa-chart-line"></i>
                    </div>
                    <div class="stat-content">
                        <h3>$<?php echo number_format($stats['average_refund_amount'], 2); ?></h3>
                        <p>Average Refund</p>
                    </div>
                </div>
            </div>

            <!-- IRS Refunds Table -->
            <div class="table-container">
                <div class="table-header">
                    <h3><i class="fas fa-file-invoice-dollar"></i> IRS Refunds</h3>
                    <p>Manage tax refunds for users</p>
                </div>
                
                <div class="filters">
                    <form method="GET" action="">
                        <div class="filter-group">
                            <label>Search</label>
                            <input type="text" name="search" placeholder="Search by name, email, or notes..." value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="filter-group">
                            <label>Status</label>
                            <select name="status">
                                <option value="">All Status</option>
                                <option value="Pending" <?php echo $status_filter === 'Pending' ? 'selected' : ''; ?>>Pending</option>
                                <option value="Processing" <?php echo $status_filter === 'Processing' ? 'selected' : ''; ?>>Processing</option>
                                <option value="Completed" <?php echo $status_filter === 'Completed' ? 'selected' : ''; ?>>Completed</option>
                                <option value="Rejected" <?php echo $status_filter === 'Rejected' ? 'selected' : ''; ?>>Rejected</option>
                            </select>
                        </div>
                        <div class="filter-group">
                            <label>Tax Year</label>
                            <select name="year">
                                <option value="">All Years</option>
                                <?php foreach ($tax_years as $year): ?>
                                    <option value="<?php echo $year; ?>" <?php echo $year_filter == $year ? 'selected' : ''; ?>>
                                        <?php echo $year; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="filter-group">
                            <label>&nbsp;</label>
                            <button type="submit" class="btn btn-primary">Filter</button>
                        </div>
                        <div class="filter-group">
                            <label>&nbsp;</label>
                            <a href="refunds.php" class="btn btn-secondary">Clear</a>
                        </div>
                    </form>
                </div>

                <div style="padding: 20px; border-bottom: 1px solid #eee;">
                    <button class="btn btn-success" onclick="openCreateModal()">
                        <i class="fas fa-plus"></i> Create New IRS Refund
                    </button>
                </div>

                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Taxpayer</th>
                            <th>Refund Amount</th>
                            <th>Tax Year</th>
                            <th>Status</th>
                            <th>Notes</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($refunds)): ?>
                            <tr>
                                <td colspan="8" style="text-align: center; padding: 40px;">
                                    <i class="fas fa-file-invoice-dollar" style="font-size: 48px; color: #ccc; margin-bottom: 15px;"></i>
                                    <p style="color: #666;">No IRS refunds found.</p>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($refunds as $refund): ?>
                                <tr>
                                    <td><?php echo $refund['id']; ?></td>
                                    <td>
                                        <div class="user-info">
                                            <div class="user-name"><?php echo htmlspecialchars($refund['firstname'] . ' ' . $refund['lastname']); ?></div>
                                            <div class="user-email"><?php echo htmlspecialchars($refund['email']); ?></div>
                                            <div style="font-size: 11px; color: #999;"><?php echo htmlspecialchars($refund['account_number']); ?></div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="refund-amount amount-display">$<?php echo number_format($refund['refund_amount'], 2); ?></div>
                                    </td>
                                    <td>
                                        <div class="tax-year"><?php echo $refund['tax_year']; ?></div>
                                    </td>
                                    <td>
                                        <span class="status-badge status-<?php echo strtolower($refund['status']); ?>">
                                            <?php echo htmlspecialchars($refund['status']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($refund['notes']): ?>
                                            <div class="notes-text" title="<?php echo htmlspecialchars($refund['notes']); ?>">
                                                <?php echo htmlspecialchars(substr($refund['notes'], 0, 50)) . (strlen($refund['notes']) > 50 ? '...' : ''); ?>
                                            </div>
                                        <?php else: ?>
                                            <span style="color: #999; font-style: italic;">No notes</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo date('M j, Y', strtotime($refund['created_at'])); ?></td>
                                    <td>
                                        <div class="action-buttons">
                                            <button class="btn btn-info btn-sm" onclick="viewRefundDetails(<?php echo $refund['id']; ?>)" title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button class="btn btn-warning btn-sm" onclick="openUpdateModal(<?php echo $refund['id']; ?>, '<?php echo $refund['status']; ?>', '<?php echo htmlspecialchars($refund['notes']); ?>')" title="Update Status">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="btn btn-danger btn-sm" onclick="deleteRefund(<?php echo $refund['id']; ?>)" title="Delete Refund">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </main>
    </div>

    <!-- Create IRS Refund Modal -->
    <div id="createModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeCreateModal()">&times;</span>
            <h3>Create New IRS Refund</h3>
            <form method="POST" action="">
                <input type="hidden" name="action" value="create">
                
                <div class="form-group">
                    <label for="user_id">Select Taxpayer:</label>
                    <select id="user_id" name="user_id" required>
                        <option value="">Select Taxpayer</option>
                        <?php foreach ($users as $user): ?>
                            <option value="<?php echo $user['id']; ?>">
                                <?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname'] . ' (' . $user['email'] . ')'); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="refund_amount">Refund Amount ($):</label>
                    <input type="number" id="refund_amount" name="refund_amount" step="0.01" min="0.01" max="1000000" required>
                </div>
                
                <div class="form-group">
                    <label for="tax_year">Tax Year:</label>
                    <select id="tax_year" name="tax_year" required>
                        <option value="">Select Tax Year</option>
                        <?php foreach ($tax_years as $year): ?>
                            <option value="<?php echo $year; ?>"><?php echo $year; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="notes">Notes (Optional):</label>
                    <textarea id="notes" name="notes" placeholder="Enter any additional notes or comments..."></textarea>
                </div>
                
                <div class="btn-group">
                    <button type="button" class="btn btn-secondary" onclick="closeCreateModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Refund</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Update Status Modal -->
    <div id="updateModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeUpdateModal()">&times;</span>
            <h3>Update IRS Refund Status</h3>
            <form method="POST" action="">
                <input type="hidden" name="action" value="update_status">
                <input type="hidden" id="refundId" name="refund_id">
                
                <div class="form-group">
                    <label for="status">Status:</label>
                    <select id="status" name="status" required>
                        <option value="Pending">Pending</option>
                        <option value="Processing">Processing</option>
                        <option value="Completed">Completed</option>
                        <option value="Rejected">Rejected</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="notes">Update Notes:</label>
                    <textarea id="notes" name="notes" placeholder="Enter status update notes..."></textarea>
                </div>
                
                <div class="btn-group">
                    <button type="button" class="btn btn-secondary" onclick="closeUpdateModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Status</button>
                </div>
            </form>
        </div>
    </div>

    <!-- View Details Modal -->
    <div id="detailsModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeDetailsModal()">&times;</span>
            <h3>IRS Refund Details</h3>
            <div id="refundDetails">
                <!-- Details will be loaded here -->
            </div>
        </div>
    </div>

    <script src="assets/js/admin.js"></script>
    <script>
        function openCreateModal() {
            document.getElementById('createModal').style.display = 'block';
        }

        function closeCreateModal() {
            document.getElementById('createModal').style.display = 'none';
            document.querySelector('#createModal form').reset();
        }

        function openUpdateModal(refundId, status, notes) {
            document.getElementById('refundId').value = refundId;
            document.getElementById('status').value = status;
            document.getElementById('notes').value = notes;
            document.getElementById('updateModal').style.display = 'block';
        }

        function closeUpdateModal() {
            document.getElementById('updateModal').style.display = 'none';
            document.querySelector('#updateModal form').reset();
        }

        function viewRefundDetails(refundId) {
            // This would typically load refund details via AJAX
            // For now, we'll show a simple message
            document.getElementById('refundDetails').innerHTML = `
                <p>Loading IRS refund details for ID: ${refundId}</p>
                <p><em>This feature would load detailed information about the IRS refund including:</em></p>
                <ul>
                    <li>Complete taxpayer information</li>
                    <li>Tax filing details</li>
                    <li>Refund processing timeline</li>
                    <li>Supporting documentation</li>
                    <li>Payment history and status updates</li>
                </ul>
            `;
            document.getElementById('detailsModal').style.display = 'block';
        }

        function closeDetailsModal() {
            document.getElementById('detailsModal').style.display = 'none';
        }

        function deleteRefund(refundId) {
            if (confirm('Are you sure you want to delete this IRS refund record? This action cannot be undone.')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="refund_id" value="${refundId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }

        // Close modals when clicking outside
        window.onclick = function(event) {
            const createModal = document.getElementById('createModal');
            const updateModal = document.getElementById('updateModal');
            const detailsModal = document.getElementById('detailsModal');
            
            if (event.target === createModal) {
                closeCreateModal();
            }
            if (event.target === updateModal) {
                closeUpdateModal();
            }
            if (event.target === detailsModal) {
                closeDetailsModal();
            }
        }

        // Format currency input
        document.getElementById('refund_amount').addEventListener('input', function(e) {
            let value = e.target.value;
            if (value && !isNaN(value)) {
                e.target.value = parseFloat(value).toFixed(2);
            }
        });
    </script>
</body>
</html>

