<?php
/**
 * Collections API Endpoint
 * Handles fetching (GET), creating (POST), and updating (POST action=update) collections
 */

require_once '../../includes/db_connection.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

// Require authentication
requireAuth();

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

$method = $_SERVER['REQUEST_METHOD'];
$db = Database::getInstance()->getConnection();

// Handle GET Requests (List or Single)
if ($method === 'GET') {
    try {
        // Check if fetching single collection
        if (isset($_GET['id'])) {
            $id = (int)$_GET['id'];
            $stmt = $db->prepare("SELECT * FROM collections WHERE id = ?");
            $stmt->execute([$id]);
            $collection = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($collection) {
                // Adjust image path for frontend
                //$collection['image_url'] = $collection['image_url'] ? $collection['image_url'] : 'assets/images/placeholder.png';
                echo json_encode(['success' => true, 'data' => $collection]);
            } else {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Collection not found']);
            }
            exit;
        }

        // Get parameters (List Logic)
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
        $search = isset($_GET['search']) ? trim($_GET['search']) : '';
        $status = isset($_GET['status']) ? $_GET['status'] : '';
        
        // Disable pagination if limit is high (e.g. for dropdowns)
        $usePagination = $limit > 0;
        $offset = ($page - 1) * $limit;
        
        // Build query
        $where = [];
        $params = [];
        
        if (!empty($search)) {
            $where[] = "(c.name LIKE ? OR c.slug LIKE ?)";
            $params[] = "%{$search}%";
            $params[] = "%{$search}%";
        }
        
        if ($status !== '' && in_array($status, ['0', '1'])) {
            $where[] = "c.is_active = ?";
            $params[] = $status;
        }
        
        $whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';
        
        // Get total count
        $countQuery = "SELECT COUNT(*) as total FROM collections c $whereClause";
        $stmt = $db->prepare($countQuery);
        $stmt->execute($params);
        $totalCollections = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        // Get collections with product count
        $query = "
            SELECT 
                c.id,
                c.name,
                c.slug,
                c.image,
                c.is_active,
                c.created_at,
                (SELECT COUNT(*) FROM product_collections pc WHERE pc.collection_id = c.id) as product_count
            FROM collections c
            $whereClause
            ORDER BY c.created_at DESC
        ";

        if ($usePagination) {
            $query .= " LIMIT ? OFFSET ?";
            $params[] = $limit;
            $params[] = $offset;
        }
        
        $stmt = $db->prepare($query);
        $stmt->execute($params);
        $collections = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Format collections
        $formattedCollections = [];
        foreach ($collections as $collection) {
            $formattedCollections[] = [
                'id' => $collection['id'],
                'name' => $collection['name'],
                'slug' => $collection['slug'],
                'image' => $collection['image'] ?: 'assets/images/placeholder.png', // Fallback
                'product_count' => (int)$collection['product_count'],
                'status' => (int)$collection['is_active'] === 1 ? 'active' : 'inactive',
                'created_at' => date('d M Y', strtotime($collection['created_at']))
            ];
        }
        
        // Calculate pagination
        $totalPages = $usePagination ? ceil($totalCollections / $limit) : 1;
        
        echo json_encode([
            'success' => true,
            'data' => $formattedCollections,
            'pagination' => [
                'current_page' => $page,
                'total_pages' => $totalPages,
                'total_items' => $totalCollections,
                'per_page' => $limit,
                'has_next' => $page < $totalPages,
                'has_prev' => $page > 1
            ]
        ]);
        
    } catch (Exception $e) {
        error_log('Collections GET API error: ' . $e->getMessage());
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to fetch collections']);
    }
}

// Handle POST Requests (Create, Update, Delete)
elseif ($method === 'POST') {
    try {
        // Helper: Check both GET and POST for action to support efficient deletes
        $action = $_GET['action'] ?? $_POST['action'] ?? 'create';
        $deleteId = $_GET['id'] ?? $_POST['id'] ?? null;

        // --- DELETE LOGIC ---
        if ($action === 'delete' && $deleteId) {
            $stmt = $db->prepare("DELETE FROM collections WHERE id = ?");
            if ($stmt->execute([$deleteId])) {
                echo json_encode(['success' => true, 'message' => 'Collection deleted successfully']);
            } else {
                throw new Exception('Failed to delete collection');
            }
            exit;
        }

        // --- UPDATE LOGIC ---
        if ($action === 'update') {
            if (empty($_POST['id'])) {
                throw new Exception('Collection ID is required for update');
            }
            $id = (int)$_POST['id'];
            $name = trim($_POST['name']);
            $description = $_POST['description'] ?? '';
            $parent_id = !empty($_POST['parent_id']) ? $_POST['parent_id'] : null;
            $is_active = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1;
            $seo_title = $_POST['seo_title'] ?? $name;
            $seo_description = $_POST['seo_description'] ?? '';

            // Optional: Slug update logic (careful with existing links)
            $slug = $_POST['slug'] ?? '';
            if (empty($slug)) {
                 $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
            }
            
            // Check for duplicate slug (excluding self)
            $stmt = $db->prepare("SELECT COUNT(*) FROM collections WHERE slug = ? AND id != ?");
            $stmt->execute([$slug, $id]);
            if ($stmt->fetchColumn() > 0) {
                 $slug .= '-' . time();
            }

            // Handle Image Upload
            $image_sql = "";
            $params = [$name, $slug, $description, $parent_id, $seo_title, $seo_description, $is_active];

            if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = '../../assets/images/collections/';
                if (!file_exists($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }
                
                $fileExtension = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                
                if (!in_array($fileExtension, $allowedExtensions)) {
                    throw new Exception('Invalid file type');
                }
                
                $newFileName = $slug . '-' . time() . '.' . $fileExtension;
                $uploadPath = $uploadDir . $newFileName;
                
                if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadPath)) {
                    $image = 'assets/images/collections/' . $newFileName;
                    $image_sql = ", image = ?";
                    $params[] = $image;
                }
            }
            
            $params[] = $id; // Add ID for WHERE clause

            $sql = "UPDATE collections SET 
                    name = ?, 
                    slug = ?, 
                    description = ?, 
                    parent_id = ?, 
                    seo_title = ?, 
                    seo_description = ?, 
                    is_active = ? 
                    $image_sql
                    WHERE id = ?";

            $stmt = $db->prepare($sql);
            $stmt->execute($params);

            echo json_encode(['success' => true, 'message' => 'Collection updated successfully']);

        } 
        
        // --- CREATE LOGIC ---
        else {
            if (empty($_POST['name'])) {
                throw new Exception('Collection name is required');
            }

            $name = trim($_POST['name']);
            $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
            
            // Generate Slug
            $stmt = $db->prepare("SELECT COUNT(*) FROM collections WHERE slug = ?");
            $stmt->execute([$slug]);
            if ($stmt->fetchColumn() > 0) {
                $slug .= '-' . time();
            }

            $description = $_POST['description'] ?? '';
            $parent_id = !empty($_POST['parent_id']) ? $_POST['parent_id'] : null;
            $is_active = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1;
            $seo_title = $_POST['seo_title'] ?? $name;
            $seo_description = $_POST['seo_description'] ?? '';

            // Handle Image Upload
            $image = null;
            if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                // ... (Same upload logic) ...
                 $uploadDir = '../../assets/images/collections/';
                if (!file_exists($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }
                
                $fileExtension = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                
                if (in_array($fileExtension, $allowedExtensions)) {
                    $newFileName = $slug . '-' . time() . '.' . $fileExtension;
                    $uploadPath = $uploadDir . $newFileName;
                     if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadPath)) {
                        $image = 'assets/images/collections/' . $newFileName;
                    }
                }
            }

            $stmt = $db->prepare("
                INSERT INTO collections (name, slug, description, image, parent_id, seo_title, seo_description, is_active, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");
            
            $stmt->execute([
                $name,
                $slug,
                $description,
                $image,
                $parent_id,
                $seo_title,
                $seo_description,
                $is_active
            ]);

            echo json_encode([
                'success' => true,
                'message' => 'Collection created successfully',
                'id' => $db->lastInsertId()
            ]);
        }

    } catch (Exception $e) {
        error_log('Collections POST API error: ' . $e->getMessage());
        http_response_code(500);
        echo json_encode([
            'success' => false, 
            'message' => $e->getMessage()
        ]);
    }
} else {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
}
?>
