<?php
/**
 * RoutexShipping - Email Flow Test Script
 * Run this in your browser: http://localhost/routex/test_email_flow.php
 */

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

// Include necessary files
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/app/Utils.php';
require_once __DIR__ . '/app/Models/Parcel.php';
require_once __DIR__ . '/app/Services/EmailService.php';

// Configuration
$test_email = 'cpsiteworks@gmail.com'; // Change this to your real email to verify delivery
$cleanup = true; // Set to false if you want to keep the test parcel in DB

?>
<!DOCTYPE html>
<html>
<head>
    <title>Email Flow Test</title>
    <style>
        body { font-family: sans-serif; max-width: 800px; margin: 20px auto; padding: 20px; line-height: 1.6; }
        .success { color: green; }
        .error { color: red; }
        .step { background: #f5f5f5; padding: 15px; margin-bottom: 20px; border-radius: 5px; border-left: 5px solid #ccc; }
        .log-box { background: #333; color: #fff; padding: 10px; border-radius: 5px; font-family: monospace; margin-top: 10px; }
    </style>
</head>
<body>
    <h1>RoutexShipping Email Flow Test</h1>
    <p>Testing with recipient: <strong><?php echo htmlspecialchars($test_email); ?></strong></p>

    <?php
    $parcel_model = new Parcel($pdo);
    $email_service = new EmailService($pdo);
    $parcel_id = null;

    // --- Test 1: Create Parcel ---
    echo "<div class='step' style='border-left-color: #667eea;'>";
    echo "<h2>Test 1: Parcel Creation</h2>";

    $parcel_data = [
        'sender_name' => 'Test Sender',
        'sender_email' => 'sender@test.com',
        'sender_phone' => '1234567890',
        'sender_address' => '123 Test St',
        'sender_city' => 'Test City',
        'sender_country' => 'Test Country',
        'receiver_name' => 'Test Receiver',
        'receiver_email' => $test_email,
        'receiver_phone' => '0987654321',
        'receiver_address' => '456 Receiver Ln',
        'receiver_city' => 'Receiver City',
        'receiver_country' => 'Receiver Country',
        'package_description' => 'Test Package',
        'package_weight' => 1.5,
        'package_dimensions' => '10x10x10',
        'service_type' => 'air_freight',
        'status' => 'pending',
        'current_location' => 'Warehouse',
        'estimated_delivery' => date('Y-m-d', strtotime('+5 days')),
        'notes' => 'Test parcel created by script'
    ];

    $result = $parcel_model->create($parcel_data);

    if ($result['success']) {
        $parcel_id = $result['parcel_id'];
        $tracking_code = $result['tracking_code'];
        echo "<p class='success'>✓ Parcel created successfully. ID: $parcel_id, Code: $tracking_code</p>";

        // Simulate Controller Logic: Send Email
        $parcel = $parcel_model->getById($parcel_id);
        $email_sent = $email_service->sendParcelNotification($parcel, $test_email);

        if ($email_sent) {
            echo "<p class='success'>✓ EmailService::send returned true.</p>";
        } else {
            echo "<p class='error'>✗ EmailService::send returned false.</p>";
        }

        // Check Logs
        $stmt = $pdo->prepare("SELECT * FROM email_logs WHERE parcel_id = ? ORDER BY id DESC LIMIT 1");
        $stmt->execute([$parcel_id]);
        $log = $stmt->fetch();

        if ($log) {
            echo "<div class='log-box'>";
            echo "Log Status: " . htmlspecialchars($log['status']) . "<br>";
            echo "Subject: " . htmlspecialchars($log['subject']) . "<br>";
            if ($log['error_message']) echo "Error: " . htmlspecialchars($log['error_message']);
            echo "</div>";
        } else {
            echo "<p class='error'>✗ No log entry found in database.</p>";
        }
    } else {
        echo "<p class='error'>✗ Failed to create parcel.</p>";
        exit;
    }
    echo "</div>";

    // --- Test 2: Update Parcel ---
    echo "<div class='step' style='border-left-color: #764ba2;'>";
    echo "<h2>Test 2: Parcel Update</h2>";

    $new_status = 'in_transit';
    $new_location = 'Distribution Center';
    $update_desc = 'Package has arrived at distribution center';

    if ($parcel_model->addUpdate($parcel_id, $new_status, $new_location, $update_desc)) {
        echo "<p class='success'>✓ Parcel update added successfully.</p>";

        // Simulate Controller Logic: Send Email
        $updated_parcel = $parcel_model->getById($parcel_id);
        $email_sent = $email_service->sendParcelNotification($updated_parcel, $test_email);

        // Check Logs
        $stmt = $pdo->prepare("SELECT * FROM email_logs WHERE parcel_id = ? ORDER BY id DESC LIMIT 1");
        $stmt->execute([$parcel_id]);
        $log = $stmt->fetch();

        if ($log) {
            echo "<div class='log-box'>";
            echo "Log Status: " . htmlspecialchars($log['status']) . "<br>";
            echo "Subject: " . htmlspecialchars($log['subject']);
            if ($log['error_message']) echo "<br>Error: " . htmlspecialchars($log['error_message']);
            echo "</div>";
        }
    } else {
        echo "<p class='error'>✗ Failed to update parcel.</p>";
    }
    echo "</div>";

    // --- Cleanup ---
    if ($cleanup && $parcel_id) {
        $pdo->prepare("DELETE FROM email_logs WHERE parcel_id = ?")->execute([$parcel_id]);
        $pdo->prepare("DELETE FROM parcel_updates WHERE parcel_id = ?")->execute([$parcel_id]);
        $pdo->prepare("DELETE FROM parcels WHERE id = ?")->execute([$parcel_id]);
        echo "<p><em>Test data cleaned up.</em></p>";
    }
    ?>
</body>
</html>