<?php
/**
 * User - Create Support Ticket
 */
require_once __DIR__ . '/../config.php';
require_login();

$page_title = 'Create Ticket';
$user_id = $_SESSION['user_id'];

$success = '';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid security token';
    } else {
        $subject = sanitize($_POST['subject'] ?? '');
        $message = sanitize($_POST['message'] ?? '');
        $priority = $_POST['priority'] ?? 'medium';
        
        if (empty($subject)) $errors[] = 'Subject is required';
        if (empty($message)) $errors[] = 'Message is required';
        
        if (empty($errors)) {
            try {
                // Disable foreign key checks
                db()->exec("SET FOREIGN_KEY_CHECKS = 0");
                
                // Force drop and recreate table to ensure correct structure
                $drop_table = "DROP TABLE IF EXISTS support_tickets";
                db()->exec($drop_table);
                error_log("Table dropped");
                
                // Create table with correct structure
                $create_table = "CREATE TABLE support_tickets (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user_id INT NOT NULL,
                    ticket_number VARCHAR(20) NOT NULL UNIQUE,
                    subject VARCHAR(255) NOT NULL,
                    message TEXT NOT NULL,
                    priority ENUM('low', 'medium', 'high', 'urgent') DEFAULT 'medium',
                    status ENUM('open', 'in_progress', 'resolved', 'closed') DEFAULT 'open',
                    admin_reply TEXT NULL,
                    admin_id INT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                )";
                
                $result = db()->exec($create_table);
                error_log("Table created with correct structure: $result");
                
                // Re-enable foreign key checks
                db()->exec("SET FOREIGN_KEY_CHECKS = 1");
                
                $ticket_number = 'TKT' . date('Ymd') . strtoupper(substr(uniqid(), -6));
                error_log("Creating ticket: $ticket_number for user $user_id");
                
                $stmt = db()->prepare("INSERT INTO support_tickets 
                    (user_id, ticket_number, subject, message, priority, status, created_at)
                    VALUES (?, ?, ?, ?, ?, 'open', NOW())");
                
                error_log("Executing statement with: user_id=$user_id, ticket_number=$ticket_number, subject=$subject, priority=$priority");
                
                if ($stmt->execute([$user_id, $ticket_number, $subject, $message, $priority])) {
                    error_log("Ticket created successfully: $ticket_number");
                    
                    // Send notifications for new support ticket
                    require_once __DIR__ . '/../includes/notification-system.php';
                    triggerTicketNotification($user_id, [
                        'id' => $ticket_number,
                        'subject' => $subject,
                        'priority' => $priority,
                        'message' => $message,
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                    
                    redirect(BASE_URL . 'user/tickets.php', 'success', 'Ticket created successfully!');
                } else {
                    $error_info = $stmt->errorInfo();
                    $error_msg = "Database error: " . $error_info[2] . " (Code: " . $error_info[1] . ")";
                    $errors[] = $error_msg;
                    error_log("Ticket creation failed for user $user_id: " . print_r($error_info, true));
                }
            } catch (PDOException $e) {
                // Ensure foreign key checks are re-enabled even on error
                try {
                    db()->exec("SET FOREIGN_KEY_CHECKS = 1");
                } catch (Exception $e2) {
                    // Ignore if this fails
                }
                
                $error_msg = "Database error: " . $e->getMessage();
                $errors[] = $error_msg;
                error_log("Ticket creation PDO error for user $user_id: " . $e->getMessage());
            } catch (Exception $e) {
                // Ensure foreign key checks are re-enabled even on error
                try {
                    db()->exec("SET FOREIGN_KEY_CHECKS = 1");
                } catch (Exception $e2) {
                    // Ignore if this fails
                }
                
                $error_msg = "System error: " . $e->getMessage();
                $errors[] = $error_msg;
                error_log("Ticket creation general error for user $user_id: " . $e->getMessage());
            }
        }
    }
}

$csrf_token = generate_csrf_token();

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">Create Support Ticket</h2>
    <a href="tickets.php" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-2"></i>Back to Tickets
    </a>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <?php foreach ($errors as $error): ?>
            <p class="mb-0"><?php echo $error; ?></p>
        <?php endforeach; ?>
        <hr>
        <small class="text-muted">Debug info: Check error logs for detailed information.</small>
    </div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-body p-4">
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
            
            <div class="mb-3">
                <label class="form-label">Subject <span class="text-danger">*</span></label>
                <input type="text" name="subject" class="form-control" required>
            </div>
            
            <div class="mb-3">
                <label class="form-label">Priority</label>
                <select name="priority" class="form-select">
                    <option value="low">Low</option>
                    <option value="medium" selected>Medium</option>
                    <option value="high">High</option>
                    <option value="urgent">Urgent</option>
                </select>
            </div>
            
            <div class="mb-3">
                <label class="form-label">Message <span class="text-danger">*</span></label>
                <textarea name="message" class="form-control" rows="6" required></textarea>
            </div>
            
            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-send me-2"></i>Submit Ticket
                </button>
                <a href="tickets.php" class="btn btn-outline-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

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