<?php
session_start();
require_once 'includes/auth_check.php';
require_once '../config/database.php';
require_once 'includes/admin_notifications.php'; // Add this line

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Log that we've reached this file
error_log("Create ticket script accessed");

// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = "Invalid request method.";
    header("Location: tickets.php");
    exit();
}

// Log the POST data
error_log("POST data: " . print_r($_POST, true));

// Get form data
$subject = trim($_POST['subject'] ?? '');
$user_id = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);
$priority = $_POST['priority'] ?? 'medium';
$message = trim($_POST['message'] ?? '');

// Validate inputs
$errors = [];

if (empty($subject)) {
    $errors[] = "Subject is required.";
}

if (!$user_id) {
    $errors[] = "Please select a valid customer.";
}

if (!in_array($priority, ['low', 'medium', 'high'])) {
    $errors[] = "Invalid priority level.";
}

if (empty($message)) {
    $errors[] = "Initial message is required.";
}

// If there are validation errors, redirect back with error message
if (!empty($errors)) {
    $_SESSION['error_message'] = implode("<br>", $errors);
    $_SESSION['form_data'] = $_POST; // Save form data for repopulation
    error_log("Validation errors: " . implode(", ", $errors));
    header("Location: tickets.php");
    exit();
}

// Function to send email notification with improved debugging
function sendTicketNotificationEmail($to, $name, $ticket_id, $subject, $message, $priority) {
    // Log the function call
    error_log("Attempting to send ticket notification email to: $to");
    
    $bankName = defined('BANK_NAME') ? BANK_NAME : 'Our Banking Platform';
    $bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'https://online.oceanbankcooperation.com/logo.png';
    $bankColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#0066cc';
    $currentYear = date('Y');
    
    // Set priority color
    $priorityColors = [
        'low' => '#28a745', // Green
        'medium' => '#ffc107', // Yellow
        'high' => '#dc3545' // Red
    ];
    $priorityColor = $priorityColors[$priority] ?? $priorityColors['medium'];
    
    $emailSubject = "New Support Ticket: $subject";
    
    // Format the date properly
    $formattedDate = date('F j, Y, g:i a');
    
    $emailBody = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>New Support Ticket</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333333;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }
        .email-container {
            max-width: 600px;
            margin: 0 auto;
            background-color: #ffffff;
            border: 1px solid #dddddd;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .email-header {
            background-color: $bankColor;
            padding: 20px;
            text-align: center;
        }
        .email-header img {
            max-width: 200px;
            height: auto;
        }
        .email-body {
            padding: 20px 30px;
        }
        .email-footer {
            background-color: #f8f8f8;
            padding: 15px;
            text-align: center;
            font-size: 12px;
            color: #666666;
            border-top: 1px solid #dddddd;
        }
        h1 {
            color: $bankColor;
            margin-top: 0;
        }
        .ticket-details {
            background-color: #f9f9f9;
            border-left: 4px solid $bankColor;
            padding: 15px;
            margin: 20px 0;
        }
        .ticket-message {
            background-color: #f0f0f0;
            border: 1px solid #ddd;
            padding: 15px;
            margin: 15px 0;
            border-radius: 4px;
        }
        .priority-badge {
            display: inline-block;
            background-color: $priorityColor;
            color: white;
            padding: 5px 10px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
        }
        .button {
            display: inline-block;
            background-color: $bankColor;
            color: white;
            text-decoration: none;
            padding: 10px 20px;
            border-radius: 4px;
            margin: 20px 0;
            font-weight: bold;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
            width: 30%;
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <img src="$bankLogo" alt="$bankName Logo">
        </div>
        <div class="email-body">
            <h1>New Support Ticket Created</h1>
            <p>Dear $name,</p>
            <p>A new support ticket has been created for your account. Our support team will review your request and respond as soon as possible.</p>
            
            <div class="ticket-details">
                <h2>Ticket Details</h2>
                <table>
                    <tr>
                        <th>Ticket ID</th>
                        <td>#$ticket_id</td>
                    </tr>
                    <tr>
                        <th>Subject</th>
                        <td>$subject</td>
                    </tr>
                    <tr>
                        <th>Priority</th>
                        <td><span class="priority-badge" style="background-color: $priorityColor;">$priority</span></td>
                    </tr>
                    <tr>
                        <th>Status</th>
                        <td>Open</td>
                    </tr>
                    <tr>
                        <th>Created On</th>
                        <td>$formattedDate</td>
                    </tr>
                </table>
            </div>
            
            <div class="ticket-message">
                <h3>Initial Message:</h3>
                <p>$message</p>
            </div>
            
            <p>You can view and respond to this ticket by clicking the button below or logging into your account.</p>
            
            <div style="text-align: center;">
                <a href="{$_SERVER['HTTP_ORIGIN']}/user/ticket_details.php?id=$ticket_id" class="button" style="color: white;">View Ticket</a>
            </div>
            
            <p>If you have any questions or need further assistance, please don't hesitate to contact our support team.</p>
            
            <p>Thank you for your patience.</p>
            
            <p>Best regards,<br>The $bankName Support Team</p>
        </div>
        <div class="email-footer">
            <p>This is an automated message. Please do not reply to this email.</p>
            <p>© $currentYear $bankName. All rights reserved.</p>
        </div>
    </div>
</body>
</html>
HTML;
    
    // Set content-type header for sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    
    // Additional headers
    $fromName = defined('MAIL_FROM_NAME') ? MAIL_FROM_NAME : $bankName;
    $fromEmail = defined('MAIL_FROM_ADDRESS') ? MAIL_FROM_ADDRESS : 'info@oceanbankcooperation.com';
    $headers .= "From: $fromName <$fromEmail>" . "\r\n";
    
    // Log the email details
    error_log("Email details: To: $to, Subject: $emailSubject, From: $fromName <$fromEmail>");
    
    // Save a copy of the email to a file for debugging
    $logDir = "../logs";
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }
    
    $emailLog = fopen("$logDir/ticket_email_" . time() . ".html", "w");
    if ($emailLog) {
        fwrite($emailLog, "To: $to\nSubject: $emailSubject\nHeaders: $headers\n\n$emailBody");
        fclose($emailLog);
        error_log("Email content saved to log file");
    }
    
    // Try to send email
    try {
        $result = mail($to, $emailSubject, $emailBody, $headers);
        error_log("PHP mail() result: " . ($result ? "Success" : "Failed"));
        return $result;
    } catch (Exception $e) {
        error_log("Error sending ticket notification email: " . $e->getMessage());
        return false;
    }
}

// No errors, proceed with creating the ticket
try {
    $database = new Database();
    $db = $database->getConnection();
    
    error_log("Database connection established");
    
    // Begin transaction
    $db->beginTransaction();
    error_log("Transaction started");
    
    // Insert the ticket
    $stmt = $db->prepare("
        INSERT INTO tickets (user_id, subject, status, priority, created_at, updated_at) 
        VALUES (?, ?, 'open', ?, NOW(), NOW())
    ");
    $stmt->execute([$user_id, $subject, $priority]);
    $ticket_id = $db->lastInsertId();
    error_log("Ticket created with ID: " . $ticket_id);
    
    // Get the current logged-in user's ID
    $admin_user_id = $_SESSION['user_id'] ?? null;
    
    // Debug information
    error_log("Session data: " . print_r($_SESSION, true));
    
    // If we don't have a valid user ID in the session, try different approaches
    if (!$admin_user_id) {
        // First, check if there's a user with role 'admin'
        $stmt = $db->prepare("SELECT id FROM users WHERE role = 'admin' LIMIT 1");
        $stmt->execute();
        $admin = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($admin) {
            $admin_user_id = $admin['id'];
            error_log("Using admin user ID from database: " . $admin_user_id);
        } else {
            // If no admin found, try to use the same user_id as the ticket
            error_log("No admin user found, using ticket user_id as sender: " . $user_id);
            $admin_user_id = $user_id;
        }
    }
    
    // Insert the initial message
    // Use is_admin = 1 to indicate this is from admin, even if we're using the user's ID as a fallback
    $stmt = $db->prepare("
        INSERT INTO ticket_messages (ticket_id, sender_id, is_admin, message, created_at) 
        VALUES (?, ?, 1, ?, NOW())
    ");
    $stmt->execute([$ticket_id, $admin_user_id, $message]);
    error_log("Initial message added with sender_id: " . $admin_user_id);
    
    // Create notification for the user
    try {
        $stmt = $db->prepare("
            INSERT INTO notifications (user_id, type, title, message, link, created_at) 
            VALUES (?, 'ticket_created', 'New Support Ticket Created', ?, ?, NOW())
        ");
        $stmt->execute([
            $user_id, 
            'A new support ticket has been created for you: ' . $subject,
            'ticket_details.php?id=' . $ticket_id
        ]);
        error_log("User notification created");
    } catch (PDOException $e) {
        // If notification creation fails, log it but continue
        error_log("Failed to create notification: " . $e->getMessage());
        // Don't throw the exception - we still want to create the ticket
    }
    
    // Get user email for notification
    $stmt = $db->prepare("SELECT email, first_name, last_name FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
   // Commit transaction
$db->commit();
error_log("Transaction committed");

// Create admin notification for the new ticket
try {
    $userName = $user['first_name'] . ' ' . $user['last_name'];
    notifyAdminTicket(
        $db,
        $ticket_id,
        $user_id,
        $userName,
        $subject,
        'new_ticket'
    );
    error_log("Admin notification created for new ticket");
} catch (Exception $e) {
    error_log("Failed to create admin notification: " . $e->getMessage());
    // Don't throw the exception - we still want to proceed with the ticket creation
}

// Prepare success message
$successMessage = "Ticket #$ticket_id has been created successfully.";

    
    // Prepare success message
    $successMessage = "Ticket #$ticket_id has been created successfully.";
    
    // Send email notification if we have user email
    if ($user && !empty($user['email'])) {
        $userName = $user['first_name'] . ' ' . $user['last_name'];
        error_log("Attempting to send email to: " . $user['email'] . " for user: " . $userName);
        
        $emailSent = sendTicketNotificationEmail(
            $user['email'],
            $userName,
            $ticket_id,
            $subject,
            $message,
            $priority
        );
        
        if ($emailSent) {
            error_log("Ticket notification email sent to user: " . $user['email']);
            $successMessage .= " Email notification has been sent to the user.";
        } else {
            error_log("Failed to send ticket notification email");
            $successMessage .= " However, the email notification could not be sent.";
        }
    } else {
        error_log("User email not found, skipping email notification");
        $successMessage .= " No email was sent because the user does not have an email address.";
    }
    
    // Store the success message in a cookie instead of session
    // This ensures it will be available after the redirect
    setcookie('ticket_success_message', $successMessage, time() + 60, '/');
    error_log("Success message set in cookie: " . $successMessage);
    
    // Redirect to ticket details page
    error_log("Redirecting to ticket_details.php?id=" . $ticket_id);
    header("Location: ticket_details.php?id=" . $ticket_id);
    exit();
    
} catch (PDOException $e) {
    // Rollback transaction on error
    if (isset($db) && $db->inTransaction()) {
        $db->rollBack();
        error_log("Transaction rolled back");
    }
    
    $_SESSION['error_message'] = "An error occurred while creating the ticket: " . $e->getMessage();
    error_log("Admin Create Ticket Error: " . $e->getMessage());
    header("Location: tickets.php");
    exit();
} catch (Exception $e) {
    // Handle other exceptions
    if (isset($db) && $db->inTransaction()) {
        $db->rollBack();
        error_log("Transaction rolled back");
    }
    
    $_SESSION['error_message'] = "An error occurred: " . $e->getMessage();
    error_log("Admin Create Ticket Error: " . $e->getMessage());
    header("Location: tickets.php");
    exit();
}
?>
