<?php
require_once '../includes/auth.php';
require_once '../includes/language_manager.php';

$auth = new Auth();
$auth->requireLogin();

// Get brands data
require_once '../config/database.php';
$database = new Database();
$db = $database->getConnection();

$brands = [];
$query = "SELECT * FROM brands ORDER BY created_at DESC";
$stmt = $db->prepare($query);
$stmt->execute();
$brands = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get content plans
$plans_query = "SELECT cp.*, b.name as brand_name FROM content_plans cp 
               LEFT JOIN brands b ON cp.brand_id = b.id 
               ORDER BY cp.created_at DESC LIMIT 10";
$plans_stmt = $db->prepare($plans_query);
$plans_stmt->execute();
$recent_plans = $plans_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="<?php echo getCurrentLanguage(); ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo t('page_title'); ?></title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/admin.css" rel="stylesheet">
    <style>
        .language-switcher {
            padding: 15px 20px;
            border-top: 1px solid #e0e0e0;
            background: #f8f9fa;
        }
        
        .language-selector {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .language-selector i {
            color: #667eea;
            font-size: 1.1rem;
        }
        
        .language-selector select {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            background: white;
            font-size: 0.9rem;
            color: #333;
        }
        
        .language-selector select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .content-management {
            padding: 30px;
        }
        
        .content-plans-section {
            margin-bottom: 40px;
        }
        
        .content-plans-section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.5rem;
        }
        
        .plans-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
            gap: 25px;
        }
        
        .plan-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            transition: transform 0.3s ease;
        }
        
        .plan-card:hover {
            transform: translateY(-5px);
        }
        
        .plan-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .plan-header h3 {
            font-size: 1.2rem;
            color: #333;
            margin: 0;
        }
        
        .plan-status {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .status-active {
            background: #d4edda;
            color: #155724;
        }
        
        .status-paused {
            background: #fff3cd;
            color: #856404;
        }
        
        .status-completed {
            background: #cce5ff;
            color: #004085;
        }
        
        .plan-info {
            margin-bottom: 20px;
        }
        
        .info-item {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
            color: #666;
            font-size: 0.9rem;
        }
        
        .info-item i {
            width: 16px;
            color: #667eea;
        }
        
        .plan-description {
            margin-bottom: 20px;
        }
        
        .plan-description p {
            color: #666;
            line-height: 1.6;
        }
        
        .plan-actions {
            display: flex;
            gap: 10px;
        }
        
        .empty-state {
            text-align: center;
            padding: 80px 20px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
        }
        
        .empty-state i {
            font-size: 4rem;
            color: #667eea;
            margin-bottom: 20px;
        }
        
        .empty-state h3 {
            font-size: 1.5rem;
            color: #333;
            margin-bottom: 10px;
        }
        
        .empty-state p {
            color: #666;
            margin-bottom: 30px;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        .articles-modal .modal-content {
            max-width: 900px;
        }
        
        .articles-toolbar {
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .articles-list {
            max-height: 60vh;
            overflow-y: auto;
        }
        
        .article-item {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .article-info h4 {
            margin: 0 0 5px 0;
            color: #333;
        }
        
        .article-meta {
            font-size: 0.9rem;
            color: #666;
        }
        
        .article-actions {
            display: flex;
            gap: 10px;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .loading i {
            font-size: 2rem;
            margin-bottom: 15px;
        }
        
        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }
        
        .modal-content {
            background-color: white;
            margin: 5% auto;
            border-radius: 15px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .modal-header {
            padding: 25px 30px 20px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-header h2 {
            font-size: 1.5rem;
            font-weight: 600;
            color: #333;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 1.5rem;
            color: #666;
            cursor: pointer;
            padding: 5px;
        }
        
        .modal-body {
            padding: 30px;
        }
        
        .modal-footer {
            padding: 20px 30px 30px;
            border-top: 1px solid #e0e0e0;
            display: flex;
            justify-content: flex-end;
            gap: 15px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }
        
        .form-control {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .btn-info {
            background: #17a2b8;
            color: white;
        }
        
        .btn-info:hover {
            background: #138496;
        }
        
        .btn-warning {
            background: #ffc107;
            color: #212529;
        }
        
        .btn-warning:hover {
            background: #e0a800;
        }
        
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
            padding: 15px 20px;
            z-index: 2000;
            transform: translateX(400px);
            transition: transform 0.3s ease;
        }
        
        .notification.show {
            transform: translateX(0);
        }
        
        .notification-success {
            border-left: 4px solid #28a745;
        }
        
        .notification-error {
            border-left: 4px solid #dc3545;
        }
        
        .notification-info {
            border-left: 4px solid #17a2b8;
        }
        
        .notification-content {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .notification-content i {
            font-size: 1.2rem;
        }
        
        .notification-success .notification-content i {
            color: #28a745;
        }
        
        .notification-error .notification-content i {
            color: #dc3545;
        }
        
        .notification-info .notification-content i {
            color: #17a2b8;
        }
    </style>
</head>
<body>
    <div class="admin-layout">
        <!-- Sidebar -->
        <aside class="sidebar">
            <div class="sidebar-header">
                <div class="logo">
                    <i class="fas fa-robot"></i>
                    <span>SEO AI</span>
                </div>
            </div>
            
            <nav class="sidebar-nav">
                <ul>
                    <li>
                        <a href="dashboard.php">
                            <i class="fas fa-tachometer-alt"></i>
                            <span><?php echo t('nav_dashboard'); ?></span>
                        </a>
                    </li>
                    <li>
                        <a href="brands.php">
                            <i class="fas fa-building"></i>
                            <span><?php echo t('nav_brands'); ?></span>
                        </a>
                    </li>
                    <li>
                        <a href="reports.php">
                            <i class="fas fa-chart-bar"></i>
                            <span><?php echo t('nav_reports'); ?></span>
                        </a>
                    </li>
                    <li>
                        <a href="seo_analysis.php">
                            <i class="fas fa-search"></i>
                            <span><?php echo t('nav_seo_analysis'); ?></span>
                        </a>
                    </li>
                    <li class="active">
                        <a href="content.php">
                            <i class="fas fa-edit"></i>
                            <span><?php echo t('nav_content'); ?></span>
                        </a>
                    </li>
                    <li>
                        <a href="analytics.php">
                            <i class="fas fa-analytics"></i>
                            <span><?php echo t('nav_analytics'); ?></span>
                        </a>
                    </li>
                    <li>
                        <a href="settings.php">
                            <i class="fas fa-cog"></i>
                            <span><?php echo t('nav_settings'); ?></span>
                        </a>
                    </li>
                    <li>
                        <a href="help.php">
                            <i class="fas fa-question-circle"></i>
                            <span><?php echo t('nav_help'); ?></span>
                        </a>
                    </li>
                    <li>
                        <a href="profile.php">
                            <i class="fas fa-user"></i>
                            <span><?php echo t('nav_profile'); ?></span>
                        </a>
                    </li>
                </ul>
            </nav>
            
            <!-- Language Switcher -->
            <div class="language-switcher">
                <div class="language-selector">
                    <i class="fas fa-globe"></i>
                    <select id="languageSelect" onchange="changeLanguage(this.value)">
                        <option value="zh-TW" <?php echo getCurrentLanguage() === 'zh-TW' ? 'selected' : ''; ?>>繁體中文</option>
                        <option value="en-US" <?php echo getCurrentLanguage() === 'en-US' ? 'selected' : ''; ?>>English</option>
                    </select>
                </div>
            </div>
            
            <div class="sidebar-footer">
                <a href="logout.php" class="logout-btn">
                    <i class="fas fa-sign-out-alt"></i>
                    <span><?php echo t('nav_logout'); ?></span>
                </a>
            </div>
        </aside>
        
        <!-- Main Content -->
        <main class="main-content">
            <header class="header">
                <div class="header-left">
                    <h1><?php echo t('content_management'); ?></h1>
                    <p><?php echo t('content_plans'); ?></p>
                </div>
                <div class="header-right">
                    <button class="btn btn-primary" onclick="showCreatePlanModal()">
                        <i class="fas fa-plus"></i>
                        <?php echo t('create_plan'); ?>
                    </button>
                </div>
            </header>
            
            <div class="content-management">
                <!-- Content Plans -->
                <div class="content-plans-section">
                    <h2><?php echo t('content_plans'); ?></h2>
                    <?php if (empty($recent_plans)): ?>
                        <div class="empty-state">
                            <i class="fas fa-calendar-alt"></i>
                            <h3><?php echo t('no_plans'); ?></h3>
                            <p><?php echo t('create_first_plan'); ?></p>
                        </div>
                    <?php else: ?>
                        <div class="plans-grid">
                            <?php foreach ($recent_plans as $plan): ?>
                                <div class="plan-card">
                                    <div class="plan-header">
                                        <h3><?php echo htmlspecialchars($plan['title']); ?></h3>
                                        <span class="plan-status status-<?php echo $plan['status']; ?>">
                                            <?php echo getStatusName($plan['status']); ?>
                                        </span>
                                    </div>
                                    
                                    <div class="plan-info">
                                        <div class="info-item">
                                            <i class="fas fa-building"></i>
                                            <span><?php echo htmlspecialchars($plan['brand_name']); ?></span>
                                        </div>
                                        <div class="info-item">
                                            <i class="fas fa-calendar"></i>
                                            <span><?php echo t('plan_duration'); ?>: <?php echo $plan['duration_months']; ?> <?php echo t('duration_3_months'); ?></span>
                                        </div>
                                        <div class="info-item">
                                            <i class="fas fa-clock"></i>
                                            <span><?php echo t('plan_frequency'); ?>: <?php echo $plan['frequency_per_week']; ?> <?php echo t('frequency_2_week'); ?></span>
                                        </div>
                                        <div class="info-item">
                                            <i class="fas fa-tags"></i>
                                            <span><?php echo t('plan_keywords'); ?>: <?php echo htmlspecialchars($plan['target_keywords']); ?></span>
                                        </div>
                                    </div>
                                    
                                    <?php if (!empty($plan['description'])): ?>
                                        <div class="plan-description">
                                            <p><?php echo htmlspecialchars($plan['description']); ?></p>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <div class="plan-actions">
                                        <button class="btn btn-secondary" onclick="viewPlanDetails(<?php echo $plan['id']; ?>)">
                                            <i class="fas fa-eye"></i>
                                            <?php echo t('view_details'); ?>
                                        </button>
                                        <button class="btn btn-primary" onclick="manageArticles(<?php echo $plan['id']; ?>)">
                                            <i class="fas fa-edit"></i>
                                            <?php echo t('manage_articles'); ?>
                                        </button>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
    
    <!-- Create Plan Modal -->
    <div id="createPlanModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2><?php echo t('create_plan_title'); ?></h2>
                <button class="modal-close" onclick="closeModal('createPlanModal')">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="createPlanForm">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="planBrand"><?php echo t('select_brand'); ?> *</label>
                        <select id="planBrand" name="brand_id" class="form-control" required>
                            <option value=""><?php echo t('select_brand_placeholder'); ?></option>
                            <?php foreach ($brands as $brand): ?>
                                <option value="<?php echo $brand['id']; ?>"><?php echo htmlspecialchars($brand['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="planTitle"><?php echo t('plan_title'); ?> *</label>
                        <input type="text" id="planTitle" name="title" class="form-control" required placeholder="<?php echo t('plan_title_placeholder'); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="planDescription"><?php echo t('plan_description'); ?></label>
                        <textarea id="planDescription" name="description" class="form-control" rows="4" placeholder="<?php echo t('plan_description_placeholder'); ?>"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="planKeywords"><?php echo t('plan_keywords'); ?></label>
                        <textarea id="planKeywords" name="target_keywords" class="form-control" rows="3" placeholder="<?php echo t('plan_keywords_placeholder'); ?>"></textarea>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label for="planDuration"><?php echo t('plan_duration'); ?> *</label>
                            <select id="planDuration" name="duration_months" class="form-control" required>
                                <option value="1"><?php echo t('duration_1_month'); ?></option>
                                <option value="3" selected><?php echo t('duration_3_months'); ?></option>
                                <option value="6"><?php echo t('duration_6_months'); ?></option>
                                <option value="12"><?php echo t('duration_12_months'); ?></option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="planFrequency"><?php echo t('plan_frequency'); ?> *</label>
                            <select id="planFrequency" name="frequency_per_week" class="form-control" required>
                                <option value="1"><?php echo t('frequency_1_week'); ?></option>
                                <option value="2" selected><?php echo t('frequency_2_week'); ?></option>
                                <option value="3"><?php echo t('frequency_3_week'); ?></option>
                                <option value="5"><?php echo t('frequency_5_week'); ?></option>
                                <option value="7"><?php echo t('frequency_7_week'); ?></option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('createPlanModal')"><?php echo t('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i>
                        <?php echo t('create_plan_btn'); ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Plan Details Modal -->
    <div id="planDetailsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="planDetailsTitle"><?php echo t('plan_details_title'); ?></h2>
                <button class="modal-close" onclick="closeModal('planDetailsModal')">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <div id="planDetailsContent">
                    <div class="loading">
                        <i class="fas fa-spinner fa-spin"></i>
                        <p><?php echo t('loading'); ?></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal('planDetailsModal')"><?php echo t('close'); ?></button>
                <button type="button" class="btn btn-primary" onclick="editPlan()">
                    <i class="fas fa-edit"></i>
                    <?php echo t('edit_plan'); ?>
                </button>
            </div>
        </div>
    </div>
    
    <!-- Edit Plan Modal -->
    <div id="editPlanModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2><?php echo t('edit_plan_title'); ?></h2>
                <button class="modal-close" onclick="closeModal('editPlanModal')">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="editPlanForm">
                <div class="modal-body">
                    <input type="hidden" id="editPlanId" name="plan_id">
                    <div class="form-group">
                        <label for="editPlanTitle"><?php echo t('plan_title'); ?> *</label>
                        <input type="text" id="editPlanTitle" name="title" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label for="editPlanDescription"><?php echo t('plan_description'); ?></label>
                        <textarea id="editPlanDescription" name="description" class="form-control" rows="4"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="editPlanKeywords"><?php echo t('plan_keywords'); ?></label>
                        <textarea id="editPlanKeywords" name="target_keywords" class="form-control" rows="3"></textarea>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="editPlanDuration"><?php echo t('plan_duration'); ?> *</label>
                            <select id="editPlanDuration" name="duration_months" class="form-control" required>
                                <option value="1"><?php echo t('duration_1_month'); ?></option>
                                <option value="3"><?php echo t('duration_3_months'); ?></option>
                                <option value="6"><?php echo t('duration_6_months'); ?></option>
                                <option value="12"><?php echo t('duration_12_months'); ?></option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="editPlanFrequency"><?php echo t('plan_frequency'); ?> *</label>
                            <select id="editPlanFrequency" name="frequency_per_week" class="form-control" required>
                                <option value="1"><?php echo t('frequency_1_week'); ?></option>
                                <option value="2"><?php echo t('frequency_2_week'); ?></option>
                                <option value="3"><?php echo t('frequency_3_week'); ?></option>
                                <option value="5"><?php echo t('frequency_5_week'); ?></option>
                                <option value="7"><?php echo t('frequency_7_week'); ?></option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="editPlanStatus"><?php echo t('plan_status_label'); ?></label>
                        <select id="editPlanStatus" name="status" class="form-control">
                            <option value="active"><?php echo t('status_active'); ?></option>
                            <option value="paused"><?php echo t('status_paused'); ?></option>
                            <option value="completed"><?php echo t('status_completed'); ?></option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('editPlanModal')"><?php echo t('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i>
                        <?php echo t('update_plan'); ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Articles Management Modal -->
    <div id="articlesModal" class="modal">
        <div class="modal-content articles-modal">
            <div class="modal-header">
                <h2 id="articlesTitle"><?php echo t('articles_management'); ?></h2>
                <button class="modal-close" onclick="closeModal('articlesModal')">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <div class="articles-toolbar">
                    <button class="btn btn-primary" onclick="createArticle()">
                        <i class="fas fa-plus"></i>
                        <?php echo t('add_article'); ?>
                    </button>
                    <button class="btn btn-success" onclick="generateTitle()">
                        <i class="fas fa-magic"></i>
                        <?php echo t('generate_title'); ?>
                    </button>
                    <button class="btn btn-info" onclick="generateContent()">
                        <i class="fas fa-robot"></i>
                        <?php echo t('generate_content'); ?>
                    </button>
                    <button class="btn btn-warning" onclick="optimizeSEO()">
                        <i class="fas fa-search"></i>
                        <?php echo t('seo_optimize'); ?>
                    </button>
                </div>
                <div id="articlesList" class="articles-list">
                    <div class="loading">
                        <i class="fas fa-spinner fa-spin"></i>
                        <p><?php echo t('loading'); ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        let currentPlanId = null;
        
        document.addEventListener('DOMContentLoaded', function() {
            // Handle create plan form submission
            const createPlanForm = document.getElementById('createPlanForm');
            if (createPlanForm) {
                createPlanForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    createPlan();
                });
            }
            
            // Handle edit plan form submission
            const editPlanForm = document.getElementById('editPlanForm');
            if (editPlanForm) {
                editPlanForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    updatePlan();
                });
            }
        });
        
        function changeLanguage(language) {
            fetch('/api/language.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin',
                body: JSON.stringify({
                    language: language
                })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    location.reload();
                } else {
                    showNotification('<?php echo t('error_occurred'); ?>', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('<?php echo t('network_error'); ?>', 'error');
            });
        }
        
        function showCreatePlanModal() {
            document.getElementById('createPlanModal').style.display = 'block';
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        function createPlan() {
            const form = document.getElementById('createPlanForm');
            const formData = new FormData(form);
            const data = Object.fromEntries(formData);
            
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <?php echo t('loading'); ?>...';
            submitBtn.disabled = true;
            
            fetch('/api/content.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin',
                body: JSON.stringify({
                    action: 'create_plan',
                    ...data
                })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    showNotification('<?php echo t('plan_created_success'); ?>', 'success');
                    closeModal('createPlanModal');
                    form.reset();
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    showNotification('<?php echo t('error_occurred'); ?>: ' + result.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('<?php echo t('network_error'); ?>', 'error');
            })
            .finally(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        }
        
        function viewPlanDetails(planId) {
            currentPlanId = planId;
            document.getElementById('planDetailsModal').style.display = 'block';
            
            fetch(`/api/content.php?action=plan&plan_id=${planId}`, {
                credentials: 'same-origin'
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    const plan = result.data;
                    document.getElementById('planDetailsTitle').textContent = plan.title;
                    document.getElementById('planDetailsContent').innerHTML = `
                        <div class="plan-info">
                            <h3><?php echo t('plan_info'); ?></h3>
                            <p><strong><?php echo t('plan_title'); ?>:</strong> ${plan.title}</p>
                            <p><strong><?php echo t('plan_description'); ?>:</strong> ${plan.description || '<?php echo t('no_data'); ?>'}</p>
                            <p><strong><?php echo t('plan_keywords'); ?>:</strong> ${plan.target_keywords || '<?php echo t('no_data'); ?>'}</p>
                            <p><strong><?php echo t('plan_duration'); ?>:</strong> ${plan.duration_months} <?php echo t('duration_3_months'); ?></p>
                            <p><strong><?php echo t('plan_frequency'); ?>:</strong> ${plan.frequency_per_week} <?php echo t('frequency_2_week'); ?></p>
                            <p><strong><?php echo t('plan_status'); ?>:</strong> ${getStatusName(plan.status)}</p>
                            <p><strong><?php echo t('plan_created'); ?>:</strong> ${new Date(plan.created_at).toLocaleDateString()}</p>
                        </div>
                    `;
                } else {
                    document.getElementById('planDetailsContent').innerHTML = '<p><?php echo t('load_failed'); ?>: ' + result.message + '</p>';
                }
            })
            .catch(error => {
                document.getElementById('planDetailsContent').innerHTML = '<p><?php echo t('load_failed'); ?>: ' + error.message + '</p>';
            });
        }
        
        function manageArticles(planId) {
            currentPlanId = planId;
            document.getElementById('articlesModal').style.display = 'block';
            loadArticles(planId);
        }
        
        async function loadArticles(planId) {
            try {
                const response = await fetch(`/api/content.php?action=articles&plan_id=${planId}`, {
                    credentials: 'same-origin'
                });
                const result = await response.json();
                
                if (result.success) {
                    const articles = result.data;
                    if (articles.length > 0) {
                        document.getElementById('articlesList').innerHTML = articles.map(article => `
                            <div class="article-item">
                                <div class="article-info">
                                    <h4>${article.title}</h4>
                                    <div class="article-meta">
                                        <span><strong><?php echo t('article_status'); ?>:</strong> ${getArticleStatusName(article.status)}</span>
                                        <span><strong><?php echo t('article_created'); ?>:</strong> ${new Date(article.created_at).toLocaleDateString()}</span>
                                    </div>
                                </div>
                                <div class="article-actions">
                                    <button class="btn btn-secondary" onclick="editArticle(${article.id})">
                                        <i class="fas fa-edit"></i>
                                        <?php echo t('article_edit'); ?>
                                    </button>
                                    <button class="btn btn-secondary" onclick="deleteArticle(${article.id})">
                                        <i class="fas fa-trash"></i>
                                        <?php echo t('article_delete'); ?>
                                    </button>
                                </div>
                            </div>
                        `).join('');
                    } else {
                        document.getElementById('articlesList').innerHTML = `
                            <div class="empty-state">
                                <i class="fas fa-file-alt"></i>
                                <h3><?php echo t('no_articles'); ?></h3>
                                <p><?php echo t('create_first_article'); ?></p>
                            </div>
                        `;
                    }
                } else {
                    document.getElementById('articlesList').innerHTML = '<p><?php echo t('load_failed'); ?>: ' + result.message + '</p>';
                }
            } catch (error) {
                document.getElementById('articlesList').innerHTML = '<p><?php echo t('load_failed'); ?>: ' + error.message + '</p>';
            }
        }
        
        function createArticle() {
            // Redirect to article editor for new article
            window.location.href = `article_editor.php?plan_id=${currentPlanId}`;
        }
        
        function editArticle(articleId) {
            // Redirect to article editor for editing
            window.location.href = `article_editor.php?id=${articleId}`;
        }
        
        function deleteArticle(articleId) {
            if (confirm('<?php echo t('confirm_delete'); ?>')) {
                deleteArticleConfirm(articleId);
            }
        }
        
        function deleteArticleConfirm(articleId) {
            fetch('/api/content.php', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin',
                body: JSON.stringify({
                    action: 'delete_article',
                    article_id: articleId
                })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    showNotification('<?php echo t('article_deleted_success'); ?>', 'success');
                    loadArticles(currentPlanId);
                } else {
                    showNotification('<?php echo t('delete_failed'); ?>: ' + result.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('<?php echo t('network_error'); ?>', 'error');
            });
        }
        
        function editPlan() {
            editPlanModal();
        }
        
        function editPlanModal() {
            if (!currentPlanId) {
                showNotification('<?php echo t('select_plan_first'); ?>', 'error');
                return;
            }
            loadPlanForEdit(currentPlanId);
        }
        
        function loadPlanForEdit(planId) {
            fetch(`/api/content.php?action=get_plan&plan_id=${planId}`, {
                method: 'GET',
                credentials: 'same-origin'
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    const plan = result.data;
                    document.getElementById('editPlanId').value = plan.id;
                    document.getElementById('editPlanTitle').value = plan.title;
                    document.getElementById('editPlanDescription').value = plan.description || '';
                    document.getElementById('editPlanKeywords').value = plan.target_keywords || '';
                    document.getElementById('editPlanDuration').value = plan.duration_months;
                    document.getElementById('editPlanFrequency').value = plan.frequency_per_week;
                    document.getElementById('editPlanStatus').value = plan.status;
                    document.getElementById('editPlanModal').style.display = 'block';
                } else {
                    showNotification('<?php echo t('load_failed'); ?>: ' + result.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('<?php echo t('network_error'); ?>', 'error');
            });
        }
        
        function updatePlan() {
            const form = document.getElementById('editPlanForm');
            const formData = new FormData(form);
            const data = Object.fromEntries(formData);
            
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <?php echo t('loading'); ?>...';
            submitBtn.disabled = true;
            
            fetch('/api/content.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin',
                body: JSON.stringify({
                    action: 'update_plan',
                    ...data
                })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    showNotification('<?php echo t('plan_updated_success'); ?>', 'success');
                    closeModal('editPlanModal');
                    location.reload();
                } else {
                    showNotification('<?php echo t('update_failed'); ?>: ' + result.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('<?php echo t('network_error'); ?>', 'error');
            })
            .finally(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        }
        
        function generateTitle() {
            if (!currentPlanId) {
                showNotification('<?php echo t('select_plan_first'); ?>', 'error');
                return;
            }
            window.location.href = `article_editor.php?plan_id=${currentPlanId}&action=generate_title`;
        }
        
        function generateContent() {
            if (!currentPlanId) {
                showNotification('<?php echo t('select_plan_first'); ?>', 'error');
                return;
            }
            window.location.href = `article_editor.php?plan_id=${currentPlanId}&action=generate_content`;
        }
        
        function optimizeSEO() {
            if (!currentPlanId) {
                showNotification('<?php echo t('select_plan_first'); ?>', 'error');
                return;
            }
            window.location.href = `article_editor.php?plan_id=${currentPlanId}&action=optimize_seo`;
        }
        
        function getStatusName(status) {
            const statuses = {
                "active": "<?php echo t('status_active'); ?>",
                "paused": "<?php echo t('status_paused'); ?>",
                "completed": "<?php echo t('status_completed'); ?>",
                "draft": "<?php echo t('article_draft'); ?>",
                "in_progress": "<?php echo t('status_active'); ?>",
                "published": "<?php echo t('article_published'); ?>",
                "scheduled": "<?php echo t('article_scheduled'); ?>"
            };
            return statuses[status] || status;
        }
        
        function getArticleStatusName(status) {
            const statuses = {
                "draft": "<?php echo t('article_draft'); ?>",
                "published": "<?php echo t('article_published'); ?>",
                "scheduled": "<?php echo t('article_scheduled'); ?>"
            };
            return statuses[status] || status;
        }
        
        function showNotification(message, type = 'success') {
            const notification = document.createElement('div');
            notification.className = `notification notification-${type}`;
            notification.innerHTML = `
                <div class="notification-content">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
                    <span>${message}</span>
                </div>
            `;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.classList.add('show');
            }, 100);
            
            setTimeout(() => {
                notification.classList.remove('show');
                setTimeout(() => {
                    if (document.body.contains(notification)) {
                        document.body.removeChild(notification);
                    }
                }, 300);
            }, 3000);
        }
    </script>
</body>
</html>

<?php
function getStatusName($status) {
    $statuses = [
        'active' => t('status_active'),
        'paused' => t('status_paused'),
        'completed' => t('status_completed'),
        'draft' => t('article_draft'),
        'in_progress' => t('status_active'),
        'published' => t('article_published'),
        'scheduled' => t('article_scheduled')
    ];
    return $statuses[$status] ?? $status;
}

function getArticleStatusName($status) {
    $statuses = [
        'draft' => t('article_draft'),
        'published' => t('article_published'),
        'scheduled' => t('article_scheduled')
    ];
    return $statuses[$status] ?? $status;
}
?>
