<?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();

// Check if user exists, if not redirect to login
if (!$user) {
    session_destroy();
    header('Location: login.php');
    exit();
}

// Handle form submission for new support ticket
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_ticket'])) {
    $subject = trim($_POST['subject']);
    $ticket_message = trim($_POST['message']);
    $priority = $_POST['priority'] ?? 'Medium';
    
    // Validate inputs
    if (empty($subject) || empty($ticket_message)) {
        $message = 'Please fill in all required fields.';
        $message_type = 'error';
    } else {
        try {
            $stmt = $conn->prepare("INSERT INTO support_tickets (user_id, subject, message, status, created_at) VALUES (?, ?, ?, 'Open', NOW())");
            $stmt->execute([$user_id, $subject, $ticket_message]);
            
            $message = 'Support ticket created successfully! We will respond within 24 hours.';
            $message_type = 'success';
            
            // Clear form data
            $_POST = array();
        } catch (Exception $e) {
            $message = 'Error creating support ticket. Please try again.';
            $message_type = 'error';
        }
    }
}

// Get user's support tickets
$stmt = $conn->prepare("SELECT * FROM support_tickets WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$user_id]);
$support_tickets = $stmt->fetchAll();

// Get support ticket statistics
$stmt = $conn->prepare("SELECT COUNT(*) as total_tickets FROM support_tickets WHERE user_id = ?");
$stmt->execute([$user_id]);
$total_tickets = $stmt->fetch()['total_tickets'];

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

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

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

// 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';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Support - <?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">
    
    <!-- Google Translator -->
    <script type="text/javascript">
        function googleTranslateElementInit() {
            new google.translate.TranslateElement({
                pageLanguage: 'en',
                includedLanguages: 'en,es,fr,de,it,pt,ru,ja,ko,zh-CN,zh-TW,ar,hi',
                layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
                autoDisplay: false
            }, 'google_translate_element');
        }
    </script>
    <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
    
    <style>
        .support-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .support-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .support-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: #667eea;
            margin-bottom: 5px;
        }
        
        .stat-label {
            color: #666;
            font-size: 0.9rem;
        }
        
        .support-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
        }
        
        .create-ticket-section {
            background: white;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .tickets-list-section {
            background: white;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }
        
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s ease;
            box-sizing: border-box;
        }
        
        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 120px;
        }
        
        .btn-create {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 8px;
            font-weight: 500;
            cursor: pointer;
            transition: transform 0.2s ease;
            width: 100%;
        }
        
        .btn-create:hover {
            transform: translateY(-2px);
        }
        
        .ticket-item {
            border: 1px solid #e1e5e9;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 15px;
            transition: box-shadow 0.3s ease;
        }
        
        .ticket-item:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        
        .ticket-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 10px;
        }
        
        .ticket-subject {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }
        
        .ticket-status {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .status-open {
            background: #e3f2fd;
            color: #1976d2;
        }
        
        .status-pending {
            background: #fff3e0;
            color: #f57c00;
        }
        
        .status-closed {
            background: #e8f5e8;
            color: #388e3c;
        }
        
        .ticket-message {
            color: #666;
            margin-bottom: 15px;
            line-height: 1.5;
        }
        
        .ticket-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.9rem;
            color: #888;
        }
        
        .ticket-response {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
            border-left: 4px solid #667eea;
        }
        
        .response-label {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
        }
        
        .section-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: #333;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .message {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        @media (max-width: 768px) {
            .support-content {
                grid-template-columns: 1fr;
            }
            
            .support-header {
                flex-direction: column;
                align-items: stretch;
            }
            
            .support-stats {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </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>
                            <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="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 class="active">
                            <a href="support.php">
                                <i class="fas fa-headset"></i>
                                <span>Support Ticket</span>
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>
        </aside>

        <!-- Main Content -->
        <main class="dashboard-main">
            <div class="support-container">
                <!-- Support Header -->
                <div class="support-header">
                    <div>
                        <h1><i class="fas fa-headset"></i> Support Center</h1>
                        <p>Get help with your account and banking needs</p>
                    </div>
                </div>

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

                <!-- Support Statistics -->
                <div class="support-stats">
                    <div class="stat-card">
                        <div class="stat-number"><?php echo $total_tickets; ?></div>
                        <div class="stat-label">Total Tickets</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number"><?php echo $open_tickets; ?></div>
                        <div class="stat-label">Open Tickets</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number"><?php echo $pending_tickets; ?></div>
                        <div class="stat-label">Pending</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number"><?php echo $closed_tickets; ?></div>
                        <div class="stat-label">Closed</div>
                    </div>
                </div>

                <!-- Support Content -->
                <div class="support-content">
                    <!-- Create New Ticket -->
                    <div class="create-ticket-section">
                        <h2 class="section-title">
                            <i class="fas fa-plus-circle"></i>
                            Create New Ticket
                        </h2>
                        
                        <form method="POST" action="">
                            <div class="form-group">
                                <label for="subject">Subject *</label>
                                <input type="text" id="subject" name="subject" 
                                       value="<?php echo isset($_POST['subject']) ? htmlspecialchars($_POST['subject']) : ''; ?>"
                                       placeholder="Brief description of your issue" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="message">Message *</label>
                                <textarea id="message" name="message" 
                                          placeholder="Please provide detailed information about your issue..." required><?php echo isset($_POST['message']) ? htmlspecialchars($_POST['message']) : ''; ?></textarea>
                            </div>
                            
                            <button type="submit" name="create_ticket" class="btn-create">
                                <i class="fas fa-paper-plane"></i> Submit Ticket
                            </button>
                        </form>
                    </div>

                    <!-- Tickets List -->
                    <div class="tickets-list-section">
                        <h2 class="section-title">
                            <i class="fas fa-ticket-alt"></i>
                            Your Support Tickets
                        </h2>
                        
                        <?php if (empty($support_tickets)): ?>
                            <div style="text-align: center; padding: 40px; color: #666;">
                                <i class="fas fa-ticket-alt" style="font-size: 3rem; margin-bottom: 20px; opacity: 0.3;"></i>
                                <p>No support tickets yet. Create your first ticket to get help!</p>
                            </div>
                        <?php else: ?>
                            <?php foreach ($support_tickets as $ticket): ?>
                                <div class="ticket-item">
                                    <div class="ticket-header">
                                        <div>
                                            <div class="ticket-subject"><?php echo htmlspecialchars($ticket['subject']); ?></div>
                                        </div>
                                        <span class="ticket-status status-<?php echo strtolower($ticket['status']); ?>">
                                            <?php echo $ticket['status']; ?>
                                        </span>
                                    </div>
                                    
                                    <div class="ticket-message">
                                        <?php echo nl2br(htmlspecialchars($ticket['message'])); ?>
                                    </div>
                                    
                                    <?php if (!empty($ticket['response'])): ?>
                                        <div class="ticket-response">
                                            <div class="response-label">
                                                <i class="fas fa-reply"></i> Support Response:
                                            </div>
                                            <div><?php echo nl2br(htmlspecialchars($ticket['response'])); ?></div>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <div class="ticket-meta">
                                        <span><i class="fas fa-calendar"></i> <?php echo date('M j, Y g:i A', strtotime($ticket['created_at'])); ?></span>
                                        <span>Ticket #<?php echo $ticket['id']; ?></span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- Google Translator Element -->
    <div id="google_translate_element" style="position: fixed; bottom: 20px; right: 20px; z-index: 1000;"></div>

    <!-- Scripts -->
    <script src="assets/js/logout-confirmation.js"></script>
    <script src="assets/js/dashboard.js"></script>
    
    <style>
        /* Google Translator Styles */
        #google_translate_element {
            position: fixed !important;
            bottom: 20px !important;
            right: 20px !important;
            z-index: 1000 !important;
        }
        
        .goog-te-gadget {
            background: white !important;
            border-radius: 8px !important;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important;
            padding: 8px !important;
        }
        
        .goog-te-gadget .goog-te-combo {
            border: 1px solid #ddd !important;
            border-radius: 4px !important;
            padding: 4px 8px !important;
            font-size: 12px !important;
        }
    </style>
</body>
</html>
