<?php
/**
 * Campaign Details and Analytics
 * View campaign performance and details
 */

session_start();

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: auth-system/login.php');
    exit;
}

require_once 'config/db.php';

$conn = $connection;
$campaign_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$campaign_id) {
    header('Location: admin-newsletter.php');
    exit;
}

// Get campaign details
$sql = "SELECT * FROM newsletter_campaigns WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $campaign_id);
$stmt->execute();
$campaign = $stmt->get_result()->fetch_assoc();

if (!$campaign) {
    header('Location: admin-newsletter.php');
    exit;
}

// Get recipient stats
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'sent' THEN 1 ELSE 0 END) as sent,
    SUM(CASE WHEN status = 'opened' THEN 1 ELSE 0 END) as opened,
    SUM(CASE WHEN status = 'clicked' THEN 1 ELSE 0 END) as clicked,
    SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed
FROM newsletter_campaign_recipients WHERE campaign_id = ?";
$stats_stmt = $conn->prepare($stats_sql);
$stats_stmt->bind_param('i', $campaign_id);
$stats_stmt->execute();
$stats = $stats_stmt->get_result()->fetch_assoc();

// Handle send action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'send_campaign') {
    $campaign_id = intval($_POST['campaign_id']);
    
    // Get all pending recipients
    $recipients_sql = "SELECT ncr.id, ns.email, ns.full_name
                       FROM newsletter_campaign_recipients ncr
                       JOIN newsletter_subscribers ns ON ncr.subscriber_id = ns.id
                       WHERE ncr.campaign_id = ? AND ncr.status = 'pending'";
    
    $recipients_stmt = $conn->prepare($recipients_sql);
    $recipients_stmt->bind_param('i', $campaign_id);
    $recipients_stmt->execute();
    $recipients = $recipients_stmt->get_result();
    
    $sent_count = 0;
    $failed_count = 0;
    
    while ($recipient = $recipients->fetch_assoc()) {
        // Simple generic campaign email
        $subject = 'Update from Faren Design';
        $message = '<html><body>';
        $message .= '<h2>Hello ' . htmlspecialchars($recipient['full_name']) . ',</h2>';
        $message .= '<p>Thank you for subscribing to our newsletter!</p>';
        $message .= '<p>Check out our latest updates and services.</p>';
        $message .= '</body></html>';
        
        if (sendCampaignEmail($recipient['email'], $subject, $message)) {
            // Mark as sent
            $update_sql = "UPDATE newsletter_campaign_recipients SET status = 'sent', sent_at = NOW() WHERE id = ?";
            $update_stmt = $conn->prepare($update_sql);
            $recipient_id = intval($recipient['id']);
            $update_stmt->bind_param('i', $recipient_id);
            $update_stmt->execute();
            $update_stmt->close();
            $sent_count++;
        } else {
            $failed_count++;
        }
    }
    
    // Update campaign status to sent
    $update_campaign_sql = "UPDATE newsletter_campaigns SET status = 'sent' WHERE id = ?";
    $update_campaign_stmt = $conn->prepare($update_campaign_sql);
    $update_campaign_stmt->bind_param('i', $campaign_id);
    $update_campaign_stmt->execute();
    $update_campaign_stmt->close();
    
    header('Location: campaign-details.php?id=' . $campaign_id . '&sent=1');
    exit;
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($campaign['campaign_name']); ?> - Campaign Details</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        body {
            font-family: 'DM Sans', Arial, sans-serif;
            background: #f5f5f5;
        }
        .container {
            max-width: 1000px;
            padding: 30px 20px;
        }
        .header {
            background: white;
            padding: 30px;
            border-radius: 8px;
            margin-bottom: 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .header h1 {
            color: #02000F;
            font-size: 28px;
            margin-bottom: 10px;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: 30px 0;
        }
        .stat-box {
            background: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            border-top: 4px solid #FF833B;
        }
        .stat-box h3 {
            color: #FF833B;
            font-size: 32px;
            font-weight: 600;
            margin: 0;
        }
        .stat-box p {
            color: #6C6D71;
            margin: 10px 0 0 0;
        }
        .content-card {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .btn-send {
            background: #FF833B;
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        .btn-send:hover {
            background: #E66D2A;
        }
        .campaign-preview {
            background: #f9f9f9;
            padding: 20px;
            border-radius: 5px;
            margin: 20px 0;
            max-height: 600px;
            overflow-y: auto;
        }
        .status-badge {
            display: inline-block;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        .badge-sent {
            background: #d4edda;
            color: #155724;
        }
        .badge-draft {
            background: #fff3cd;
            color: #856404;
        }
        .badge-scheduled {
            background: #d1ecf1;
            color: #0c5460;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <a href="admin-newsletter.php" style="color: #FF833B; text-decoration: none;">← Back to Campaigns</a>
            <h1><?php echo htmlspecialchars($campaign['campaign_name']); ?></h1>
            <p style="color: #6C6D71; margin: 10px 0;">
                <span class="status-badge badge-<?php echo $campaign['status']; ?>">
                    <?php echo ucfirst($campaign['status']); ?>
                </span>
            </p>
        </div>

        <div class="stats-grid">
            <div class="stat-box">
                <h3><?php echo $stats['total'] ?? 0; ?></h3>
                <p>Total Recipients</p>
            </div>
            <div class="stat-box">
                <h3><?php echo $stats['sent'] ?? 0; ?></h3>
                <p>Emails Sent</p>
            </div>
            <div class="stat-box">
                <h3><?php echo $stats['opened'] ?? 0; ?></h3>
                <p>Opened</p>
            </div>
            <div class="stat-box">
                <h3><?php echo $stats['clicked'] ?? 0; ?></h3>
                <p>Clicked</p>
            </div>
        </div>

        <div class="content-card">
            <h2>Campaign Details</h2>
            <table style="width: 100%; margin: 20px 0;">
                <tr>
                    <td style="padding: 10px; font-weight: 600; width: 200px;">Campaign Name:</td>
                    <td style="padding: 10px;"><?php echo htmlspecialchars($campaign['campaign_name']); ?></td>
                </tr>
                <tr style="background: #f9f9f9;">
                    <td style="padding: 10px; font-weight: 600;">Status:</td>
                    <td style="padding: 10px;"><span class="status-badge badge-<?php echo $campaign['status']; ?>"><?php echo ucfirst($campaign['status']); ?></span></td>
                </tr>
                <tr>
                    <td style="padding: 10px; font-weight: 600;">Recipients:</td>
                    <td style="padding: 10px;"><?php echo $stats['total'] ?? 0; ?></td>
                </tr>
            </table>

            <?php if ($campaign['status'] === 'draft' || $campaign['status'] === 'scheduled'): ?>
            <form method="POST" style="margin-top: 30px;">
                <input type="hidden" name="action" value="send_campaign">
                <input type="hidden" name="campaign_id" value="<?php echo $campaign_id; ?>">
                <button type="submit" class="btn-send" onclick="return confirm('Send this campaign to all confirmed subscribers?');">
                    Send Campaign Now
                </button>
            </form>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>

<?php
function sendCampaignEmail($to, $subject, $message) {
    try {
        // Load PHPMailer from auth-system
        $exception_path = __DIR__ . '/auth-system/PHPMailer/src/Exception.php';
        $smtp_path = __DIR__ . '/auth-system/PHPMailer/src/SMTP.php';
        $phpmailer_path = __DIR__ . '/auth-system/PHPMailer/src/PHPMailer.php';
        
        if (file_exists($phpmailer_path)) {
            require_once $exception_path;
            require_once $smtp_path;
            require_once $phpmailer_path;
            
            $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
            $mail->isSMTP();
            $mail->Host = 'mail.zemaraimgroups.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'info@zemaraimgroups.com';
            $mail->Password = 'zemaraimgroups@123';
            $mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;
            $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );
            $mail->setFrom('info@zemaraimgroups.com', 'Interior Design Solutions');
            $mail->addAddress($to);
            $mail->Subject = $subject;
            $mail->isHTML(true);
            $mail->Body = $message;
            return $mail->send();
        } else {
            // Fallback to basic mail()
            $header_str = "MIME-Version: 1.0\r\nContent-type: text/html; charset=UTF-8\r\n";
            $header_str .= "From: Faren Design <noreply@farendesign.com>\r\n";
            return mail($to, $subject, $message, $header_str);
        }
    } catch (\PHPMailer\PHPMailer\Exception $e) {
        error_log("PHPMailer Error: " . $e->getMessage());
        return false;
    } catch (Exception $e) {
        error_log("Exception: " . $e->getMessage());
        return false;
    }
}

$conn->close();
?>
