<?php
/**
 * Admin Newsletter Management
 * Manage newsletter subscribers, campaigns, and approvals
 */

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;

if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

$admin_id = $_SESSION['user_id'];
$action = isset($_GET['action']) ? $_GET['action'] : 'subscribers';
$message = '';
$message_type = '';

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'approve_subscriber') {
            $subscriber_id = intval($_POST['subscriber_id']);
            $notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';
            
            $sql = "UPDATE newsletter_subscribers SET status = 'confirmed' WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('i', $subscriber_id);
            
            if ($stmt->execute()) {
                // Log approval
                $log_sql = "INSERT INTO newsletter_approval_logs (subscriber_id, admin_id, action, notes) VALUES (?, ?, 'approved', ?)";
                $log_stmt = $conn->prepare($log_sql);
                $log_stmt->bind_param('iis', $subscriber_id, $admin_id, $notes);
                $log_stmt->execute();
                $log_stmt->close();
                
                // Get subscriber details for email
                $sub_sql = "SELECT email, full_name FROM newsletter_subscribers WHERE id = ?";
                $sub_stmt = $conn->prepare($sub_sql);
                $sub_stmt->bind_param('i', $subscriber_id);
                $sub_stmt->execute();
                $sub_result = $sub_stmt->get_result();
                
                if ($sub_result->num_rows > 0) {
                    $sub = $sub_result->fetch_assoc();
                    // Send approval email
                    sendApprovalEmail($sub['email'], $sub['full_name']);
                }
                $sub_stmt->close();
                
                $message = 'Subscriber approved successfully!';
                $message_type = 'success';
            } else {
                $message = 'Failed to approve subscriber.';
                $message_type = 'danger';
            }
            $stmt->close();
            
        } elseif ($_POST['action'] === 'reject_subscriber') {
            $subscriber_id = intval($_POST['subscriber_id']);
            $reason = isset($_POST['reason']) ? trim($_POST['reason']) : '';
            
            $sql = "UPDATE newsletter_subscribers SET status = 'blocked' WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('i', $subscriber_id);
            
            if ($stmt->execute()) {
                $log_sql = "INSERT INTO newsletter_approval_logs (subscriber_id, admin_id, action, reason) VALUES (?, ?, 'rejected', ?)";
                $log_stmt = $conn->prepare($log_sql);
                $log_stmt->bind_param('iis', $subscriber_id, $admin_id, $reason);
                $log_stmt->execute();
                $log_stmt->close();
                
                $message = 'Subscriber rejected.';
                $message_type = 'success';
            } else {
                $message = 'Failed to reject subscriber.';
                $message_type = 'danger';
            }
            $stmt->close();
            
        } elseif ($_POST['action'] === 'create_campaign') {
            $campaign_name = trim($_POST['campaign_name']);
            $status = 'draft';
            
            $sql = "INSERT INTO newsletter_campaigns (campaign_name, status) 
                    VALUES (?, ?)";
            $stmt = $conn->prepare($sql);
            
            if (!$stmt) {
                $message = 'Database error: ' . $conn->error;
                $message_type = 'danger';
            } else {
                $stmt->bind_param('ss', $campaign_name, $status);
                
                if ($stmt->execute()) {
                    $campaign_id = $stmt->insert_id;
                    
                    // Add subscribers to campaign
                    $add_sql = "INSERT INTO newsletter_campaign_recipients (campaign_id, subscriber_id, status) 
                               SELECT ?, id, 'pending' FROM newsletter_subscribers WHERE status = 'confirmed'";
                    $add_stmt = $conn->prepare($add_sql);
                    if ($add_stmt) {
                        $add_stmt->bind_param('i', $campaign_id);
                        $add_stmt->execute();
                        $add_stmt->close();
                    }
                    
                    $message = 'Campaign created successfully!';
                    $message_type = 'success';
                } else {
                    $message = 'Failed to create campaign: ' . $stmt->error;
                    $message_type = 'danger';
                }
                $stmt->close();
            }
        }
    }
}

// Get newsletter statistics
$stats_sql = "SELECT 
    (SELECT COUNT(*) FROM newsletter_subscribers WHERE status = 'confirmed') as confirmed_subscribers,
    (SELECT COUNT(*) FROM newsletter_subscribers WHERE status = 'pending') as pending_subscribers,
    (SELECT COUNT(*) FROM newsletter_campaigns WHERE status = 'sent') as sent_campaigns,
    (SELECT COUNT(*) FROM newsletter_campaigns WHERE status = 'draft') as draft_campaigns";

$stats = $conn->query($stats_sql)->fetch_assoc();

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Newsletter Management - Admin Dashboard</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/fontawesome.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        body {
            font-family: 'DM Sans', Arial, sans-serif;
            background: #f5f5f5;
        }
        .navbar {
            background: linear-gradient(180deg, #1a1a2e 0%, #16213e 100%);
            padding: 15px 0;
        }
        .navbar-brand {
            color: white !important;
            font-size: 24px;
            font-weight: 600;
        }
        .nav-link {
            color: white !important;
            margin: 0 10px;
            transition: color 0.3s;
        }
        .nav-link:hover {
            color: #FF833B !important;
        }
        .admin-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 30px 20px;
        }
        .section-header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .section-header h2 {
            color: #02000F;
            font-size: 28px;
            margin-bottom: 10px;
            font-weight: 600;
        }
        .nav-tabs {
            border-bottom: 2px solid #FF833B;
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .nav-tabs .nav-link {
            color: #6C6D71 !important;
            border: none;
            padding: 10px 20px;
        }
        .nav-tabs .nav-link.active {
            color: #FF833B !important;
            border-bottom: 3px solid #FF833B;
            background: none;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            border-left: 4px solid #FF833B;
        }
        .stat-card h3 {
            color: #FF833B;
            font-size: 32px;
            font-weight: 600;
            margin: 0;
        }
        .stat-card 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-primary {
            background: #FF833B;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            color: white;
            cursor: pointer;
            transition: all 0.3s;
        }
        .btn-primary:hover {
            background: #E66D2A;
            color: white;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        table thead {
            background: #f5f5f5;
            border-bottom: 2px solid #e0e0e0;
        }
        table th {
            padding: 15px;
            text-align: left;
            color: #02000F;
            font-weight: 600;
        }
        table td {
            padding: 15px;
            border-bottom: 1px solid #e0e0e0;
        }
        table tr:hover {
            background: #f9f9f9;
        }
        .status-badge {
            display: inline-block;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        .badge-confirmed {
            background: #d4edda;
            color: #155724;
        }
        .badge-pending {
            background: #fff3cd;
            color: #856404;
        }
        .badge-blocked {
            background: #f8d7da;
            color: #721c24;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            color: #02000F;
            font-weight: 600;
            margin-bottom: 8px;
        }
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #e0e0e0;
            border-radius: 5px;
            font-family: 'DM Sans', Arial, sans-serif;
            font-size: 14px;
        }
        .alert {
            padding: 15px 20px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .action-buttons {
            display: flex;
            gap: 10px;
        }
        .action-buttons button {
            padding: 6px 12px;
            font-size: 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .btn-approve {
            background: #28a745;
            color: white;
        }
        .btn-approve:hover {
            background: #218838;
        }
        .btn-reject {
            background: #dc3545;
            color: white;
        }
        .btn-reject:hover {
            background: #c82333;
        }
        .editor-container {
            margin: 20px 0;
        }
    </style>
</head>
<body>
    <nav class="navbar">
        <div class="container-fluid">
            <a class="navbar-brand" href="admin-dashboard.php">Faren Design Admin</a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="admin-dashboard.php">Dashboard</a>
                <a class="nav-link" href="admin-newsletter.php">Newsletter</a>
                <a class="nav-link" href="auth-system/logout.php">Logout</a>
            </div>
        </div>
    </nav>

    <div class="admin-container">
        <?php if ($message): ?>
            <div class="alert alert-<?php echo $message_type; ?>">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>

        <div class="section-header">
            <h2>Newsletter Management</h2>
            <p>Manage subscribers, create campaigns, and track engagement</p>
        </div>

        <div class="stats-grid">
            <div class="stat-card">
                <h3><?php echo $stats['confirmed_subscribers']; ?></h3>
                <p>Confirmed Subscribers</p>
            </div>
            <div class="stat-card">
                <h3><?php echo $stats['pending_subscribers']; ?></h3>
                <p>Pending Approval</p>
            </div>
            <div class="stat-card">
                <h3><?php echo $stats['sent_campaigns']; ?></h3>
                <p>Campaigns Sent</p>
            </div>
            <div class="stat-card">
                <h3><?php echo $stats['draft_campaigns']; ?></h3>
                <p>Draft Campaigns</p>
            </div>
        </div>

        <div class="nav-tabs">
            <ul class="nav" role="tablist">
                <li class="nav-item">
                    <a class="nav-link <?php echo $action === 'subscribers' ? 'active' : ''; ?>" 
                       href="?action=subscribers">Subscribers</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo $action === 'campaigns' ? 'active' : ''; ?>" 
                       href="?action=campaigns">Campaigns</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo $action === 'create_campaign' ? 'active' : ''; ?>" 
                       href="?action=create_campaign">Create Campaign</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo $action === 'approvals' ? 'active' : ''; ?>" 
                       href="?action=approvals">Pending Approvals</a>
                </li>
            </ul>
        </div>

        <div class="content-card">
            <?php if ($action === 'subscribers'): ?>
                <h3>Newsletter Subscribers</h3>
                <table>
                    <thead>
                        <tr>
                            <th>Email</th>
                            <th>Name</th>
                            <th>Status</th>
                            <th>Subscribed</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $sql = "SELECT id, email, full_name, status, created_at FROM newsletter_subscribers ORDER BY created_at DESC";
                        $result = $conn->query($sql);
                        
                        if ($result && $result->num_rows > 0) {
                            while ($row = $result->fetch_assoc()) {
                                $status_class = 'badge-' . $row['status'];
                                echo '<tr>';
                                echo '<td>' . htmlspecialchars($row['email']) . '</td>';
                                echo '<td>' . htmlspecialchars($row['full_name'] ?: 'N/A') . '</td>';
                                echo '<td><span class="status-badge ' . $status_class . '">' . ucfirst($row['status']) . '</span></td>';
                                echo '<td>' . date('M d, Y', strtotime($row['created_at'])) . '</td>';
                                echo '<td><a href="mailto:' . htmlspecialchars($row['email']) . '" class="btn btn-primary btn-sm">Email</a></td>';
                                echo '</tr>';
                            }
                        } else {
                            echo '<tr><td colspan="5" style="text-align: center; padding: 30px;">No subscribers yet</td></tr>';
                        }
                        ?>
                    </tbody>
                </table>

            <?php elseif ($action === 'campaigns'): ?>
                <h3>Newsletter Campaigns</h3>
                <table>
                    <thead>
                        <tr>
                            <th>Campaign Name</th>
                            <th>Status</th>
                            <th>Recipients</th>
                            <th>Sent</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $sql = "SELECT id, campaign_name, status FROM newsletter_campaigns ORDER BY id DESC";
                        $result = $conn->query($sql);
                        
                        if ($result && $result->num_rows > 0) {
                            while ($row = $result->fetch_assoc()) {
                                // Count recipients for this campaign
                                $recipient_count_sql = "SELECT COUNT(*) as count FROM newsletter_campaign_recipients WHERE campaign_id = ?";
                                $recipient_stmt = $conn->prepare($recipient_count_sql);
                                $recipient_stmt->bind_param('i', $row['id']);
                                $recipient_stmt->execute();
                                $recipient_result = $recipient_stmt->get_result();
                                $recipient_count = $recipient_result->fetch_assoc()['count'] ?? 0;
                                $recipient_stmt->close();
                                
                                // Count sent emails for this campaign
                                $sent_count_sql = "SELECT COUNT(*) as count FROM newsletter_campaign_recipients WHERE campaign_id = ? AND status = 'sent'";
                                $sent_stmt = $conn->prepare($sent_count_sql);
                                $sent_stmt->bind_param('i', $row['id']);
                                $sent_stmt->execute();
                                $sent_result = $sent_stmt->get_result();
                                $sent_count = $sent_result->fetch_assoc()['count'] ?? 0;
                                $sent_stmt->close();
                                
                                echo '<tr>';
                                echo '<td><strong>' . htmlspecialchars($row['campaign_name']) . '</strong></td>';
                                echo '<td><span class="status-badge badge-' . $row['status'] . '">' . ucfirst($row['status']) . '</span></td>';
                                echo '<td>' . $recipient_count . '</td>';
                                echo '<td>' . $sent_count . '</td>';
                                echo '<td>-</td>';
                                echo '<td><a href="campaign-details.php?id=' . $row['id'] . '" class="btn btn-primary btn-sm">View</a></td>';
                                echo '</tr>';
                            }
                        } else {
                            echo '<tr><td colspan="6" style="text-align: center; padding: 30px;">No campaigns yet</td></tr>';
                        }
                        ?>
                    </tbody>
                </table>

            <?php elseif ($action === 'create_campaign'): ?>
                <h3>Create New Campaign</h3>
                <form method="POST" action="">
                    <input type="hidden" name="action" value="create_campaign">
                    
                    <div class="form-group">
                        <label>Campaign Name</label>
                        <input type="text" name="campaign_name" required placeholder="e.g., Summer Interior Trends">
                    </div>

                    <div class="form-group">
                        <label>Email Subject Line</label>
                        <input type="text" name="subject_line" required placeholder="What will your subscribers see?">
                    </div>

                    <div class="form-group">
                        <label>Preview Text (Optional)</label>
                        <input type="text" name="preview_text" placeholder="Brief preview of email content">
                    </div>

                    <div class="form-group">
                        <label>Template Type</label>
                        <select name="template_type">
                            <option value="custom">Custom</option>
                            <option value="service_announcement">Service Announcement</option>
                            <option value="project_showcase">Project Showcase</option>
                            <option value="promotion">Promotion</option>
                            <option value="update">Update</option>
                        </select>
                    </div>

                    <div class="form-group editor-container">
                        <label>Email Content (HTML)</label>
                        <textarea name="email_content" id="email_editor" required style="min-height: 400px;"></textarea>
                    </div>

                    <div class="form-group">
                        <label>Schedule Send (Optional)</label>
                        <input type="datetime-local" name="scheduled_at">
                    </div>

                    <button type="submit" class="btn btn-primary">Create Campaign</button>
                </form>

            <?php elseif ($action === 'approvals'): ?>
                <h3>Pending Subscriber Approvals</h3>
                <table>
                    <thead>
                        <tr>
                            <th>Email</th>
                            <th>Name</th>
                            <th>Phone</th>
                            <th>Subscribed</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $sql = "SELECT id, email, full_name, phone, created_at FROM newsletter_subscribers WHERE status = 'pending' ORDER BY created_at DESC";
                        $result = $conn->query($sql);
                        
                        if ($result && $result->num_rows > 0) {
                            while ($row = $result->fetch_assoc()) {
                                echo '<tr>';
                                echo '<td>' . htmlspecialchars($row['email']) . '</td>';
                                echo '<td>' . htmlspecialchars($row['full_name'] ?: 'N/A') . '</td>';
                                echo '<td>' . htmlspecialchars($row['phone'] ?: 'N/A') . '</td>';
                                echo '<td>' . date('M d, Y H:i', strtotime($row['created_at'])) . '</td>';
                                echo '<td>';
                                echo '<form method="POST" style="display: inline;">';
                                echo '<input type="hidden" name="action" value="approve_subscriber">';
                                echo '<input type="hidden" name="subscriber_id" value="' . $row['id'] . '">';
                                echo '<button type="submit" class="btn-approve">Approve</button>';
                                echo '</form>';
                                echo ' ';
                                echo '<form method="POST" style="display: inline;">';
                                echo '<input type="hidden" name="action" value="reject_subscriber">';
                                echo '<input type="hidden" name="subscriber_id" value="' . $row['id'] . '">';
                                echo '<input type="hidden" name="reason" value="Manual rejection">';
                                echo '<button type="submit" class="btn-reject">Reject</button>';
                                echo '</form>';
                                echo '</td>';
                                echo '</tr>';
                            }
                        } else {
                            echo '<tr><td colspan="5" style="text-align: center; padding: 30px;">No pending approvals</td></tr>';
                        }
                        ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Simple text editor if you want to add a WYSIWYG later
        // For now, users can input HTML directly
    </script>
</body>
</html>

<?php
$conn->close();

function sendApprovalEmail($email, $name) {
    $subject = 'Welcome to Faren Design Newsletter!';
    
    $message = "
    <html>
    <head>
        <style>
            body { font-family: 'DM Sans', Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: linear-gradient(180deg, #1a1a2e 0%, #16213e 100%); color: white; padding: 30px; text-align: center; border-radius: 5px 5px 0 0; }
            .header h1 { margin: 0; font-size: 28px; }
            .content { padding: 30px; background: #f8f9fa; border: 1px solid #e0e0e0; }
            .feature-list { margin: 20px 0; }
            .feature-list li { margin: 10px 0; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h1>Welcome to Faren Design!</h1>
            </div>
            <div class='content'>
                <p>Hi " . htmlspecialchars($name ?: 'there') . ",</p>
                
                <p>Congratulations! Your newsletter subscription has been approved and is now active.</p>
                
                <p>You'll now receive updates about:</p>
                <ul class='feature-list'>
                    <li>✓ Exclusive interior design inspirations</li>
                    <li>✓ Our latest project portfolios</li>
                    <li>✓ Special discounts and exclusive offers</li>
                    <li>✓ Interior design tips and trends</li>
                    <li>✓ New service launches</li>
                </ul>
                
                <p>We're excited to have you in our community of interior design enthusiasts!</p>
                
                <p>Best regards,<br>
                <strong>Faren Design Team</strong></p>
            </div>
        </div>
    </body>
    </html>";
    
    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 = 'smtp.gmail.comsmtp.gmail.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'mohamedhalith117@gmail.commohamedhalith117@gmail.com';
            $mail->Password = 'arctfbzmhhddkfqrarctfbzmhhddkfqr';
            $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('mohamedhalith117@gmail.com', 'Interior Design Solutions');
            $mail->addAddress($email);
            $mail->Subject = $subject;
            $mail->isHTML(true);
            $mail->Body = $message;
            $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";
            mail($email, $subject, $message, $header_str);
        }
    } catch (\PHPMailer\PHPMailer\Exception $e) {
        error_log("PHPMailer Error in sendApprovalEmail: " . $e->getMessage());
    } catch (Exception $e) {
        error_log("General Exception in sendApprovalEmail: " . $e->getMessage());
    }
}
?>
