<?php
session_start();

// Use the main DB connection (istrowberritech_ppdco) which contains the `messages` table
require_once 'main_db_connect.php';

$response = ['success' => false, 'error' => ''];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['error'] = 'Invalid request method.';
    echo json_encode($response);
    exit();
}

// Determine sender id: prefer session sender_id, fallback to posted userId
$senderId = $_SESSION['sender_id'] ?? $_POST['userId'] ?? $_SESSION['user_id'] ?? null;
if (!$senderId) {
    $response['error'] = 'Sender not identified.';
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
        echo json_encode($response);
    } else {
        // Redirect back to whichever dashboard is appropriate
        $loc = isset($_SESSION['user_type']) && $_SESSION['user_type'] === 'admin' ? 'admin_dashboard.php' : 'users/user_dashboard.php';
        header('Location: ' . $loc . '?error=sender_not_identified');
    }
    exit();
}

$message = trim($_POST['message'] ?? '');
if ($message === '') {
    $response['error'] = 'Message is empty.';
    echo json_encode($response);
    exit();
}

// Fetch sender details from accounts table (in main DB connection $conn)
$fullName = $username = $email = $phoneNumber = 'N/A';
if (isset($conn)) {
    $stmt = $conn->prepare('SELECT full_name, username, email, phone_number FROM accounts WHERE id = ?');
    if ($stmt) {
        $stmt->bind_param('i', $senderId);
        $stmt->execute();
        $stmt->bind_result($fullName, $username, $email, $phoneNumber);
        $stmt->fetch();
        $stmt->close();
    }
}

// Insert into messages table (structure matches localhost SQL dump)
$insertStmt = $conn->prepare('INSERT INTO messages (sender_id, full_name, username, email, phone_number, message) VALUES (?, ?, ?, ?, ?, ?)');
if ($insertStmt === false) {
    $response['error'] = 'Prepare failed: ' . $conn->error;
    echo json_encode($response);
    exit();
}

$insertStmt->bind_param('isssss', $senderId, $fullName, $username, $email, $phoneNumber, $message);
$ok = $insertStmt->execute();
if ($ok === false) {
    $response['error'] = 'Execute failed: ' . $insertStmt->error;
    $insertStmt->close();
    echo json_encode($response);
    exit();
}

$insertStmt->close();
$response['success'] = true;

// If AJAX request, return JSON. Otherwise redirect back to dashboard that initiated it.
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
    echo json_encode($response);
    exit();
}
$redirect = (isset($_SESSION['user_type']) && $_SESSION['user_type'] === 'admin') ? 'admin_dashboard.php' : 'users/user_dashboard.php';
header('Location: ' . $redirect . '?message_sent=1');
// Notify system administrators via email (best-effort)
require_once 'email_helpers.php';
if (isset($conn)) {
    $res = $conn->query("SELECT sysad_email, sysad_full_name FROM system_administrators WHERE sysad_email IS NOT NULL AND sysad_email != ''");
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $to = $row['sysad_email'];
            $name = $row['sysad_full_name'] ?: 'System Administrator';
            $subject = 'New message from ' . ($fullName ?: $username ?: 'User');
            $plain = "You have received a new message from: \n\nName: " . ($fullName ?: $username) . "\nUsername: " . ($username ?: 'N/A') . "\nEmail: " . ($email ?: 'N/A') . "\nPhone: " . ($phoneNumber ?: 'N/A') . "\n\nMessage:\n" . $message . "\n\nPlease login to the admin panel to respond.";
            // Use the helper to send (it expects reset-style args, but it's okay to call mail directly)
            if (function_exists('sendPasswordResetEmail')) {
                // Use PHP mail as fallback via the helper's internal mail wrapper
                $headers = 'From: PPDCO <' . (defined('EMAIL_FROM') ? EMAIL_FROM : 'office@lagunappdco.online') . '>' . "\r\n";
                mail($to, $subject, $plain, $headers);
            } else {
                mail($to, $subject, $plain);
            }
        }
    }
}

header('Location: ' . $redirect . '?message_sent=1');
exit();

?>
