<?php
include("includes/db.php");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $subject = strtoupper($_POST['subject']);
    $message = $_POST['message'];
    $email = $_POST['email'];
    $teacher_name = strtoupper($_POST['teacher_name']);
    $teacher_id = $_POST['teacher_id'];
    
    // If no teacher_id, insert the new teacher name into 'teachers' table
    if (empty($teacher_id)) {
        $query = "INSERT INTO teachers (name) VALUES (?)";
        $stmt = $conn->prepare($query);
        $stmt->bind_param('s', $teacher_name); // 's' stands for string
        $stmt->execute();
        $teacher_id = $conn->insert_id; // Get the newly inserted teacher ID
    }

    // Insert into support_messages table
    $query = "INSERT INTO support_messages (subject, message, email, created_by) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('sssi', $subject, $message, $email, $teacher_id); // 's' for strings and 'i' for integer
    $stmt->execute();
    $support_message_id = $conn->insert_id; // Get the message ID for naming the images

    // Handle file upload
    $uploaded_files = [];
    if (!empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['name'] as $key => $image_name) {
            $tmp_name = $_FILES['images']['tmp_name'][$key];
            $ext = pathinfo($image_name, PATHINFO_EXTENSION);
            $new_name = $support_message_id . '_' . $teacher_name . '_' . uniqid() . '.' . $ext;
            $destination = 'uploads/support/' . $new_name;
            if (move_uploaded_file($tmp_name, $destination)) {
                $uploaded_files[] = $new_name;
            }
        }
    }

    // Insert image file paths into 'support_images' table
    if (!empty($uploaded_files)) {
        foreach ($uploaded_files as $file) {
            $query = "INSERT INTO support_images (message_id, image_path) VALUES (?, ?)";
            $stmt = $conn->prepare($query);
            $stmt->bind_param('is', $support_message_id, $file); // 'i' for integer and 's' for string
            $stmt->execute();
        }
    }

    header("Location: thank_you.php"); // Redirect to a thank you page after successful submission
    exit();
}
?>
