<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

use PHPMailer\PHPMailer\PHPMailer;
require_once __DIR__ . '/email/vendor/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/email/vendor/phpmailer/src/Exception.php';
require_once __DIR__ . '/email/vendor/phpmailer/src/SMTP.php';

function enc($str) { return base64_encode($str); }
function dec($str) { return base64_decode($str); }

$type = $_POST['type'] ?? '';

if ($type == "create") {
    $to = $_POST['to'] ?? '';
    $toHashed = password_hash($to, PASSWORD_BCRYPT);
    $subject = $_POST['subject'] ?? '';
    $password = $_POST['password'] ?? '';
    $passwordHashed = password_hash($password, PASSWORD_BCRYPT);
    $message = $_POST['message'] ?? '';
    $expirationType = $_POST['expirationType'] ?? '';
    $expirationTime = $_POST['expirationTime'] ?? '';
    if ($expirationType === 'destroy') { $remaining = 1; }
    else { $remaining = "unlimited"; }



    $safeDirName = preg_replace('/[^a-zA-Z0-9_-]/', '_', $passwordHashed);
    $uploadDir = __DIR__ . "/messages/$safeDirName/";
    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true)) {
        die(json_encode(['status' => 'error', 'message' => "Failed to create directory"]));
    }

    $attachmentPaths = [];
    if (!empty($_FILES['attachments']['name'][0])) {
        foreach ($_FILES['attachments']['name'] as $i => $name) {
            if ($_FILES['attachments']['error'][$i] !== UPLOAD_ERR_OK) {
                error_log("File upload error for $name: " . $_FILES['attachments']['error'][$i]);
                continue;
            }
            $ext = pathinfo($name, PATHINFO_EXTENSION);
            $filename = uniqid('msg_', true) . '.' . $ext;
            $destination = $uploadDir . $filename;
            if (move_uploaded_file($_FILES['attachments']['tmp_name'][$i], $destination)) {
                $attachmentPaths[] = $filename;
            } else {
                error_log("Failed to move uploaded file: $name");
            }
        }
    }

    $data = [
        'to' => $toHashed,
        'subject' => $subject,
        'password' => $passwordHashed,
        'message' => $message,
        'attachments' => $attachmentPaths,
        'expirationType' => $expirationType,
        'expirationTime' => $expirationTime,
        'remaining' => $remaining,
        'timestamp' => date('Y-m-d H:i:s')
    ];

    $jsonFile = $uploadDir . "message.json";
    if (!file_put_contents($jsonFile, json_encode($data, JSON_PRETTY_PRINT))) {
        die(json_encode(['status' => 'error', 'message' => "Failed to write message.json"]));
    }

    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host = 'vianexu.com';
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;
        $mail->Username = 'info@vianexu.com';
        $mail->Password = 'wxuixzhjqvdbwldz';
        $mail->setFrom('info@vianexu.com', 'Vianexu');
        $mail->addAddress($to);
        $mail->isHTML(true);
        $mail->Subject = "Message Notification - " . date("Y-m-d h:i");
        $mail->Body = "<div style='font-family: 'Courier New', monospace; text-align: center;'>
            <img style='width: 70px; margin: 10px;' src='https://vianexu.com/images/viacryptologo.png' alt='Logo'>
            <h3>Hi,</h3>
            <h4>You received an encrypted message. Use code below together with your email address to open the message.</h4>
            <h3>Code: <b>$password</b></h3> 
            Link to access: <a style='color: blue;' href='https://vianexu.com/apps/viamail?type=read&pass=" . enc($passwordHashed) . "&to=" . enc($toHashed) . 
            "&exptype=" . enc($expirationType) . "&exptime=" . enc($expirationTime) . "'>https://vianexu.com/viamail</a>.</h3>
            <h3>Best Regards,<br/>Vianexu</h3></div>";
        $mail->send();
        echo 200;
    } catch (Exception $e) {
        error_log("PHPMailer error: " . $e->getMessage()); 
        echo 400;
    }
    } elseif ($type == "read") {
    $submittedEmail = ($_POST['to']) ?? '';
    $hashedTo = dec(($_POST['to2']) ?? '');
    $submittedPass = $_POST['password'] ?? '';
    $hashedPassword = dec($_POST['password2'] ?? '');
    $expirationType = dec($_POST['expirationType'] ?? 'noexpirationType');
    $expirationTime = dec($_POST['expirationTime'] ?? '');

echo "p1: " . $submittedPass . "<br>";
echo "p2: " . $hashedPassword . "<br>";

echo "e1: " . $submittedEmail . "<br>";
echo "e2: " . $hashedTo . "<br>";
echo "checkemail: " . password_verify($submittedEmail, $hashedTo) . "<br>";
echo "checkpass: " . password_verify($submittedPass, $hashedPassword) . "<br>";


$countdown = '';
    if ($expirationTime && time() < $expirationTime) {
        $diff = date_diff(new DateTime(), DateTime::createFromFormat('U', $expirationTime));
        $countdown = $diff->format('%ad %hh %im');
        $countdown = str_replace(['0d ', '0h ', ' 0m'], ['', '', ''], $countdown);
    }
    if (!password_verify($submittedPass, $hashedPassword) || !password_verify($submittedEmail, $hashedTo)) {
        echo "nomatch";
        exit;
    }

    $folder = preg_replace('/[^a-zA-Z0-9_-]/', '_', $hashedPassword);
    $fsDir = __DIR__ . "/messages/$folder/";
    $jsonFile = $fsDir . "message.json";
    if (!file_exists($jsonFile) || ($expirationTime && time() >= $expirationTime)) {
        echo 410;
        exit;
    }

    $jsonData = json_decode(file_get_contents($jsonFile), true);
    if (!$jsonData) {
        echo 500;
        exit;
    }

    // Handle 'remaining' logic
    if (isset($jsonData['remaining']) && $jsonData['remaining'] === 1) {
        // Update remaining to 0
        $jsonData['remaining'] = 0;
        if (!file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT))) {
            echo json_encode(['status' => 'error', 'message' => "Failed to update message.json"]);
            exit;
        }
    } elseif (isset($jsonData['remaining']) && $jsonData['remaining'] === 0) {
        // Delete the message directory and its contents
        array_map('unlink', glob($fsDir . "*"));
        rmdir($fsDir);
        echo 410; // Indicate the message is gone
        exit;
    }

    $expirationMessage = $expirationType === 'destroy' ? 'This message will be destroyed after reading.' : 
        ($countdown ? "Message expires in <b>$countdown</b>." : '');

    $attachmentsDir = "/messages/$folder/";
    // Rest of the code remains unchanged...    $fsDir = __DIR__ . $attachmentsDir;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Email Message</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; }
        .email { border: 1px solid #ccc; padding: 15px; }
        .attachment { margin: 5px; }
    </style>
</head>
<body>
    <h2>Email Message</h2>
    <?php if ($expirationMessage): ?>
        <div class="alert"><?php echo ($expirationMessage); ?></div>
    <?php endif; ?>
    <div class="email">
        <p><strong>Subject:</strong> <?php echo ($jsonData['subject'] ?? 'No subject'); ?></p>
        <p><strong>Date:</strong> <?php echo ($jsonData['timestamp'] ?? 'No date'); ?></p>
        <p><strong>Message:</strong><br><?php echo nl2br(($jsonData['message'] ?? 'No message')); ?></p>
    </div>
    <h3>Attachments</h3>
    
    <?php 
    $zipPath = $fsDir . "attachments.zip";
    $zip = new ZipArchive;
    if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
        foreach ($jsonData['attachments'] as $file) {
            $p = $fsDir.$file;
            if (file_exists($p)) $zip->addFile($p, $file);
        }
        $zip->close();
    }
    if (file_exists($zipPath)): ?>
        <div style="margin-bottom:20px;">
            <a href="<?= $attachmentsDir.'attachments.zip' ?>" download
               style="display:inline-block; padding:10px 20px; background:#4285f4; color:#fff;
                      text-decoration:none; border-radius:6px; font-weight:bold;">
                <span class="material-symbols-outlined" style="vertical-align:middle;">archive</span>
                Download all as ZIP
            </a>
        </div>
    <?php endif; ?>
    
    <div style="display:flex; flex-wrap:wrap; gap:15px;">
    <?php if (!empty($jsonData['attachments'])): ?>
        <?php foreach ($jsonData['attachments'] as $file): 
            $filePath = $fsDir . $file;
            if (!file_exists($filePath)) continue;
            $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
            $isImage = in_array($ext, ['jpg','jpeg','png','gif','webp']);
            $icon = match($ext) {
                'pdf'   => 'picture_as_pdf',
                'doc','docx' => 'description',
                'xls','xlsx' => 'grid_on',
                'zip','rar'  => 'folder_zip',
                'txt'        => 'notes',
                default      => 'insert_drive_file'
            };
        ?>
            <div style="width:120px; text-align:center; font-size:12px;">
                <a href="<?= $attachmentsDir.$file ?>" download style="text-decoration:none; color:#333;">
                    <?php if ($isImage): ?>
                        <img src="<?= $attachmentsDir.$file ?>" 
                             style="width:100px; height:100px; object-fit:cover; border:1px solid #ddd; border-radius:6px;" 
                             alt="<?= htmlspecialchars($file) ?>">
                    <?php else: ?>
                        <span class="material-symbols-outlined" 
                              style="font-size:60px; color:#666; display:block; margin:10px auto;">
                            <?= $icon ?>
                        </span>
                    <?php endif; ?>
                    <div style="overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
                        <?= htmlspecialchars($file) ?>
                    </div>
                </a>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <p>No attachments.</p>
    <?php endif; ?>
    </div>
    
    <!-- Google Material Symbols -->
    <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet" />
</body>
</html>
<?php
}
?>