<?php
// api/presenters/item.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';

// Detect method from _method parameter (for FormData)
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'POST' && isset($_POST['_method'])) {
    $method = strtoupper($_POST['_method']);
}

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

$user = requireAdmin();

$id = isset($_GET['id']) ? intval($_GET['id']) : null;

if (!$id) {
    sendError('Presenter ID required', 400);
}

// GET - Retrieve single presenter
if ($method === 'GET') {
    try {
        $stmt = $pdo->prepare("SELECT * FROM presenters WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $presenter = $stmt->fetch();
        
        if (!$presenter) {
            sendError('Presenter not found', 404);
        }
        
        if ($presenter['image']) {
            $presenter['image_url'] = R2_PUBLIC_URL . '/' . $presenter['image'];
        }
        
        sendSuccess($presenter);
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
// PUT - Update presenter
} elseif ($method === 'PUT' || ($method === 'POST' && isset($_POST['_method']))) {


    // Check if FormData or JSON
    $isMultipart = !empty($_FILES);
    
    if ($isMultipart) {
        // Handle FormData with image upload
        $name = $_POST['name'] ?? null;
        $bio = $_POST['bio'] ?? null;
        $image = null;
        
        // Check if presenter exists
        $stmt = $pdo->prepare("SELECT id, image FROM presenters WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $presenter = $stmt->fetch();
        
        if (!$presenter) {
            sendError('Presenter not found', 404);
        }
        
        // 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)) {
                // Delete old image if exists
                if ($presenter['image']) {
                    deleteFromR2($presenter['image']);
                }
                
                $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;
                }
            }
        }
        
        $updates = [];
        $params = [':id' => $id];
        
        if ($name !== null) {
            $updates[] = "name = :name";
            $params[':name'] = $name;
        }
        
        if ($bio !== null) {
            $updates[] = "bio = :bio";
            $params[':bio'] = $bio;
        }
        
        if ($image !== null) {
            $updates[] = "image = :image";
            $params[':image'] = $image;
        }
        
        if (empty($updates)) {
            sendError('No fields to update', 400);
        }
        
        $sql = "UPDATE presenters SET " . implode(', ', $updates) . " WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        sendSuccess(null, 'Presenter updated successfully');
        
    } else {
        // Handle JSON data
        $data = getRequestData();
        
        $stmt = $pdo->prepare("SELECT id FROM presenters WHERE id = :id");
        $stmt->execute([':id' => $id]);
        if (!$stmt->fetch()) {
            sendError('Presenter not found', 404);
        }
        
        $updates = [];
        $params = [':id' => $id];
        
        if (isset($data['name'])) {
            $updates[] = "name = :name";
            $params[':name'] = $data['name'];
        }
        
        if (isset($data['bio'])) {
            $updates[] = "bio = :bio";
            $params[':bio'] = $data['bio'];
        }
        
        if (isset($data['image'])) {
            $updates[] = "image = :image";
            $params[':image'] = $data['image'];
        }
        
        if (empty($updates)) {
            sendError('No fields to update', 400);
        }
        
        $sql = "UPDATE presenters SET " . implode(', ', $updates) . " WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        sendSuccess(null, 'Presenter updated successfully');
    }
    
// DELETE - Remove presenter
} elseif ($method === 'DELETE') {
    try {
        $stmt = $pdo->prepare("SELECT image FROM presenters WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $presenter = $stmt->fetch();
        
        if (!$presenter) {
            sendError('Presenter not found', 404);
        }
        
        // Check if presenter is linked to any podcasts or media
        $podcastStmt = $pdo->prepare("SELECT COUNT(*) FROM podcast_presenters WHERE presenter_id = :id");
        $podcastStmt->execute([':id' => $id]);
        $podcastCount = $podcastStmt->fetchColumn();
        
        $mediaStmt = $pdo->prepare("SELECT COUNT(*) FROM media_presenters WHERE presenter_id = :id");
        $mediaStmt->execute([':id' => $id]);
        $mediaCount = $mediaStmt->fetchColumn();
        
        if ($podcastCount > 0 || $mediaCount > 0) {
            sendError('Cannot delete presenter. They are linked to ' . $podcastCount . ' podcast(s) and ' . $mediaCount . ' media item(s).', 400);
        }
        
        // Delete image from R2 if exists
        if ($presenter['image']) {
            deleteFromR2($presenter['image']);
        }
        
        $stmt = $pdo->prepare("DELETE FROM presenters WHERE id = :id");
        $stmt->execute([$id]);
        
        sendSuccess(null, 'Presenter deleted successfully');
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
} else {
    sendError('Method not allowed', 405);
}
?>