<?php
/**
 * Admin Import/Export API
 * Product import/export functionality
 */

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/Database.php';
require_once __DIR__ . '/../../includes/Auth.php';
require_once __DIR__ . '/../../includes/ImportExport.php';

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

// Check admin authentication
$auth = new Auth();
if (!$auth->isAdmin()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$importExport = new ImportExport();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            if ($action === 'export') {
                $filters = [
                    'category_id' => $_GET['category_id'] ?? null,
                    'search' => $_GET['search'] ?? null
                ];
                $importExport->exportProductsToCSV($filters);
                exit; // CSV output
            } elseif ($action === 'logs') {
                $type = $_GET['type'] ?? null;
                $logs = $importExport->getLogs($type);
                echo json_encode(['success' => true, 'logs' => $logs]);
            }
            break;

        case 'POST':
            if ($action === 'import') {
                if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'File upload failed']);
                    exit;
                }
                
                $filePath = $_FILES['file']['tmp_name'];
                $adminId = $auth->getUserId();
                
                $result = $importExport->importProductsFromCSV($filePath, $adminId);
                echo json_encode($result);
            }
            break;

        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>

