MMCT TEAM
Server IP : 217.21.85.138  /  Your IP : 216.73.216.103
Web Server : LiteSpeed
System : Linux in-mum-web906.main-hosting.eu 4.18.0-553.37.1.lve.el8.x86_64 #1 SMP Mon Feb 10 22:45:17 UTC 2025 x86_64
User : u915722082 ( 915722082)
PHP Version : 7.4.33
Disable Function : system, exec, shell_exec, passthru, mysql_list_dbs, ini_alter, dl, symlink, link, chgrp, leak, popen, apache_child_terminate, virtual, mb_send_mail
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : OFF  |  Python : OFF
Directory (0755) :  /home/u915722082/.nvm/../public_html/lohri/user/

[  Home  ][  C0mmand  ][  Upload File  ]

Current File : /home/u915722082/.nvm/../public_html/lohri/user/send_abandoned_checkout_emails.php
<?php
// ============================================================================
// LOHRI ABANDONED CART EMAIL - UI-BASED DESIGN
// ============================================================================

chdir(__DIR__);

// Set timezone to Indian Standard Time
date_default_timezone_set('Asia/Kolkata');

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/abandoned_email_cron.log');

error_log("============================================");
error_log("CRON STARTED: " . date('Y-m-d H:i:s'));
error_log("============================================");

set_time_limit(300);
ignore_user_abort(true);

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once __DIR__ . '/../config/config.php';

try {
    $pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
        DB_USER,
        DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
    );
    
    // Set MySQL timezone to IST
    $pdo->exec("SET time_zone = '+05:30'");
    
    error_log("✅ Database connected");

    // Get settings
    $settingsStmt = $pdo->query("SELECT SEND_AFTER FROM abandonedcheckout LIMIT 1");
    $settings = $settingsStmt->fetch();
    $sendAfterMinutes = $settings ? intval($settings['SEND_AFTER']) : 1;
    
    error_log("⏰ Send after: {$sendAfterMinutes} minutes");
    
    $cutoffTime = date('Y-m-d H:i:s', strtotime("-{$sendAfterMinutes} minutes"));
    error_log("⏰ Cutoff time: $cutoffTime");

    // Get abandoned checkouts
    $query = "
        SELECT 
            ac.id, ac.user_id, ac.email, ac.cart_data, ac.checkout_timestamp,
            CONCAT(u.fname, ' ', u.lname) as user_name
        FROM abandoned_checkouts ac
        INNER JOIN tbl_user u ON ac.user_id = u.uid
        WHERE ac.email_sent = 0 AND ac.checkout_timestamp <= ?
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute([$cutoffTime]);
    $abandonedCheckouts = $stmt->fetchAll();

    error_log("đŸ“Ŧ Found " . count($abandonedCheckouts) . " checkout(s) to email");

    if (empty($abandonedCheckouts)) {
        error_log("â„šī¸ No checkouts ready for email");
        exit;
    }

    // Load PHPMailer
    $autoload_paths = [
        __DIR__ . '/../vendor/autoload.php',
        __DIR__ . '/../../vendor/autoload.php',
        __DIR__ . '/../vendor_mail/autoload.php'
    ];

    foreach ($autoload_paths as $path) {
        if (file_exists($path)) {
            require_once $path;
            error_log("✅ PHPMailer loaded: $path");
            break;
        }
    }

    $emailsSent = 0;
    $baseUrl = 'https://lohri.thedotstudios.com';

    foreach ($abandonedCheckouts as $checkout) {
        try {
            error_log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
            error_log("📧 Processing ID: {$checkout['id']} - {$checkout['email']}");
            
            // Validate email address
            if (empty($checkout['email']) || !filter_var($checkout['email'], FILTER_VALIDATE_EMAIL)) {
                error_log("❌ Invalid email address: {$checkout['email']}");
                continue;
            }
            
            error_log("✅ Email validation passed");
            
            $cartData = json_decode($checkout['cart_data'], true);
            
            if (json_last_error() !== JSON_ERROR_NONE) {
                error_log("❌ JSON decode error: " . json_last_error_msg());
                continue;
            }
            
            if (empty($cartData)) {
                error_log("âš ī¸ Empty cart data");
                continue;
            }
            
            error_log("✅ Cart has " . count($cartData) . " items");

            $productsHTML = '';
            $subtotal = 0;

            foreach ($cartData as $key => $item) {
                $productName = $item['pname'] ?? 'Product';
                $variantName = $item['vname'] ?? '';
                $quantity = intval($item['quantity'] ?? 1);
                $price = floatval($item['price'] ?? 0);
                
                // Fallback: Get price from DB if needed
                if ($price == 0 && isset($item['pid'])) {
                    $priceQuery = $pdo->prepare("SELECT customer_final_price FROM products WHERE pid = ?");
                    $priceQuery->execute([$item['pid']]);
                    $priceData = $priceQuery->fetch();
                    $price = floatval($priceData['customer_final_price'] ?? 0);
                }
                
                $itemSubtotal = $price * $quantity;
                $subtotal += $itemSubtotal;
                
                // Get image
                $imagePath = $item['image'] ?? 'default.jpg';
                $imageUrl = $baseUrl . '/Images/Product/' . htmlspecialchars($imagePath);
                
                error_log("đŸ–ŧī¸ Image: {$imagePath}");
                error_log("🔗 URL: {$imageUrl}");
                error_log("💰 {$productName} - Qty:{$quantity} x ₹{$price} = ₹{$itemSubtotal}");
                
                // Build product card
                $productsHTML .= '
                <div style="text-align: center; margin-bottom: 30px;">
                    <img src="' . $imageUrl . '" 
                         style="width: 200px; height: 200px; object-fit: cover; margin-bottom: 15px;"
                         alt="' . htmlspecialchars($productName) . '">
                    <div style="font-size: 14px; color: #333; margin-bottom: 10px;">
                        <strong>The ' . htmlspecialchars($productName) . '</strong> you viewed just dropped in price
                    </div>
                    ' . (!empty($variantName) ? '<div style="font-size: 12px; color: #666; margin-bottom: 8px;">' . htmlspecialchars($variantName) . '</div>' : '') . '
                    <div style="font-size: 18px; font-weight: bold; color: #000; margin-bottom: 15px;">
                        Now: ₹' . number_format($price, 2) . '
                    </div>
                </div>';
            }

            error_log("đŸ’ĩ Subtotal: ₹{$subtotal}");

            // Send email
            $mail = new PHPMailer(true);
            
            // Enable verbose debug output
            $mail->SMTPDebug = 0; // Set to 2 for detailed debugging
            $mail->Debugoutput = function($str, $level) {
                error_log("SMTP Debug: $str");
            };
            
            $mail->isSMTP();
            $mail->Host = SMTP_HOST;
            $mail->SMTPAuth = true;
            $mail->Username = SMTP_USERNAME;
            $mail->Password = SMTP_PASSWORD;
            $mail->SMTPSecure = (SMTP_PORT == 465) ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = SMTP_PORT;
            $mail->Timeout = 30;
            $mail->SMTPKeepAlive = true;
            
            error_log("📤 SMTP Config - Host: " . SMTP_HOST . ", Port: " . SMTP_PORT . ", User: " . SMTP_USERNAME);
            
            $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
            $mail->addAddress($checkout['email'], $checkout['user_name']);
            
            error_log("📧 From: " . SMTP_FROM_EMAIL . " To: {$checkout['email']}");
            
            $mail->isHTML(true);
            $mail->Subject = "CAUGHT YOU LOOKING.";
            
            $mail->Body = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body { 
            margin: 0; 
            padding: 0; 
            font-family: Arial, sans-serif; 
            background-color: #000000;
        }
        .email-container { 
            max-width: 600px; 
            margin: 0 auto; 
            background-color: #ffffff;
        }
        .header { 
            background-color: #000000; 
            padding: 30px 20px; 
            text-align: center;
        }
        .logo { 
            font-size: 32px; 
            font-weight: bold; 
            color: #ffffff; 
            letter-spacing: 2px;
        }
        .nav-links {
            margin-top: 15px;
            font-size: 14px;
        }
        .nav-links a {
            color: #ffffff;
            text-decoration: underline;
            margin: 0 15px;
            font-weight: 500;
        }
        .content { 
            padding: 40px 30px;
            background-color: #fff;
        }
        .headline { 
            font-size: 24px; 
            font-weight: bold; 
            color: #000; 
            margin-bottom: 20px;
            letter-spacing: 1px;
        }
        .greeting {
            font-size: 14px;
            color: #333;
            margin-bottom: 10px;
        }
        .message {
            font-size: 14px;
            color: #333;
            line-height: 1.6;
            margin-bottom: 30px;
        }
        .cta-button { 
            display: inline-block;
            background-color: #000000;
            color: #ffffff !important;
            padding: 15px 50px;
            text-decoration: none;
            font-weight: bold;
            font-size: 14px;
            letter-spacing: 1px;
            border: none;
            cursor: pointer;
            margin: 20px 0;
        }
        .cta-button:hover {
            background-color: #333333;
        }
        .footer { 
            background-color: #000000; 
            padding: 30px 20px;
            text-align: center;
        }
        .footer-logo {
            font-size: 28px;
            font-weight: bold;
            color: #ffffff;
            margin-bottom: 15px;
            letter-spacing: 2px;
        }
        .social-links {
            margin: 15px 0;
        }
        .social-links a {
            color: #ffffff;
            text-decoration: none;
            margin: 0 10px;
            font-size: 18px;
        }
        .footer-links {
            margin: 15px 0;
            font-size: 12px;
        }
        .footer-links a {
            color: #ffffff;
            text-decoration: underline;
            margin: 0 10px;
        }
        .footer-text {
            font-size: 11px;
            color: #ffffff;
            line-height: 1.5;
            margin-top: 15px;
        }
    </style>
</head>
<body>
    <div class="email-container">
        <!-- Header -->
        <div class="header">
            <div class="logo">LOHRI</div>
            <div class="nav-links">
                <a href="https://lohri.thedotstudios.com/user/shop?category=Women">Women</a>
                <a href="https://lohri.thedotstudios.com/user/shop?category=Men">Men</a>
                <a href="https://lohri.thedotstudios.com/user/cart">Clear Out</a>
            </div>
        </div>

        <!-- Main Content -->
        <div class="content">
            <div class="headline">CAUGHT YOU LOOKING.</div>
            
            <div class="greeting">Hi ' . htmlspecialchars($checkout['user_name']) . ',</div>
            
            <div class="message">
                The items you viewed just dropped in price<br>
                Remember, every piece of pre-loved is unique. So snap it up before someone else does.
            </div>

            <!-- Products -->
            ' . $productsHTML . '

            <!-- CTA Button -->
            <div style="text-align: center;">
                <a href="https://lohri.thedotstudios.com/user/cart" class="cta-button">MAKE IT YOURS</a>
            </div>
        </div>

        <!-- Footer -->
        <div class="footer">
            <div class="footer-logo">LOHRI</div>
            
            <div class="social-links">
                <a href="#">📷</a>
                <a href="#">f</a>
                <a href="#">â™Ē</a>
            </div>
            
            <div class="footer-links">
                <a href="' . $baseUrl . '/account">My Account</a>
                <a href="' . $baseUrl . '/help">Help</a>
                <a href="' . $baseUrl . '/unsubscribe">Unsubscribe</a>
            </div>
            
            <div class="footer-text">
                Unit 1 Brunel Road, Tottenham Industrial Centre, Gzorly, England, N17 GBZ<br>
                *Prices valid only for the time listed on the website<br>
                UK Company number: 09230162 - Yacht Trading Ltd.<br>
                Please note this is an unguarded address and security will be on site at all times.
            </div>
        </div>
    </div>
</body>
</html>';

            $mail->AltBody = "Hi {$checkout['user_name']}, the items you viewed just dropped in price. Complete your order: https://lohri.thedotstudios.com/user/cart";
            
            error_log("🔄 Attempting to send email...");
            
            if (!$mail->send()) {
                error_log("❌ Mail Error: " . $mail->ErrorInfo);
                throw new Exception("Failed to send: " . $mail->ErrorInfo);
            }
            
            error_log("✅ Email sent successfully");
            
            // Update database
            $updateStmt = $pdo->prepare("UPDATE abandoned_checkouts SET email_sent = 1, email_sent_at = NOW() WHERE id = ?");
            if (!$updateStmt->execute([$checkout['id']])) {
                error_log("âš ī¸ Failed to update database for ID: {$checkout['id']}");
            } else {
                error_log("✅ Database updated for ID: {$checkout['id']}");
            }
            
            $emailsSent++;
            error_log("✅ Email sent to: {$checkout['email']}");
            
            // Clear PHPMailer for next iteration
            $mail->clearAddresses();
            $mail->clearAttachments();
            
        } catch (Exception $e) {
            error_log("❌ Failed ID {$checkout['id']}: " . $e->getMessage());
            error_log("❌ Stack trace: " . $e->getTraceAsString());
            
            // Try to log the failure in database
            try {
                $failStmt = $pdo->prepare("UPDATE abandoned_checkouts SET email_error = ? WHERE id = ?");
                $failStmt->execute([$e->getMessage(), $checkout['id']]);
            } catch (Exception $dbError) {
                error_log("❌ Could not log error to database: " . $dbError->getMessage());
            }
        }
    }

    error_log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    error_log("📊 DONE: Sent: $emailsSent");
    error_log("============================================");

    echo "✅ Completed! Emails sent: $emailsSent\n";

} catch (Exception $e) {
    error_log("❌ ERROR: " . $e->getMessage());
    echo "❌ Error: " . $e->getMessage() . "\n";
}
?>

MMCT - 2023