<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'customer') {
    header('Location: login.php');
    exit();
}

require_once 'admin/config/database.php';

// Format currency display - currency field now contains the actual symbol
function formatCurrency($amount, $currencySymbol) {
    return $currencySymbol . number_format($amount, 2);
}

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

// Get user data
$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!$user) {
    header('Location: login.php');
    exit();
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $refund_amount = $_POST['refund_amount'];
    $tax_year = $_POST['tax_year'];
    $notes = $_POST['notes'];
    
    // Validate inputs
    if (empty($refund_amount) || empty($tax_year)) {
        $message = 'Please fill in all required fields.';
        $message_type = 'error';
    } elseif (!is_numeric($refund_amount) || $refund_amount <= 0) {
        $message = 'Refund amount must be a positive number.';
        $message_type = 'error';
    } elseif (!is_numeric($tax_year) || $tax_year < 2015 || $tax_year > date('Y')) {
        $message = 'Please enter a valid tax year between 2015 and ' . date('Y') . '.';
        $message_type = 'error';
    } elseif ($refund_amount > 1000000) {
        $message = 'Refund amount cannot exceed ' . formatCurrency(1000000, $_SESSION['currency'] ?? '$') . '.';
        $message_type = 'error';
    } else {
        try {
            // Insert new IRS refund application
            $stmt = $conn->prepare("INSERT INTO irs_refunds (user_id, refund_amount, tax_year, notes, status) VALUES (?, ?, ?, ?, 'Pending')");
            
            if ($stmt->execute([$user_id, $refund_amount, $tax_year, $notes])) {
                $message = 'IRS refund application submitted successfully! We will review your application and update you on the status.';
                $message_type = 'success';
            } else {
                $message = 'Failed to submit refund application. Please try again.';
                $message_type = 'error';
            }
        } catch (Exception $e) {
            $message = 'An error occurred. Please try again.';
            $message_type = 'error';
        }
    }
}

// Get user's existing refund applications
$stmt = $conn->prepare("SELECT * FROM irs_refunds WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$user_id]);
$refund_applications = $stmt->fetchAll();

// Calculate refund statistics
$stmt = $conn->prepare("SELECT COUNT(*) as total_applications FROM irs_refunds WHERE user_id = ?");
$stmt->execute([$user_id]);
$total_applications = $stmt->fetch()['total_applications'];

$stmt = $conn->prepare("SELECT SUM(refund_amount) as total_requested FROM irs_refunds WHERE user_id = ? AND status IN ('Pending', 'Processing')");
$stmt->execute([$user_id]);
$total_requested = $stmt->fetch()['total_requested'] ?? 0;

$stmt = $conn->prepare("SELECT SUM(refund_amount) as total_approved FROM irs_refunds WHERE user_id = ? AND status = 'Completed'");
$stmt->execute([$user_id]);
$total_approved = $stmt->fetch()['total_approved'] ?? 0;

$stmt = $conn->prepare("SELECT COUNT(*) as pending_applications FROM irs_refunds WHERE user_id = ? AND status = 'Pending'");
$stmt->execute([$user_id]);
$pending_applications = $stmt->fetch()['pending_applications'];

// Get general settings for site name
$siteName = 'TrustBNK';
try {
    $stmt = $conn->prepare("SELECT site_name FROM general_settings WHERE id = 1");
    $stmt->execute();
    $settings = $stmt->fetch();
    
    if ($settings && $settings['site_name']) {
        $siteName = $settings['site_name'];
    }
} catch (Exception $e) {
    // Use default site name if database query fails
    $siteName = 'TrustBNK';
}

$database->closeConnection();

// Get current date and time
$current_date = date('l, F j, Y');
$current_time = date('H:i:s');
$greeting = 'Good Morning';
$hour = (int)date('H');
if ($hour >= 12 && $hour < 17) {
    $greeting = 'Good Afternoon';
} elseif ($hour >= 17) {
    $greeting = 'Good Evening';
}

// Generate tax year options
$current_year = date('Y');
$tax_years = [];
for ($year = $current_year; $year >= 2015; $year--) {
    $tax_years[] = $year;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IRS Tax Refund - <?php echo htmlspecialchars($siteName); ?> Credit</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>
        .irs-refund-container {
            max-width: 1000px;
            margin: 0 auto;
        }

        .page-header {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e0e6ed;
        }

        .page-header .header-content h1 {
            color: #2c3e50;
            margin: 0 0 10px 0;
            font-size: 2rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .page-header .header-content h1 i {
            color: #667eea;
        }

        .page-header .header-content p {
            color: #5a6c7d;
            margin: 0;
            font-size: 1.1rem;
        }

        .application-form {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border: 1px solid #e0e6ed;
            margin-bottom: 30px;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .form-section h3 {
            color: #2c3e50;
            margin: 0 0 20px 0;
            font-size: 1.3rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .form-section h3 i {
            color: #667eea;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
            font-size: 0.95rem;
        }

        .form-group label .required {
            color: #dc3545;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e6ed;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
            background: white;
            font-family: inherit;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-group textarea {
            resize: vertical;
            min-height: 100px;
        }

        .form-group .help-text {
            font-size: 0.85rem;
            color: #6c757d;
            margin-top: 5px;
        }

        .form-actions {
            display: flex;
            gap: 15px;
            justify-content: flex-end;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e0e6ed;
        }

        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-primary:hover {
            background: #5a67d8;
            transform: translateY(-2px);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .refund-applications {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border: 1px solid #e0e6ed;
        }

        .applications-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
        }

        .applications-header h3 {
            color: #2c3e50;
            margin: 0;
            font-size: 1.4rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .applications-header h3 i {
            color: #667eea;
        }

        .refund-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }

        .refund-card {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            border: 1px solid #e9ecef;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .refund-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
        }

        .refund-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .refund-id {
            font-weight: 600;
            color: #2c3e50;
            font-size: 1.1rem;
        }

        .refund-amount {
            font-size: 1.3rem;
            font-weight: 700;
            color: #28a745;
        }

        .refund-details {
            margin-bottom: 15px;
        }

        .refund-detail {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 0.9rem;
        }

        .refund-detail-label {
            color: #5a6c7d;
            font-weight: 500;
        }

        .refund-detail-value {
            color: #2c3e50;
            font-weight: 600;
        }

        .refund-notes {
            background: white;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
            font-size: 0.9rem;
            color: #495057;
            border-left: 4px solid #667eea;
        }

        .status-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-processing {
            background: #d1ecf1;
            color: #0c5460;
        }

        .status-completed {
            background: #d4edda;
            color: #155724;
        }

        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }

        .no-applications {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }

        .no-applications i {
            font-size: 4rem;
            color: #dee2e6;
            margin-bottom: 20px;
        }

        .no-applications h4 {
            color: #5a6c7d;
            margin: 0 0 10px 0;
            font-size: 1.3rem;
        }

        .no-applications p {
            margin: 0;
            font-size: 1rem;
        }

        @media (max-width: 768px) {
            .irs-refund-container {
                padding: 0 20px;
            }
            
            .refund-grid {
                grid-template-columns: 1fr;
            }
            
            .form-actions {
                flex-direction: column;
            }
            
            .applications-header {
                flex-direction: column;
                gap: 15px;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body class="dashboard-page">
    <!-- Top Header Bar -->
    <div class="dashboard-header">
        <div class="header-left">
            <div class="current-balance">
                <span class="balance-label">Current Balance</span>
                <span class="balance-amount"><?php echo formatCurrency($user['balance'], $_SESSION['currency'] ?? '$'); ?></span>
            </div>
        </div>
        <div class="header-center">
            <div class="current-date"><?php echo $current_date; ?></div>
        </div>
        <div class="header-right">
            <div class="header-actions">
                <button class="notification-btn">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge">3</span>
                </button>
                <div class="user-profile">
                    <div class="user-avatar">
                        <?php if ($user['profile_photo']): ?>
                            <img src="admin/<?php echo htmlspecialchars($user['profile_photo']); ?>" alt="Profile Photo">
                        <?php else: ?>
                            <span><?php echo strtoupper(substr($user['firstname'], 0, 1) . substr($user['lastname'], 0, 1)); ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="user-info">
                        <span class="user-name"><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></span>
                        <span class="user-id"><?php echo htmlspecialchars($user['account_number']); ?></span>
                        <span class="kyc-badge">KYC Verified</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="dashboard-container">
        <!-- Mobile Menu Toggle -->
        <button class="mobile-menu-toggle" id="mobileMenuToggle">
            <i class="fas fa-bars"></i>
        </button>
        
        <!-- Sidebar Overlay -->
        <div class="sidebar-overlay" id="sidebarOverlay"></div>
        
        <!-- Left Sidebar -->
        <aside class="dashboard-sidebar">
            <div class="sidebar-header">
                <div class="logo">
                    <div class="logo-emblem">
                        <span class="logo-t">T</span>
                        <span class="logo-b">B</span>
                    </div>
                    <div class="logo-text">
                        <div class="logo-main"><?php echo htmlspecialchars($siteName); ?></div>
                        <div class="logo-sub">Credit</div>
                    </div>
                </div>
            </div>
            
            <div class="user-profile-sidebar">
                <div class="user-avatar-sidebar">
                    <?php if ($user['profile_photo']): ?>
                        <img src="admin/<?php echo htmlspecialchars($user['profile_photo']); ?>" alt="Profile Photo">
                    <?php else: ?>
                        <span><?php echo strtoupper(substr($user['firstname'], 0, 1) . substr($user['lastname'], 0, 1)); ?></span>
                    <?php endif; ?>
                </div>
                <div class="user-details">
                    <div class="user-name"><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></div>
                    <div class="user-id"><?php echo htmlspecialchars($user['account_number']); ?></div>
                    <span class="kyc-badge">KYC Verified</span>
                </div>
                <div class="profile-actions">
                    <a href="profile.php" class="btn btn-profile">Profile</a>
                    <a href="logout.php" class="btn btn-logout">Logout</a>
                </div>
            </div>
            
            <nav class="sidebar-nav">
                <div class="nav-section">
                    <h3>MAIN MENU</h3>
                    <ul>
                        <li>
                            <a href="dashboard.php">
                                <i class="fas fa-home"></i>
                                <span>Dashboard</span>
                            </a>
                        </li>
                        <li>
                            <a href="transactions.php">
                                <i class="fas fa-exchange-alt"></i>
                                <span>Transactions</span>
                            </a>
                        </li>
                        <li>
                            <a href="cards.php">
                                <i class="fas fa-credit-card"></i>
                                <span>Cards</span>
                            </a>
                        </li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>TRANSFERS</h3>
                    <ul>
                        <li>
                            <a href="transfer.php">
                                <i class="fas fa-paper-plane"></i>
                                <span>Transfer Funds</span>
                            </a>
                        </li>
                        <li>
                            <a href="deposit.php">
                                <i class="fas fa-arrow-down"></i>
                                <span>Deposit</span>
                            </a>
                        </li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>SERVICES</h3>
                    <ul>
                        <li>
                            <a href="loan-request.php">
                                <i class="fas fa-hand-holding-usd"></i>
                                <span>Loan Request</span>
                            </a>
                        </li>
                        <li class="active">
                            <a href="irs-refund.php">
                                <i class="fas fa-file-invoice-dollar"></i>
                                <span>IRS Tax Refund</span>
                            </a>
                        </li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>ACCOUNT</h3>
                    <ul>
                        <li>
                            <a href="account-info.php">
                                <i class="fas fa-user-circle"></i>
                                <span>Account Info</span>
                            </a>
                        </li>
                        <li>
                            <a href="loan-history.php">
                                <i class="fas fa-history"></i>
                                <span>Loan History</span>
                            </a>
                        </li>
                        <li>
                            <a href="settings.php">
                                <i class="fas fa-cog"></i>
                                <span>Settings</span>
                            </a>
                        </li>
                        <li>
                            <a href="support.php">
                                <i class="fas fa-headset"></i>
                                <span>Support Ticket</span>
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>
            
            <div class="sidebar-footer">
                <div class="secure-banking">
                    <i class="fas fa-shield-alt"></i>
                    <span>Secure Banking</span>
                </div>
                <div class="version">v1.2.0</div>
            </div>
        </aside>

        <!-- Main Content Area -->
        <main class="dashboard-main">
            <div class="irs-refund-container">
                <!-- Page Header -->
                <div class="page-header">
                    <div class="header-content">
                        <h1><i class="fas fa-file-invoice-dollar"></i> IRS Tax Refund</h1>
                        <p>Apply for your IRS tax refund and track your application status</p>
                    </div>
                </div>

                <!-- Refund Statistics -->
                <div class="overview-cards">
                    <div class="overview-card">
                        <div class="card-icon">
                            <i class="fas fa-file-invoice"></i>
                        </div>
                        <div class="card-content">
                            <h3>Total Applications</h3>
                            <div class="card-amount"><?php echo number_format($total_applications); ?></div>
                        </div>
                    </div>
                    
                    <div class="overview-card">
                        <div class="card-icon income">
                            <i class="fas fa-dollar-sign"></i>
                        </div>
                        <div class="card-content">
                            <h3>Total Requested</h3>
                            <div class="card-amount"><?php echo formatCurrency($total_requested, $_SESSION['currency'] ?? '$'); ?></div>
                        </div>
                    </div>
                    
                    <div class="overview-card">
                        <div class="card-icon limit">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div class="card-content">
                            <h3>Total Approved</h3>
                            <div class="card-amount"><?php echo formatCurrency($total_approved, $_SESSION['currency'] ?? '$'); ?></div>
                        </div>
                    </div>
                    
                    <div class="overview-card">
                        <div class="card-icon outgoing">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div class="card-content">
                            <h3>Pending</h3>
                            <div class="card-amount"><?php echo number_format($pending_applications); ?></div>
                        </div>
                    </div>
                </div>

                <?php if ($message): ?>
                    <div class="alert alert-<?php echo $message_type === 'success' ? 'success' : 'error'; ?>">
                        <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                        <?php echo htmlspecialchars($message); ?>
                    </div>
                <?php endif; ?>

                <!-- Application Form -->
                <form method="POST" class="application-form">
                    <div class="form-section">
                        <h3><i class="fas fa-edit"></i> Refund Application Details</h3>
                        
                        <div class="form-group">
                            <label for="refund_amount">Expected Refund Amount <span class="required">*</span></label>
                            <input type="number" id="refund_amount" name="refund_amount" min="1" max="1000000" step="0.01" required>
                            <div class="help-text">Enter the amount you expect to receive from your tax refund</div>
                        </div>
                        
                        <div class="form-group">
                            <label for="tax_year">Tax Year <span class="required">*</span></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 class="help-text">Select the tax year for which you are claiming the refund</div>
                        </div>
                        
                        <div class="form-group">
                            <label for="notes">Additional Notes (Optional)</label>
                            <textarea id="notes" name="notes" placeholder="Provide any additional information about your refund claim..."></textarea>
                            <div class="help-text">Include any relevant details that might help with processing your application</div>
                        </div>
                    </div>

                    <div class="form-actions">
                        <button type="reset" class="btn btn-secondary">
                            <i class="fas fa-undo"></i>
                            Clear Form
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane"></i>
                            Submit Application
                        </button>
                    </div>
                </form>

                <!-- Existing Applications -->
                <div class="refund-applications">
                    <div class="applications-header">
                        <h3><i class="fas fa-history"></i> Your Refund Applications</h3>
                    </div>
                    
                    <?php if (empty($refund_applications)): ?>
                        <div class="no-applications">
                            <i class="fas fa-file-invoice"></i>
                            <h4>No Refund Applications</h4>
                            <p>You haven't submitted any refund applications yet. Use the form above to submit your first application.</p>
                        </div>
                    <?php else: ?>
                        <div class="refund-grid">
                            <?php foreach ($refund_applications as $application): ?>
                                <div class="refund-card">
                                    <div class="refund-header">
                                        <div class="refund-id">Application #<?php echo str_pad($application['id'], 6, '0', STR_PAD_LEFT); ?></div>
                                        <div class="refund-amount"><?php echo formatCurrency($application['refund_amount'], $_SESSION['currency'] ?? '$'); ?></div>
                                    </div>
                                    
                                    <div class="refund-details">
                                        <div class="refund-detail">
                                            <span class="refund-detail-label">Tax Year:</span>
                                            <span class="refund-detail-value"><?php echo htmlspecialchars($application['tax_year']); ?></span>
                                        </div>
                                        <div class="refund-detail">
                                            <span class="refund-detail-label">Status:</span>
                                            <span class="status-badge status-<?php echo strtolower($application['status']); ?>">
                                                <?php echo htmlspecialchars($application['status']); ?>
                                            </span>
                                        </div>
                                        <div class="refund-detail">
                                            <span class="refund-detail-label">Submitted:</span>
                                            <span class="refund-detail-value"><?php echo date('M j, Y', strtotime($application['created_at'])); ?></span>
                                        </div>
                                    </div>
                                    
                                    <?php if ($application['notes']): ?>
                                        <div class="refund-notes">
                                            <strong>Notes:</strong><br>
                                            <?php echo htmlspecialchars($application['notes']); ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>

    <script src="assets/js/main.js"></script>
</body>
</html>

