<?php
// import_departments.php

// Include the reusable CORS handler
require_once __DIR__ . '/cors.php';


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

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/PdoCrud.php';

// Set up PdoCrud for the departments table
$crud = new PdoCrud($pdo, 'departments', 'id');

// This script only handles POST requests for batch import
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $insertedDepartments = [];
    $errors = [];

    try {
        $data = json_decode(file_get_contents('php://input'), true);

        if (!$data || !is_array($data)) {
            throw new Exception("Invalid JSON data. Expected an array of departments.");
        }

        foreach ($data as $departmentData) {
            try {
                // Validate department data before inserting
                if (!isset($departmentData['name'])) {
                    throw new Exception("Missing 'name' field in a department entry.");
                }

                // Add default status if not provided in the CSV
                if (!isset($departmentData['status'])) {
                    $departmentData['status'] = 'Active';
                }

                // Create the department and get the new ID
                $id = $crud->create($departmentData);
                $insertedDepartments[] = $id;

            } catch (Exception $e) {
                // Log the error and the data that caused it
                $errors[] = [
                    'data' => $departmentData,
                    'error' => $e->getMessage()
                ];
            }
        }
        
        // Respond with success message and a list of inserted IDs
        echo json_encode(['message' => 'Batch import completed.', 'inserted' => $insertedDepartments, 'errors' => $errors]);
        
    } catch (Exception $e) {
        http_response_code(400);
        echo json_encode(['error' => $e->getMessage()]);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}
