<?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;
        }
        
        $name = trim($input['name'] ?? '');
        $website = trim($input['website'] ?? '');
        $industry = trim($input['industry'] ?? '');
        $description = trim($input['description'] ?? '');
        $target_keywords = trim($input['target_keywords'] ?? '');
        $competitor_websites = trim($input['competitor_websites'] ?? '');
        
        // Validation
        if (empty($name)) {
            echo json_encode(['success' => false, 'message' => '品牌名稱不能為空']);
            exit();
        }
        
        if (strlen($name) > 255) {
            echo json_encode(['success' => false, 'message' => '品牌名稱不能超過255個字符']);
            exit();
        }
        
        // Check if brand name already exists
        $check_query = "SELECT COUNT(*) FROM brands WHERE name = :name";
        $check_stmt = $db->prepare($check_query);
        $check_stmt->bindParam(':name', $name);
        $check_stmt->execute();
        
        if ($check_stmt->fetchColumn() > 0) {
            echo json_encode(['success' => false, 'message' => '品牌名稱已存在']);
            exit();
        }
        
        // Validate website URL if provided
        if (!empty($website) && !filter_var($website, FILTER_VALIDATE_URL)) {
            echo json_encode(['success' => false, 'message' => '請輸入有效的網站網址']);
            exit();
        }
        
        try {
            $query = "INSERT INTO brands (name, website, industry, description, target_keywords, competitor_websites) 
                      VALUES (:name, :website, :industry, :description, :target_keywords, :competitor_websites)";
            $stmt = $db->prepare($query);
            $stmt->bindParam(':name', $name);
            $stmt->bindParam(':website', $website);
            $stmt->bindParam(':industry', $industry);
            $stmt->bindParam(':description', $description);
            $stmt->bindParam(':target_keywords', $target_keywords);
            $stmt->bindParam(':competitor_websites', $competitor_websites);
            
            if ($stmt->execute()) {
                $brand_id = $db->lastInsertId();
                
                // Get the created brand data
                $get_query = "SELECT * FROM brands WHERE id = :id";
                $get_stmt = $db->prepare($get_query);
                $get_stmt->bindParam(':id', $brand_id);
                $get_stmt->execute();
                $brand_data = $get_stmt->fetch(PDO::FETCH_ASSOC);
                
                echo json_encode([
                    'success' => true, 
                    'message' => '品牌新增成功！',
                    'data' => $brand_data
                ]);
            } else {
                echo json_encode(['success' => false, 'message' => '品牌新增失敗，請稍後再試']);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => '資料庫錯誤: ' . $e->getMessage()]);
        }
        break;
        
    case 'GET':
        try {
            $query = "SELECT * FROM brands ORDER BY created_at DESC";
            $stmt = $db->prepare($query);
            $stmt->execute();
            $brands = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode(['success' => true, 'data' => $brands]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => '資料庫錯誤: ' . $e->getMessage()]);
        }
        break;
        
    case 'PUT':
        $input = json_decode(file_get_contents('php://input'), true);
        $brand_id = $input['id'] ?? '';
        
        if (empty($brand_id)) {
            echo json_encode(['success' => false, 'message' => '品牌ID不能為空']);
            exit();
        }
        
        $name = trim($input['name'] ?? '');
        $website = trim($input['website'] ?? '');
        $industry = trim($input['industry'] ?? '');
        $description = trim($input['description'] ?? '');
        $target_keywords = trim($input['target_keywords'] ?? '');
        $competitor_websites = trim($input['competitor_websites'] ?? '');
        
        if (empty($name)) {
            echo json_encode(['success' => false, 'message' => '品牌名稱不能為空']);
            exit();
        }
        
        try {
            $query = "UPDATE brands SET name = :name, website = :website, industry = :industry, 
                      description = :description, target_keywords = :target_keywords, 
                      competitor_websites = :competitor_websites, updated_at = CURRENT_TIMESTAMP 
                      WHERE id = :id";
            $stmt = $db->prepare($query);
            $stmt->bindParam(':id', $brand_id);
            $stmt->bindParam(':name', $name);
            $stmt->bindParam(':website', $website);
            $stmt->bindParam(':industry', $industry);
            $stmt->bindParam(':description', $description);
            $stmt->bindParam(':target_keywords', $target_keywords);
            $stmt->bindParam(':competitor_websites', $competitor_websites);
            
            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()]);
        }
        break;
        
    case 'DELETE':
        $brand_id = $_GET['id'] ?? '';
        
        if (empty($brand_id)) {
            echo json_encode(['success' => false, 'message' => '品牌ID不能為空']);
            exit();
        }
        
        try {
            // Check if brand has related data
            $check_reports = $db->query("SELECT COUNT(*) FROM seo_reports WHERE brand_id = $brand_id")->fetchColumn();
            $check_content = $db->query("SELECT COUNT(*) FROM content_plans WHERE brand_id = $brand_id")->fetchColumn();
            $check_tracking = $db->query("SELECT COUNT(*) FROM seo_tracking WHERE brand_id = $brand_id")->fetchColumn();
            
            if ($check_reports > 0 || $check_content > 0 || $check_tracking > 0) {
                echo json_encode(['success' => false, 'message' => '無法刪除：此品牌還有相關的報告、內容或追蹤數據']);
                exit();
            }
            
            $query = "DELETE FROM brands WHERE id = :id";
            $stmt = $db->prepare($query);
            $stmt->bindParam(':id', $brand_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()]);
        }
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => '不支援的請求方法']);
        break;
}
?>
