<?php
session_start();
require_once 'email_helpers.php';
// Load main/admin DB connection for audit logging
require_once 'main_db_connect.php';
// Load shared helper functions (includes logAction)
require_once 'functions.php';

// Check if user is logged in
if (!isset($_SESSION['username'])) {
	echo json_encode(['success' => false, 'error' => 'Unauthorized']);
	exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	$documentId = $_POST['document_id'] ?? null;
	$recipient = trim($_POST['recipient'] ?? '');
	$subject = trim($_POST['subject'] ?? 'Document from PPDCO');
	$message = $_POST['message'] ?? '';

	if (!$documentId || !$recipient) {
		echo json_encode(['success' => false, 'error' => 'Missing required parameters']);
		exit();
	}

	if (!filter_var($recipient, FILTER_VALIDATE_EMAIL)) {
		echo json_encode(['success' => false, 'error' => 'Invalid recipient email']);
		exit();
	}

	// Use the pmed DB connection (from main_db_connect.php this is $conn2).
	// Fall back to $conn if $conn2 isn't available.
	$pmedDb = isset($conn2) ? $conn2 : (isset($conn) ? $conn : null);
	if (!$pmedDb) {
		echo json_encode(['success' => false, 'error' => 'Database connection not available']);
		exit();
	}

	// Get file information from pmed database
	$stmt = $pmedDb->prepare("SELECT pmed_file_name, pmed_file_path FROM pmed_documents WHERE pmed_document_id = ?");
	$stmt->bind_param("i", $documentId);
	$stmt->execute();
	$result = $stmt->get_result();

	if ($result->num_rows === 0) {
		echo json_encode(['success' => false, 'error' => 'Document not found']);
		exit();
	}

	$file = $result->fetch_assoc();
	$fileName = $file['pmed_file_name'];
	$filePath = $file['pmed_file_path'];

    // Resolve to absolute path if needed (Windows or Unix). Avoid regex modifier pitfalls
    $absolutePath = $filePath;
    $isWindowsAbsolute = (preg_match('#^[A-Za-z]:[\\/]#', $absolutePath) === 1);
    $isUnixAbsolute = (strlen($absolutePath) > 0 && ($absolutePath[0] === '/' || $absolutePath[0] === '\\'));
    if (!$isWindowsAbsolute && !$isUnixAbsolute) {
        $absolutePath = __DIR__ . DIRECTORY_SEPARATOR . ltrim($filePath, "/\\");
    }

	if (!file_exists($absolutePath)) {
		echo json_encode(['success' => false, 'error' => 'File not found on server']);
		exit();
	}

	$fromEmail = defined('EMAIL_FROM') ? EMAIL_FROM : 'office@lagunappdco.online';
	$fromName = defined('EMAIL_FROM_NAME') ? EMAIL_FROM_NAME : 'PPDCO pmed Files';

	$sent = false;
	$error = '';

	// Prefer PHPMailer if available
	if (class_exists('\\PHPMailer\\PHPMailer\\PHPMailer')) {
		try {
			$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
			if (defined('SMTP_HOST') && SMTP_HOST) {
				$mail->isSMTP();
				$mail->Host = SMTP_HOST;
				$mail->SMTPAuth = (defined('SMTP_USER') && defined('SMTP_PASS'));
				if (defined('SMTP_USER')) $mail->Username = SMTP_USER;
				if (defined('SMTP_PASS')) $mail->Password = SMTP_PASS;
				if (defined('SMTP_SECURE')) $mail->SMTPSecure = SMTP_SECURE;
				if (defined('SMTP_PORT')) $mail->Port = SMTP_PORT;
			} else {
				$mail->isMail();
			}
			$mail->setFrom($fromEmail, $fromName);
			$mail->addAddress($recipient);
			$mail->Subject = $subject ?: 'Document from PPDCO';
			$mail->isHTML(true);
			$mail->Body = nl2br($message ?: 'Please see the attached document.');
			$mail->AltBody = $message ?: 'Please see the attached document.';
			$mail->addAttachment($absolutePath, $fileName ?: basename($absolutePath));
			$mail->send();
			$sent = true;
		} catch (\PHPMailer\PHPMailer\Exception $e) {
			$error = $e->getMessage();
		}
	}

	// Fallback to mail() with MIME if PHPMailer failed or is unavailable
	if (!$sent) {
		$boundary = '=_Part_' . md5(uniqid((string)mt_rand(), true));
		$headers = 'From: ' . $fromName . ' <' . $fromEmail . '>' . "\r\n";
		$headers .= 'Reply-To: ' . $fromEmail . "\r\n";
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= 'Content-Type: multipart/mixed; boundary="' . $boundary . '"' . "\r\n";

		$plain = $message ?: 'Please see the attached document.';
		$body = '--' . $boundary . "\r\n";
		$body .= "Content-Type: text/plain; charset=\"utf-8\"\r\n";
		$body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
		$body .= $plain . "\r\n\r\n";

		$fileContent = file_get_contents($absolutePath);
		$fileContent = chunk_split(base64_encode($fileContent));
		$attachmentName = $fileName ?: basename($absolutePath);

		$body .= '--' . $boundary . "\r\n";
		$body .= 'Content-Type: application/octet-stream; name="' . addslashes($attachmentName) . '"' . "\r\n";
		$body .= 'Content-Disposition: attachment; filename="' . addslashes($attachmentName) . '"' . "\r\n";
		$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
		$body .= $fileContent . "\r\n";
		$body .= '--' . $boundary . '--';

		if (mail($recipient, ($subject ?: 'Document from PPDCO'), $body, $headers)) {
			$sent = true;
		} else {
			if (!$error) $error = 'Failed to send email';
		}
	}

	$stmt->close();

	if ($sent) {
		// Audit log: Emailed a file from Gender and development to (recipient's email)
		if (function_exists('logAction')) {
			$userId = $_SESSION['user_id'] ?? 0;
			$username = $_SESSION['username'] ?? 'Guest';
			$actionText = "Emailed a file from PMED to {$recipient}";
			// Pass the admin/main DB connection ($conn) which logAction expects as first param
			$logResult = logAction(isset($conn) ? $conn : null, $userId, $username, $actionText, $documentId, $fileName);
			if ($logResult === false) {
				// If logging failed, write to error log for diagnosis
				error_log("logAction failed for user={$userId}, doc={$documentId}, recipient={$recipient}");
			}
		}
		echo json_encode(['success' => true]);
	} else {
		echo json_encode(['success' => false, 'error' => $error ?: 'Failed to send email']);
	}
} else {
	echo json_encode(['success' => false, 'error' => 'Invalid request method']);
}
?>
