<?php
session_start();
require_once 'includes/auth_check.php'; // Auth check is in customer/includes folder
require_once '../includes/email_templates.php'; // Email templates is in main root includes folder

$page = 'tickets';
$database = new Database();
$db = $database->getConnection();

$success_message = '';
$error_message = '';

// Create a new ticket
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_ticket'])) {
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');
    $priority = $_POST['priority'] ?? 'medium';
    
    if (empty($subject) || empty($message)) {
        $error_message = "Subject and message are required.";
    } else {
        try {
            $db->beginTransaction();
            
            // Insert the ticket
            $stmt = $db->prepare("INSERT INTO tickets (user_id, subject, priority) VALUES (?, ?, ?)");
            $stmt->execute([$_SESSION['user_id'], $subject, $priority]);
            $ticket_id = $db->lastInsertId();
            
            // Insert the first message
            $stmt = $db->prepare("INSERT INTO ticket_messages (ticket_id, sender_id, message) VALUES (?, ?, ?)");
            $stmt->execute([$ticket_id, $_SESSION['user_id'], $message]);
            
            // Create notification for admins
            $stmt = $db->prepare("INSERT INTO admin_notifications (type, title, message, link) VALUES (?, ?, ?, ?)");
            $stmt->execute([
                'new_ticket', 
                'New Support Ticket', 
                'A new support ticket has been created: ' . $subject, 
                'admin/ticket_details.php?id=' . $ticket_id
            ]);
            
            $db->commit();
            
            // Get user information for email
            $stmt = $db->prepare("SELECT email, first_name, last_name FROM users WHERE id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // Send confirmation email
            if ($user) {
                $userName = $user['first_name'] . ' ' . $user['last_name'];
                sendTicketCreationEmail(
                    $user['email'],
                    $userName,
                    $ticket_id,
                    $subject,
                    $message
                );
            }
            
            $success_message = "Your ticket has been submitted successfully. A confirmation has been sent to your email.";
        } catch (PDOException $e) {
            $db->rollBack();
            $error_message = "An error occurred while creating your ticket.";
            error_log("Ticket Creation Error: " . $e->getMessage());
        }
    }
}

// Reply to a ticket
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply_ticket'])) {
    $ticket_id = filter_input(INPUT_POST, 'ticket_id', FILTER_VALIDATE_INT);
    $message = trim($_POST['message'] ?? '');
    
    if (!$ticket_id || empty($message)) {
        $error_message = "Message is required.";
    } else {
        try {
            // Verify the ticket belongs to the user
            $stmt = $db->prepare("SELECT id FROM tickets WHERE id = ? AND user_id = ?");
            $stmt->execute([$ticket_id, $_SESSION['user_id']]);
            if ($stmt->rowCount() === 0) {
                $error_message = "Invalid ticket.";
            } else {
                $db->beginTransaction();
                
                // Insert the reply
                $stmt = $db->prepare("INSERT INTO ticket_messages (ticket_id, sender_id, message) VALUES (?, ?, ?)");
                $stmt->execute([$ticket_id, $_SESSION['user_id'], $message]);
                
                // Update the ticket status to open if it was closed
                $stmt = $db->prepare("UPDATE tickets SET status = 'open', updated_at = NOW() WHERE id = ? AND status = 'closed'");
                $stmt->execute([$ticket_id]);
                
                // Create notification for admins
                $stmt = $db->prepare("
                    INSERT INTO admin_notifications (type, title, message, link) 
                    SELECT 'ticket_reply', 'New Reply to Ticket', CONCAT('New reply to ticket: ', t.subject), CONCAT('admin/ticket_details.php?id=', ?)
                    FROM tickets t WHERE t.id = ?
                ");
                $stmt->execute([$ticket_id, $ticket_id]);
                
                $db->commit();
                $success_message = "Your reply has been sent successfully.";
            }
        } catch (PDOException $e) {
            $db->rollBack();
            $error_message = "An error occurred while sending your reply.";
            error_log("Ticket Reply Error: " . $e->getMessage());
        }
    }
}

// Fetch all tickets for the user
$stmt = $db->prepare("
    SELECT t.*, 
           (SELECT COUNT(*) FROM ticket_messages WHERE ticket_id = t.id) as message_count,
           (SELECT created_at FROM ticket_messages WHERE ticket_id = t.id ORDER BY created_at DESC LIMIT 1) as last_activity
    FROM tickets t 
    WHERE t.user_id = ? 
    ORDER BY 
        CASE WHEN t.status = 'open' THEN 1 
             WHEN t.status = 'in_progress' THEN 2
             ELSE 3 END,
        t.updated_at DESC
");
$stmt->execute([$_SESSION['user_id']]);
$tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
/* Ticket System Styles */
:root {
    --primary-color: #4f46e5;
    --primary-light: #eef2ff;
    --border-color: #e2e8f0;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --danger-color: #ef4444;
    --info-color: #3b82f6;
}

.ticket-list {
    border: 1px solid var(--border-color);
    border-radius: 0.5rem;
    overflow: hidden;
}

.ticket-item {
    padding: 1rem;
    border-bottom: 1px solid var(--border-color);
    transition: background-color 0.2s;
}

.ticket-item:last-child {
    border-bottom: none;
}

.ticket-item:hover {
    background-color: var(--primary-light);
}

.ticket-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.5rem;
}

.ticket-title {
    font-weight: 600;
    font-size: 1.1rem;
    color: #1f2937;
}

.ticket-status {
    padding: 0.25rem 0.75rem;
    border-radius: 9999px;
    font-size: 0.75rem;
    font-weight: 600;
}

.ticket-status.open {
    background-color: var(--info-color);
    color: white;
}

.ticket-status.in_progress {
    background-color: var(--warning-color);
    color: white;
}

.ticket-status.closed {
    background-color: var(--success-color);
    color: white;
}

.ticket-meta {
    display: flex;
    justify-content: space-between;
    font-size: 0.875rem;
    color: #6b7280;
}

.priority-badge {
    padding: 0.15rem 0.5rem;
    border-radius: 9999px;
    font-size: 0.75rem;
}

.priority-low {
    background-color: #e5e7eb;
    color: #4b5563;
}

.priority-medium {
    background-color: #fef3c7;
    color: #92400e;
}

.priority-high {
    background-color: #fee2e2;
    color: #b91c1c;
}

.message-bubble {
    padding: 1rem;
    border-radius: 0.5rem;
    margin-bottom: 1rem;
    position: relative;
}

.message-bubble.user {
    background-color: var(--primary-light);
    margin-left: 2rem;
}

.message-bubble.admin {
    background-color: #f3f4f6;
    margin-right: 2rem;
}

.message-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.5rem;
    font-size: 0.875rem;
    color: #6b7280;
}

.message-sender {
    font-weight: 600;
}

.message-time {
    font-size: 0.75rem;
}

.message-content {
    white-space: pre-line;
}
</style>

<div class="main-content">
    <div class="container py-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3 mb-0">Support Tickets</h1>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newTicketModal">
                <i class='bx bx-plus me-1'></i> New Ticket
            </button>
        </div>

        <?php if (!empty($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $success_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">My Tickets</h5>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($tickets)): ?>
                            <div class="text-center py-5">
                                <i class='bx bx-support' style="font-size: 4rem; color: #d1d5db;"></i>
                                <h5 class="mt-3">No Tickets Found</h5>
                                <p class="text-muted">You haven't created any support tickets yet.</p>
                                <button class="btn btn-primary mt-2" data-bs-toggle="modal" data-bs-target="#newTicketModal">
                                    Create Your First Ticket
                                </button>
                            </div>
                        <?php else: ?>
                            <div class="ticket-list">
                                <?php foreach ($tickets as $ticket): ?>
                                    <div class="ticket-item">
                                        <div class="ticket-header">
                                            <div class="ticket-title">
                                                <a href="ticket_details.php?id=<?php echo $ticket['id']; ?>" class="text-decoration-none">
                                                    <?php echo htmlspecialchars($ticket['subject']); ?>
                                                </a>
                                            </div>
                                            <span class="ticket-status <?php echo $ticket['status']; ?>">
                                                <?php echo ucfirst(str_replace('_', ' ', $ticket['status'])); ?>
                                            </span>
                                        </div>
                                        <div class="ticket-meta">
                                            <div>
                                                <span class="priority-badge priority-<?php echo $ticket['priority']; ?>">
                                                    <?php echo ucfirst($ticket['priority']); ?> Priority
                                                </span>
                                                <span class="ms-2">
                                                    <i class='bx bx-message'></i> <?php echo $ticket['message_count']; ?> messages
                                                </span>
                                            </div>
                                            <div>
                                                Last activity: <?php echo date('M j, Y g:i A', strtotime($ticket['last_activity'] ?? $ticket['created_at'])); ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- New Ticket Modal -->
<div class="modal fade" id="newTicketModal" tabindex="-1" aria-labelledby="newTicketModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="newTicketModalLabel">Create New Support Ticket</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="tickets.php">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="subject" class="form-label">Subject</label>
                        <input type="text" class="form-control" id="subject" name="subject" required>
                    </div>
                    <div class="mb-3">
                        <label for="priority" class="form-label">Priority</label>
                        <select class="form-select" id="priority" name="priority">
                            <option value="low">Low</option>
                            <option value="medium" selected>Medium</option>
                            <option value="high">High</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="message" class="form-label">Message</label>
                        <textarea class="form-control" id="message" name="message" rows="5" required></textarea>
                        <div class="form-text">Please describe your issue in detail.</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="create_ticket" class="btn btn-primary">Submit Ticket</button>
                </div>
            </form>
        </div>
    </div>
</div>

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