<?php
$page_title = "Support";
require_once '../config/config.php';

require_once '../includes/user_auth.php';
require_once '../includes/functions.php';



$db = Database::getInstance()->connect();
if (!$auth->isLoggedIn()) {
    header("Location: ../login.php");
    exit();
}
$user_id = $auth->getCurrentUserId();

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

if (!$user) {
    $_SESSION['error'] = "User not found";
    header('Location: dashboard.php');
    exit();
}

// Handle new ticket submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_ticket'])) {
    $subject = trim($_POST['subject']);
    $message = trim($_POST['message']);
    $priority = $_POST['priority'] ?? 'normal';

    if (empty($subject) || empty($message)) {
        $_SESSION['error'] = "Please fill in all required fields";
    } else {
        $ticket_ref = 'TKT' . time() . rand(10, 99);
        $ticket_stmt = $db->prepare("
            INSERT INTO support_tickets (user_id, ticket_id, subject, message, priority, status, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, 'open', NOW(), NOW())
        ");
        $result = $ticket_stmt->execute([$user_id, $ticket_ref, $subject, $message, $priority]);

        if ($result) {
            $_SESSION['success'] = "Support ticket created successfully. We will respond soon.";
        } else {
            $_SESSION['error'] = "Failed to create ticket. Please try again.";
        }
    }

    header('Location: support.php');
    exit();
}

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

<?php require_once '../includes/header_user.php'; ?>

<div class="min-h-screen bg-gray-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Header -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-gray-900">Support Center</h1>
            <p class="mt-2 text-gray-600">Get help with your account and investments</p>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Create New Ticket -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-lg shadow-sm p-6">
                    <h2 class="text-xl font-semibold text-gray-900 mb-4">Create New Ticket</h2>

                    <form method="POST" class="space-y-4">
                        <div>
                            <label for="subject" class="block text-sm font-medium text-gray-700">Subject</label>
                            <input type="text" id="subject" name="subject" required
                                   class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div>
                            <label for="priority" class="block text-sm font-medium text-gray-700">Priority</label>
                            <select id="priority" name="priority"
                                    class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                                <option value="low">Low</option>
                                <option value="normal" selected>Normal</option>
                                <option value="high">High</option>
                                <option value="urgent">Urgent</option>
                            </select>
                        </div>

                        <div>
                            <label for="message" class="block text-sm font-medium text-gray-700">Message</label>
                            <textarea id="message" name="message" rows="6" required
                                      class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                                      placeholder="Describe your issue in detail..."></textarea>
                        </div>

                        <button type="submit" name="create_ticket"
                                class="w-full bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                            Submit Ticket
                        </button>
                    </form>
                </div>
            </div>

            <!-- Support Tickets -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-lg shadow-sm p-6">
                    <h2 class="text-xl font-semibold text-gray-900 mb-4">Your Support Tickets</h2>

                    <?php if (empty($tickets)): ?>
                        <div class="text-center py-8">
                            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                            </svg>
                            <h3 class="mt-2 text-sm font-medium text-gray-900">No support tickets</h3>
                            <p class="mt-1 text-sm text-gray-500">You haven't created any support tickets yet.</p>
                        </div>
                    <?php else: ?>
                        <div class="space-y-4">
                            <?php foreach ($tickets as $ticket): ?>
                                <div class="border border-gray-200 rounded-lg p-4 hover:bg-gray-50">
                                    <div class="flex items-center justify-between">
                                        <div class="flex-1">
                                            <h3 class="text-lg font-medium text-gray-900"><?php echo htmlspecialchars($ticket['subject']); ?></h3>
                                            <p class="text-sm text-gray-600 mt-1"><?php echo htmlspecialchars(substr($ticket['message'], 0, 100)) . (strlen($ticket['message']) > 100 ? '...' : ''); ?></p>
                                            <div class="flex items-center mt-2 space-x-4">
                                                <span class="text-sm text-gray-500">
                                                    Created: <?php echo date('M j, Y g:i A', strtotime($ticket['created_at'])); ?>
                                                </span>
                                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                                                    <?php
                                                    switch ($ticket['status']) {
                                                        case 'open':
                                                            echo 'bg-green-100 text-green-800';
                                                            break;
                                                        case 'in_progress':
                                                            echo 'bg-yellow-100 text-yellow-800';
                                                            break;
                                                        case 'answered':
                                                            echo 'bg-blue-100 text-blue-800';
                                                            break;
                                                        case 'closed':
                                                            echo 'bg-gray-100 text-gray-800';
                                                            break;
                                                        default:
                                                            echo 'bg-gray-100 text-gray-800';
                                                    }
                                                    ?>">
                                                    <?php echo ucfirst(str_replace('_', ' ', $ticket['status'])); ?>
                                                </span>
                                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                                                    <?php
                                                    switch ($ticket['priority']) {
                                                        case 'low':
                                                            echo 'bg-blue-100 text-blue-800';
                                                            break;
                                                        case 'normal':
                                                            echo 'bg-gray-100 text-gray-800';
                                                            break;
                                                        case 'high':
                                                            echo 'bg-orange-100 text-orange-800';
                                                            break;
                                                        case 'urgent':
                                                            echo 'bg-red-100 text-red-800';
                                                            break;
                                                        default:
                                                            echo 'bg-gray-100 text-gray-800';
                                                    }
                                                    ?>">
                                                    <?php echo ucfirst($ticket['priority']); ?>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="ml-4">
                                            <a href="ticket-view.php?id=<?php echo $ticket['id']; ?>"
                                               class="text-blue-600 hover:text-blue-500 text-sm font-medium">
                                                View Details →
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>