<?php
session_start();
require 'config/db.php';
include 'includes/header.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php"); exit();
}

$user_id = $_SESSION['user_id'];
$msg = "";

// 1. HANDLE NEW TICKET
if (isset($_POST['create_ticket'])) {
    $subject = trim($_POST['subject']);
    $order_id = $_POST['order_id'];
    $message = trim($_POST['message']);

    if (!empty($subject) && !empty($message)) {
        // Create Ticket
        $stmt = $pdo->prepare("INSERT INTO tickets (user_id, order_id, subject, status) VALUES (?, ?, ?, 'open')");
        $stmt->execute([$user_id, $order_id, $subject]);
        $ticket_id = $pdo->lastInsertId();

        // Add First Message
        $stmtMsg = $pdo->prepare("INSERT INTO ticket_messages (ticket_id, sender, message) VALUES (?, 'user', ?)");
        $stmtMsg->execute([$ticket_id, $message]);

        $msg = "Ticket #$ticket_id Created Successfully!";
    }
}

// 2. FETCH USER TICKETS
$tickets = $pdo->prepare("SELECT * FROM tickets WHERE user_id = ? ORDER BY created_at DESC");
$tickets->execute([$user_id]);
$my_tickets = $tickets->fetchAll();

// 3. FETCH USER ORDERS (For Dropdown)
$orders = $pdo->prepare("SELECT id FROM orders WHERE user_id = ? ORDER BY id DESC");
$orders->execute([$user_id]);
$my_orders = $orders->fetchAll();
?>

<div class="container" style="padding-top: 40px; padding-bottom: 60px;">
    <h1 style="border-bottom: 1px solid #ddd; padding-bottom: 15px;">My Support Tickets</h1>

    <?php if($msg): ?>
        <div style="background:#d4edda; color:#155724; padding:10px; margin-bottom:20px; border-radius:5px;">
            <?php echo $msg; ?>
        </div>
    <?php endif; ?>

    <div style="display: flex; gap: 40px; flex-wrap: wrap;">
        
        <div style="flex: 2; min-width: 300px;">
            <?php if(count($my_tickets) > 0): ?>
                <table style="width: 100%; border-collapse: collapse; background: white; box-shadow: 0 2px 5px rgba(0,0,0,0.05); border-radius: 8px; overflow: hidden;">
                    <thead style="background: #f8f9fa; text-align: left;">
                        <tr>
                            <th style="padding: 15px;">ID</th>
                            <th>Subject</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($my_tickets as $t): ?>
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 15px;">#<?php echo $t['id']; ?></td>
                            <td>
                                <?php if($t['order_id'] > 0): ?>
                                    <span style="font-size:11px; background:#eee; padding:2px 5px; border-radius:3px;">Order #<?php echo $t['order_id']; ?></span><br>
                                <?php endif; ?>
                                <strong><?php echo htmlspecialchars($t['subject']); ?></strong>
                            </td>
                            <td>
                                <?php if($t['status'] == 'open'): ?>
                                    <span style="color: orange; font-weight: bold;">Pending</span>
                                <?php elseif($t['status'] == 'answered'): ?>
                                    <span style="color: green; font-weight: bold;">Answered</span>
                                <?php else: ?>
                                    <span style="color: gray;">Closed</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo date('d M', strtotime($t['created_at'])); ?></td>
                            <td>
                                <a href="view_ticket.php?id=<?php echo $t['id']; ?>" class="btn btn-primary" style="padding: 5px 15px; font-size: 12px;">View</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p>You have no support tickets.</p>
            <?php endif; ?>
        </div>

        <div style="flex: 1; min-width: 300px;">
            <div style="background: white; padding: 25px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
                <h3 style="margin-top: 0;">Open New Ticket</h3>
                <form method="POST">
                    <div style="margin-bottom: 15px;">
                        <label style="font-weight: bold; display: block; margin-bottom: 5px;">Related Order (Optional)</label>
                        <select name="order_id" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
                            <option value="0">General Inquiry</option>
                            <?php foreach($my_orders as $o): ?>
                                <option value="<?php echo $o['id']; ?>">Order #<?php echo $o['id']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div style="margin-bottom: 15px;">
                        <label style="font-weight: bold; display: block; margin-bottom: 5px;">Subject</label>
                        <input type="text" name="subject" required placeholder="e.g. Key not working" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;">
                    </div>

                    <div style="margin-bottom: 15px;">
                        <label style="font-weight: bold; display: block; margin-bottom: 5px;">Message</label>
                        <textarea name="message" required rows="5" placeholder="Describe your issue..." style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;"></textarea>
                    </div>

                    <button type="submit" name="create_ticket" class="btn btn-primary" style="width: 100%;">Submit Ticket</button>
                </form>
            </div>
        </div>

    </div>
</div>

<?php include 'includes/footer.php'; ?>