<?php
// Cron job to send email notifications
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../vendor/phpmailer/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/../vendor/phpmailer/phpmailer/src/SMTP.php';
require_once __DIR__ . '/../vendor/phpmailer/phpmailer/src/Exception.php';

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

$functions = new InvestmentFunctions();

// Function to send notification emails
function sendNotificationEmail($to, $subject, $htmlContent) {
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host = SMTP_HOST;
        $mail->SMTPAuth = true;
        $mail->Username = SMTP_USERNAME;
        $mail->Password = SMTP_PASSWORD;
        $mail->SMTPSecure = SMTP_ENCRYPTION;
        $mail->Port = SMTP_PORT;

        $mail->setFrom(SITE_EMAIL, SITE_NAME);
        $mail->addAddress($to);

        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body = $htmlContent;

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Email sending failed to $to: " . $mail->ErrorInfo);
        return false;
    }
}

try {
    // Send daily profit notifications
    $stmt = $functions->db->prepare("
        SELECT u.email, u.username, t.amount, t.created_at, t.details
        FROM transactions t
        JOIN users u ON t.user_id = u.id
        WHERE t.type = 'profit'
        AND t.created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)
        AND t.status = 'completed'
        AND u.email_verified = 1
    ");
    $stmt->execute();
    $profit_transactions = $stmt->fetchAll();

    foreach ($profit_transactions as $transaction) {
        $details = json_decode($transaction['details'], true);
        $investment_id = $details['investment_id'] ?? '';

        // Create notification
        $notification_stmt = $functions->db->prepare("
            INSERT INTO notifications (user_id, type, title, message, data)
            SELECT u.id, 'profit', 'Daily Profit Added',
                   CONCAT('You have received $', ?, ' in daily profit from your investment.'),
                   JSON_OBJECT('amount', ?, 'investment_id', ?, 'date', ?)
            FROM users u WHERE u.email = ?
        ");
        $notification_stmt->execute([
            number_format($transaction['amount'], 2),
            $transaction['amount'],
            $investment_id,
            $transaction['created_at'],
            $transaction['email']
        ]);

        // Send email notification
        $emailContent = "
        <html>
        <head>
            <title>Daily Profit Added</title>
        </head>
        <body>
            <h2>Daily Profit Notification</h2>
            <p>Dear {$transaction['username']},</p>
            <p>Great news! You have received <strong>$" . number_format($transaction['amount'], 2) . "</strong> in daily profit from your investment.</p>
            <p><strong>Details:</strong></p>
            <ul>
                <li>Amount: $" . number_format($transaction['amount'], 2) . "</li>
                <li>Date: " . date('M j, Y g:i A', strtotime($transaction['created_at'])) . "</li>
                <li>Investment ID: {$investment_id}</li>
            </ul>
            <p>You can view your complete transaction history in your dashboard.</p>
            <br>
            <p>Best regards,<br>" . SITE_NAME . " Team</p>
        </body>
        </html>
        ";
        sendNotificationEmail($transaction['email'], 'Daily Profit Added - ' . SITE_NAME, $emailContent);
    }

    // Send investment completion notifications
    $stmt = $functions->db->prepare("
        SELECT u.email, u.username, i.id as investment_id, i.amount, i.total_profit,
               p.name as plan_name, p.principal_return
        FROM investments i
        JOIN users u ON i.user_id = u.id
        JOIN investment_plans p ON i.plan_id = p.id
        WHERE i.status = 'completed'
        AND i.updated_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)
        AND u.email_verified = 1
    ");
    $stmt->execute();
    $completed_investments = $stmt->fetchAll();

    foreach ($completed_investments as $investment) {
        // Create notification
        $notification_stmt = $functions->db->prepare("
            INSERT INTO notifications (user_id, type, title, message, data)
            SELECT u.id, 'investment_completed', 'Investment Completed',
                   CONCAT('Your investment of $', ?, ' in ', ?, ' plan has been completed. Total profit earned: $', ?),
                   JSON_OBJECT('investment_id', ?, 'amount', ?, 'profit', ?, 'plan_name', ?)
            FROM users u WHERE u.email = ?
        ");
        $notification_stmt->execute([
            number_format($investment['amount'], 2),
            $investment['plan_name'],
            number_format($investment['total_profit'], 2),
            $investment['investment_id'],
            $investment['amount'],
            $investment['total_profit'],
            $investment['plan_name'],
            $investment['email']
        ]);

        // Send email notification
        $emailContent = "
        <html>
        <head>
            <title>Investment Completed</title>
        </head>
        <body>
            <h2>Investment Completion Notification</h2>
            <p>Dear {$investment['username']},</p>
            <p>Congratulations! Your investment has been completed successfully.</p>
            <p><strong>Investment Summary:</strong></p>
            <ul>
                <li>Plan: {$investment['plan_name']}</li>
                <li>Principal Amount: $" . number_format($investment['amount'], 2) . "</li>
                <li>Total Profit Earned: $" . number_format($investment['total_profit'], 2) . "</li>
                <li>Principal Return: " . ($investment['principal_return'] ? 'Yes' : 'No') . "</li>
            </ul>
            <p>You can now withdraw your profits or reinvest in new plans.</p>
            <br>
            <p>Best regards,<br>" . SITE_NAME . " Team</p>
        </body>
        </html>
        ";
        sendNotificationEmail($investment['email'], 'Investment Completed - ' . SITE_NAME, $emailContent);
    }

    // Send deposit approval notifications
    $stmt = $functions->db->prepare("
        SELECT u.email, u.username, t.amount, t.created_at
        FROM transactions t
        JOIN users u ON t.user_id = u.id
        WHERE t.type = 'deposit'
        AND t.status = 'completed'
        AND t.updated_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)
        AND t.admin_action_by IS NOT NULL
        AND u.email_verified = 1
    ");
    $stmt->execute();
    $approved_deposits = $stmt->fetchAll();

    foreach ($approved_deposits as $deposit) {
        // Create notification
        $notification_stmt = $functions->db->prepare("
            INSERT INTO notifications (user_id, type, title, message, data)
            SELECT u.id, 'deposit_approved', 'Deposit Approved',
                   CONCAT('Your deposit of $', ?, ' has been approved and added to your account.'),
                   JSON_OBJECT('amount', ?, 'date', ?)
            FROM users u WHERE u.email = ?
        ");
        $notification_stmt->execute([
            number_format($deposit['amount'], 2),
            $deposit['amount'],
            $deposit['created_at'],
            $deposit['email']
        ]);

        // Send email notification
        $emailContent = "
        <html>
        <head>
            <title>Deposit Approved</title>
        </head>
        <body>
            <h2>Deposit Approval Notification</h2>
            <p>Dear {$deposit['username']},</p>
            <p>Great news! Your deposit has been approved and successfully added to your account.</p>
            <p><strong>Deposit Details:</strong></p>
            <ul>
                <li>Amount: $" . number_format($deposit['amount'], 2) . "</li>
                <li>Date: " . date('M j, Y g:i A', strtotime($deposit['created_at'])) . "</li>
            </ul>
            <p>The funds are now available in your account balance. You can start investing or view your transaction history in the dashboard.</p>
            <br>
            <p>Best regards,<br>" . SITE_NAME . " Team</p>
        </body>
        </html>
        ";
        sendNotificationEmail($deposit['email'], 'Deposit Approved - ' . SITE_NAME, $emailContent);
    }

    // Send withdrawal approval notifications
    $stmt = $functions->db->prepare("
        SELECT u.email, u.username, t.amount, t.net_amount, t.created_at
        FROM transactions t
        JOIN users u ON t.user_id = u.id
        WHERE t.type = 'withdrawal'
        AND t.status = 'completed'
        AND t.updated_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)
        AND t.admin_action_by IS NOT NULL
        AND u.email_verified = 1
    ");
    $stmt->execute();
    $approved_withdrawals = $stmt->fetchAll();

    foreach ($approved_withdrawals as $withdrawal) {
        // Create notification
        $notification_stmt = $functions->db->prepare("
            INSERT INTO notifications (user_id, type, title, message, data)
            SELECT u.id, 'withdrawal_approved', 'Withdrawal Approved',
                   CONCAT('Your withdrawal of $', ?, ' has been processed successfully.'),
                   JSON_OBJECT('amount', ?, 'net_amount', ?, 'date', ?)
            FROM users u WHERE u.email = ?
        ");
        $notification_stmt->execute([
            number_format($withdrawal['net_amount'], 2),
            $withdrawal['amount'],
            $withdrawal['net_amount'],
            $withdrawal['created_at'],
            $withdrawal['email']
        ]);

        // Send email notification
        $emailContent = "
        <html>
        <head>
            <title>Withdrawal Processed</title>
        </head>
        <body>
            <h2>Withdrawal Approval Notification</h2>
            <p>Dear {$withdrawal['username']},</p>
            <p>Your withdrawal request has been processed successfully!</p>
            <p><strong>Withdrawal Details:</strong></p>
            <ul>
                <li>Requested Amount: $" . number_format($withdrawal['amount'], 2) . "</li>
                <li>Net Amount: $" . number_format($withdrawal['net_amount'], 2) . "</li>
                <li>Date: " . date('M j, Y g:i A', strtotime($withdrawal['created_at'])) . "</li>
            </ul>
            <p>The funds have been sent to your designated payment method. Processing time may vary depending on your payment provider.</p>
            <br>
            <p>Best regards,<br>" . SITE_NAME . " Team</p>
        </body>
        </html>
        ";
        sendNotificationEmail($withdrawal['email'], 'Withdrawal Processed - ' . SITE_NAME, $emailContent);
    }

    // Mark old notifications as read (older than 7 days)
    $update_stmt = $functions->db->prepare("
        UPDATE notifications SET is_read = 1
        WHERE is_read = 0 AND created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)
    ");
    $update_stmt->execute();

    // Log summary
    $notifications_created = count($profit_transactions) + count($completed_investments) +
                           count($approved_deposits) + count($approved_withdrawals);

    if ($notifications_created > 0) {
        error_log("Send notifications cron completed: $notifications_created notifications created");
    }

} catch (Exception $e) {
    error_log("Cron job error in send-notifications.php: " . $e->getMessage());
}
?>
