<?php
header('Content-Type: application/json');

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../includes/auth.php';

$auth = new Auth();

// Check if user is logged in
if (!$auth->isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '請先登入']);
    exit();
}

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

$database = new Database();
$db = $database->getConnection();

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'POST':
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            $input = $_POST;
        }
        
        $action = $input['action'] ?? '';
        
        switch ($action) {
            case 'create_plan':
                createContentPlan($input, $db);
                break;
            case 'create_article':
                createArticle($input, $db);
                break;
            case 'update_plan':
                updateContentPlan($input, $db);
                break;
            case 'update_article':
                updateArticle($input, $db);
                break;
            default:
                echo json_encode(['success' => false, 'message' => '無效的操作']);
                break;
        }
        break;
        
    case 'GET':
        $action = $_GET['action'] ?? '';
        $brand_id = $_GET['brand_id'] ?? '';
        $plan_id = $_GET['plan_id'] ?? '';
        $article_id = $_GET['article_id'] ?? '';
        
        switch ($action) {
            case 'plans':
                getContentPlans($brand_id, $db);
                break;
            case 'plan':
                getContentPlan($plan_id, $db);
                break;
            case 'articles':
                getArticles($plan_id, $db);
                break;
            case 'article':
            case 'get_plan':
                getContentPlan($plan_id, $db);
                break;
                getArticle($article_id, $db);
                break;
            default:
                echo json_encode(['success' => false, 'message' => '無效的操作']);
                break;
        }
        break;
        
    case 'DELETE':
        $input = json_decode(file_get_contents('php://input'), true);
        $action = $input['action'] ?? '';
        
        switch ($action) {
            case 'delete_plan':
                deleteContentPlan($input['plan_id'], $db);
                break;
            case 'delete_article':
                deleteArticle($input['article_id'], $db);
                break;
            default:
                echo json_encode(['success' => false, 'message' => '無效的操作']);
                break;
        }
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => '不支援的請求方法']);
        break;
}

function createContentPlan($input, $db) {
    $brand_id = $input['brand_id'] ?? '';
    $title = trim($input['title'] ?? '');
    $description = trim($input['description'] ?? '');
    $target_keywords = trim($input['target_keywords'] ?? '');
    $duration_months = intval($input['duration_months'] ?? 3);
    $frequency_per_week = intval($input['frequency_per_week'] ?? 2);
    
    if (empty($brand_id) || empty($title)) {
        echo json_encode(['success' => false, 'message' => '品牌ID和計畫標題不能為空']);
        return;
    }
    
    try {
        $query = "INSERT INTO content_plans (brand_id, title, description, target_keywords, duration_months, frequency_per_week, status, created_at) 
                  VALUES (:brand_id, :title, :description, :target_keywords, :duration_months, :frequency_per_week, 'active', NOW())";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':brand_id', $brand_id);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':target_keywords', $target_keywords);
        $stmt->bindParam(':duration_months', $duration_months);
        $stmt->bindParam(':frequency_per_week', $frequency_per_week);
        
        if ($stmt->execute()) {
            $plan_id = $db->lastInsertId();
            
            // Generate content calendar
            generateContentCalendar($plan_id, $brand_id, $duration_months, $frequency_per_week, $db);
            
            echo json_encode([
                'success' => true,
                'message' => '內容計畫創建成功！',
                'data' => ['plan_id' => $plan_id]
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => '內容計畫創建失敗']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => '資料庫錯誤: ' . $e->getMessage()]);
    }
}

function createArticle($input, $db) {
    $plan_id = $input['plan_id'] ?? '';
    $title = trim($input['title'] ?? '');
    $content = trim($input['content'] ?? '');
    $keywords = trim($input['keywords'] ?? '');
    $publish_date = $input['publish_date'] ?? '';
    $status = $input['status'] ?? 'draft';
    
    if (empty($plan_id) || empty($title)) {
        echo json_encode(['success' => false, 'message' => '計畫ID和文章標題不能為空']);
        return;
    }
    
    try {
        $query = "INSERT INTO content_articles (plan_id, title, content, keywords, publish_date, status, created_at) 
                  VALUES (:plan_id, :title, :content, :keywords, :publish_date, :status, NOW())";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':plan_id', $plan_id);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':content', $content);
        $stmt->bindParam(':keywords', $keywords);
        $stmt->bindParam(':publish_date', $publish_date);
        $stmt->bindParam(':status', $status);
        
        if ($stmt->execute()) {
            $article_id = $db->lastInsertId();
            echo json_encode([
                'success' => true,
                'message' => '文章創建成功！',
                'data' => ['article_id' => $article_id]
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => '文章創建失敗']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => '資料庫錯誤: ' . $e->getMessage()]);
    }
}

function updateContentPlan($input, $db) {
    $plan_id = $input['plan_id'] ?? '';
    $title = trim($input['title'] ?? '');
    $description = trim($input['description'] ?? '');
    $target_keywords = trim($input['target_keywords'] ?? '');
    $status = $input['status'] ?? 'active';
    
    if (empty($plan_id) || empty($title)) {
        echo json_encode(['success' => false, 'message' => '計畫ID和標題不能為空']);
        return;
    }
    
    try {
        $query = "UPDATE content_plans SET title = :title, description = :description, target_keywords = :target_keywords, status = :status, updated_at = NOW() WHERE id = :plan_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':plan_id', $plan_id);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':target_keywords', $target_keywords);
        $stmt->bindParam(':status', $status);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => '內容計畫更新成功！']);
        } else {
            echo json_encode(['success' => false, 'message' => '內容計畫更新失敗']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => '資料庫錯誤: ' . $e->getMessage()]);
    }
}

function updateArticle($input, $db) {
    $article_id = $input['article_id'] ?? '';
    $title = trim($input['title'] ?? '');
    $content = trim($input['content'] ?? '');
    $keywords = trim($input['keywords'] ?? '');
    $publish_date = $input['publish_date'] ?? '';
    $status = $input['status'] ?? 'draft';
    
    if (empty($article_id) || empty($title)) {
        echo json_encode(['success' => false, 'message' => '文章ID和標題不能為空']);
        return;
    }
    
    try {
        $query = "UPDATE content_articles SET title = :title, content = :content, keywords = :keywords, publish_date = :publish_date, status = :status, updated_at = NOW() WHERE id = :article_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':article_id', $article_id);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':content', $content);
        $stmt->bindParam(':keywords', $keywords);
        $stmt->bindParam(':publish_date', $publish_date);
        $stmt->bindParam(':status', $status);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => '文章更新成功！']);
        } else {
            echo json_encode(['success' => false, 'message' => '文章更新失敗']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => '資料庫錯誤: ' . $e->getMessage()]);
    }
}

function getContentPlans($brand_id, $db) {
    try {
        if (empty($brand_id)) {
            $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";
            $stmt = $db->prepare($query);
        } else {
            $query = "SELECT cp.*, b.name as brand_name FROM content_plans cp 
                     LEFT JOIN brands b ON cp.brand_id = b.id 
                     WHERE cp.brand_id = :brand_id 
                     ORDER BY cp.created_at DESC";
            $stmt = $db->prepare($query);
            $stmt->bindParam(':brand_id', $brand_id);
        }
        
        $stmt->execute();
        $plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode(['success' => true, 'data' => $plans]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => '資料庫錯誤: ' . $e->getMessage()]);
    }
}

function getContentPlan($plan_id, $db) {
    try {
        $query = "SELECT cp.*, b.name as brand_name FROM content_plans cp 
                 LEFT JOIN brands b ON cp.brand_id = b.id 
                 WHERE cp.id = :plan_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':plan_id', $plan_id);
        $stmt->execute();
        $plan = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($plan) {
            echo json_encode(['success' => true, 'data' => $plan]);
        } else {
            echo json_encode(['success' => false, 'message' => '找不到內容計畫']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => '資料庫錯誤: ' . $e->getMessage()]);
    }
}

function getArticles($plan_id, $db) {
    try {
        $query = "SELECT * FROM content_articles WHERE plan_id = :plan_id ORDER BY publish_date ASC";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':plan_id', $plan_id);
        $stmt->execute();
        $articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode(['success' => true, 'data' => $articles]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => '資料庫錯誤: ' . $e->getMessage()]);
    }
}

function getArticle($article_id, $db) {
    try {
        $query = "SELECT * FROM content_articles WHERE id = :article_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':article_id', $article_id);
        $stmt->execute();
        $article = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($article) {
            echo json_encode(['success' => true, 'data' => $article]);
        } else {
            echo json_encode(['success' => false, 'message' => '找不到文章']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => '資料庫錯誤: ' . $e->getMessage()]);
    }
}

function deleteContentPlan($plan_id, $db) {
    try {
        // First delete all articles in this plan
        $delete_articles = "DELETE FROM content_articles WHERE plan_id = :plan_id";
        $stmt = $db->prepare($delete_articles);
        $stmt->bindParam(':plan_id', $plan_id);
        $stmt->execute();
        
        // Then delete the plan
        $delete_plan = "DELETE FROM content_plans WHERE id = :plan_id";
        $stmt = $db->prepare($delete_plan);
        $stmt->bindParam(':plan_id', $plan_id);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => '內容計畫刪除成功！']);
        } else {
            echo json_encode(['success' => false, 'message' => '內容計畫刪除失敗']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => '資料庫錯誤: ' . $e->getMessage()]);
    }
}

function deleteArticle($article_id, $db) {
    try {
        $query = "DELETE FROM content_articles WHERE id = :article_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':article_id', $article_id);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => '文章刪除成功！']);
        } else {
            echo json_encode(['success' => false, 'message' => '文章刪除失敗']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => '資料庫錯誤: ' . $e->getMessage()]);
    }
}

function generateContentCalendar($plan_id, $brand_id, $duration_months, $frequency_per_week, $db) {
    try {
        // Get brand information for content generation
        $brand_query = "SELECT * FROM brands WHERE id = :brand_id";
        $brand_stmt = $db->prepare($brand_query);
        $brand_stmt->bindParam(':brand_id', $brand_id);
        $brand_stmt->execute();
        $brand = $brand_stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$brand) {
            return;
        }
        
        // Generate content topics based on brand information
        $topics = generateContentTopics($brand, $duration_months, $frequency_per_week);
        
        // Insert articles into database
        foreach ($topics as $topic) {
            $query = "INSERT INTO content_articles (plan_id, title, content, keywords, publish_date, status, created_at) 
                      VALUES (:plan_id, :title, :content, :keywords, :publish_date, 'draft', NOW())";
            $stmt = $db->prepare($query);
            $stmt->bindParam(':plan_id', $plan_id);
            $stmt->bindParam(':title', $topic['title']);
            $stmt->bindParam(':content', $topic['content']);
            $stmt->bindParam(':keywords', $topic['keywords']);
            $stmt->bindParam(':publish_date', $topic['publish_date']);
            $stmt->execute();
        }
    } catch (Exception $e) {
        // Log error but don't fail the main operation
        error_log("Content calendar generation failed: " . $e->getMessage());
    }
}

function generateContentTopics($brand, $duration_months, $frequency_per_week) {
    $topics = [];
    $total_articles = $duration_months * 4 * $frequency_per_week; // Approximate weeks per month
    $start_date = new DateTime();
    
    // Base topics based on brand industry
    $base_topics = [
        '科技' => [
            '最新科技趨勢分析',
            '數位轉型成功案例',
            'AI技術應用指南',
            '雲端服務比較',
            '網路安全最佳實踐'
        ],
        '電子商務' => [
            '電商平台選擇指南',
            '線上銷售策略',
            '客戶體驗優化',
            '物流管理技巧',
            '電商行銷趨勢'
        ],
        '金融' => [
            '投資理財基礎',
            '金融科技創新',
            '風險管理策略',
            '數位銀行服務',
            '金融法規更新'
        ],
        '教育' => [
            '線上學習平台',
            '教育科技應用',
            '學習方法分享',
            '教育趨勢分析',
            '數位教學工具'
        ],
        '醫療' => [
            '健康管理指南',
            '醫療科技發展',
            '預防保健知識',
            '數位醫療服務',
            '醫療資訊安全'
        ]
    ];
    
    $industry_topics = $base_topics[$brand['industry']] ?? $base_topics['科技'];
    
    for ($i = 0; $i < $total_articles; $i++) {
        $topic_index = $i % count($industry_topics);
        $topic = $industry_topics[$topic_index];
        
        // Add brand-specific variations
        if ($i > 0 && $i % count($industry_topics) == 0) {
            $topic = $brand['name'] . '的' . $topic;
        }
        
        $publish_date = clone $start_date;
        $publish_date->add(new DateInterval('P' . ($i * 7 / $frequency_per_week) . 'D'));
        
        $topics[] = [
            'title' => $topic,
            'content' => "這是關於「{$topic}」的內容大綱。\n\n請根據品牌「{$brand['name']}」的特色和目標關鍵字「{$brand['target_keywords']}」來完善這篇文章的內容。\n\n建議包含：\n1. 引言和背景\n2. 主要內容\n3. 實用建議\n4. 結論和行動呼籲",
            'keywords' => $brand['target_keywords'],
            'publish_date' => $publish_date->format('Y-m-d')
        ];
    }
    
    return $topics;
}
?>
