<?php
// api/presenters/index.php

require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../config/r2.php';
require_once '../../helpers/response.php';
require_once '../../helpers/request.php';
require_once '../../helpers/auth.php';

$method = getRequestMethod();

if ($method === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$user = requireAdmin();

// GET - List presenters (no changes needed)
if ($method === 'GET') {
    $search = isset($_GET['search']) ? $_GET['search'] : null;
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
    $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;
    $include_media = isset($_GET['include_media']) ? filter_var($_GET['include_media'], FILTER_VALIDATE_BOOLEAN) : false;
    
    try {
        $sql = "SELECT p.*, 
                (SELECT COUNT(*) FROM media_presenters mp WHERE mp.presenter_id = p.id) as media_count
                FROM presenters p 
                WHERE 1=1";
        $params = [];
        
        if ($search) {
            $sql .= " AND (p.name LIKE :search OR p.bio LIKE :search)";
            $params[':search'] = "%{$search}%";
        }
        
        $sql .= " ORDER BY p.name ASC LIMIT :limit OFFSET :offset";
        $params[':limit'] = $limit;
        $params[':offset'] = $offset;
        
        $stmt = $pdo->prepare($sql);
        foreach ($params as $key => &$val) {
            if ($key === ':limit' || $key === ':offset') {
                $stmt->bindParam($key, $val, PDO::PARAM_INT);
            } else {
                $stmt->bindParam($key, $val);
            }
        }
        $stmt->execute();
        
        $presenters = $stmt->fetchAll();
        

        foreach ($presenters as &$presenter) {
            if ($presenter['image']) {
                $presenter['image_url'] = R2_PUBLIC_URL . '/' . $presenter['image'];
            } else {
                $presenter['image_url'] = null;
            }
            
            if ($include_media) {
                $mediaStmt = $pdo->prepare("
                    SELECT mp.*, m.title, m.type, m.media_id, m.is_premium
                    FROM media_presenters mp
                    JOIN media m ON m.id = mp.media_id
                    WHERE mp.presenter_id = :presenter_id
                    ORDER BY m.created_at DESC
                    LIMIT 20
                ");
                $mediaStmt->execute([':presenter_id' => $presenter['id']]);
                $media = $mediaStmt->fetchAll();
                
                foreach ($media as &$item) {
                    $item['url'] = R2_PUBLIC_URL . '/' . $item['media_id'];
                }
                $presenter['media'] = $media;
            }
        }
        
        $countStmt = $pdo->query("SELECT COUNT(*) FROM presenters");
        $total = $countStmt->fetchColumn();
        
        sendSuccess([
            'data' => $presenters,
            'pagination' => [
                'total' => intval($total),
                'limit' => $limit,
                'offset' => $offset
            ]
        ]);
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
// POST - Create new presenter (supports both JSON and FormData)
} elseif ($method === 'POST') {
    // Check if FormData (file upload) or JSON
    $isMultipart = !empty($_FILES);
    
    if ($isMultipart) {
        // Handle FormData with image upload
        $name = $_POST['name'] ?? '';
        $bio = $_POST['bio'] ?? '';
        $image = null;
        
        if (!$name) {
            sendError('Name is required', 400);
        }
        
        // Handle image upload
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['image'];
            $allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/jpg'];
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime_type = finfo_file($finfo, $file['tmp_name']);
            finfo_close($finfo);
            
            if (in_array($mime_type, $allowedTypes)) {
                $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                $safeTitle = preg_replace('/[^a-zA-Z0-9_-]/', '_', pathinfo($file['name'], PATHINFO_FILENAME));
                $image_key = 'presenters/' . $safeTitle . '_' . time() . '_' . uniqid() . '.' . $extension;
                
                $uploadResult = uploadToR2($file['tmp_name'], $image_key, $mime_type);
                if ($uploadResult['success']) {
                    $image = $image_key;
                }
            }
        }
        
        try {
            $stmt = $pdo->prepare("
                INSERT INTO presenters (name, bio, image) 
                VALUES (:name, :bio, :image)
            ");
            
            $stmt->execute([
                ':name' => $name,
                ':bio' => $bio,
                ':image' => $image
            ]);
            
            $presenter_id = $pdo->lastInsertId();
            
            sendSuccess([
                'id' => $presenter_id,
                'name' => $name,
                'bio' => $bio,
                'image' => $image
            ], 'Presenter created successfully');
            
        } catch (PDOException $e) {
            sendError('Database error: ' . $e->getMessage(), 500);
        }
        
    } else {
        // Handle JSON data (original way)
        $data = getRequestData();
        validateRequiredFields($data, ['name']);
        
        try {
            $stmt = $pdo->prepare("
                INSERT INTO presenters (name, bio, image) 
                VALUES (:name, :bio, :image)
            ");
            
            $stmt->execute([
                ':name' => $data['name'],
                ':bio' => $data['bio'] ?? null,
                ':image' => $data['image'] ?? null
            ]);
            
            $presenter_id = $pdo->lastInsertId();
            
            sendSuccess([
                'id' => $presenter_id,
                'name' => $data['name'],
                'bio' => $data['bio'] ?? null,
                'image' => $data['image'] ?? null
            ], 'Presenter created successfully');
            
        } catch (PDOException $e) {
            sendError('Database error: ' . $e->getMessage(), 500);
        }
    }
    
} else {
    sendError('Method not allowed', 405);
}
?>