<?php
include 'bd/myData.php';
require_once 'auth.php';
include 'cors.php';
setupCORS();

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

requireAuth();

class BarcodeService {
    private $db;

    public function __construct() {
        global $pdo;
        $this->db = $pdo;
    }

    public function getBarcodeConfig() {
        try {
            connect();
            $query = "SELECT * FROM barcode_config WHERE active = true ORDER BY date_cre DESC LIMIT 1";
            $result = metodGet($query)->fetch(PDO::FETCH_ASSOC);
            
            if (!$result) {
                // Return default config if none exists
                return [
                    'format' => 'CODE128',
                    'prefix' => '',
                    'suffix' => ''
                ];
            }
            
            return $result;
        } catch (Exception $e) {
            throw new Exception("Database error in getBarcodeConfig: " . $e->getMessage());
        } finally {
            disconnect();
        }
    }

    public function getProductBarcode($reference) {
        try {
            connect();
            // Get product with custom barcode settings
            $query = "SELECT p.*, c.nom_categorie, m.description as marque_desc,
                            bc.format as default_format, bc.prefix, bc.suffix
                     FROM produits p 
                     LEFT JOIN categories c ON p.id_categorie = c.id_categorie 
                     LEFT JOIN marque m ON p.id_marque = m.id_marque
                     LEFT JOIN barcode_config bc ON bc.active = true
                     WHERE p.reference = :reference";
            
            $result = metodGet($query, [':reference' => $reference])->fetch(PDO::FETCH_ASSOC);

            if (!$result) {
                throw new Exception("Product not found: " . $reference);
            }

            // Generate barcode data
            $barcode_data = $result['use_custom_barcode'] ? 
                           $result['custom_barcode_value'] : 
                           $result['prefix'] . $result['reference'] . $result['suffix'];

            return [
                'reference' => $result['reference'],
                'barcode_data' => $barcode_data,
                'format' => $result['barcode_format'] ?? $result['default_format'] ?? 'CODE128',
                'designation' => $result['designation'],
                'marque' => $result['marque_desc'],
                'categorie' => $result['nom_categorie'],
                'useCustom' => (bool)$result['use_custom_barcode'],
                'customValue' => $result['custom_barcode_value']
            ];

        } catch (Exception $e) {
            throw new Exception("Error getting product barcode: " . $e->getMessage());
        } finally {
            disconnect();
        }
    }

    public function updateBarcodeConfig($data) {
        try {
            connect();
            
            // First, update the product-specific settings
            $updateProductQuery = "UPDATE produits 
                                 SET barcode_format = :format,
                                     use_custom_barcode = :use_custom,
                                     custom_barcode_value = :custom_value,
                                     user_upd = :user_upd
                                 WHERE reference = :reference";
            
            $productParams = [
                ':format' => $data['format'],
                ':use_custom' => $data['useCustom'] ? 1 : 0,
                ':custom_value' => $data['useCustom'] ? $data['customValue'] : null,
                ':user_upd' => $_SESSION['username'] ?? 'system',
                ':reference' => $data['reference']
            ];
            
            metodPut($updateProductQuery, $productParams, 'produits');

            // Then, update or insert global barcode configuration if needed
            if (isset($data['updateGlobalConfig']) && $data['updateGlobalConfig']) {
                // Get existing config
                $existingConfig = $this->getBarcodeConfig();
                
                if ($existingConfig) {
                    // Update existing config
                    $updateConfigQuery = "UPDATE barcode_config 
                                       SET format = :format,
                                           prefix = :prefix,
                                           suffix = :suffix,
                                           user_upd = :user_upd
                                       WHERE id = :id";
                    
                    $configParams = [
                        ':format' => $data['format'],
                        ':prefix' => $data['prefix'] ?? '',
                        ':suffix' => $data['suffix'] ?? '',
                        ':user_upd' => $_SESSION['username'] ?? 'system',
                        ':id' => $existingConfig['id']
                    ];
                    
                    metodPut($updateConfigQuery, $configParams, 'barcode_config');
                } else {
                    // Insert new config
                    $insertConfigQuery = "INSERT INTO barcode_config 
                                        (format, prefix, suffix, active, user_cre) 
                                        VALUES 
                                        (:format, :prefix, :suffix, 1, :user_cre)";
                    
                    $configParams = [
                        ':format' => $data['format'],
                        ':prefix' => $data['prefix'] ?? '',
                        ':suffix' => $data['suffix'] ?? '',
                        ':user_cre' => $_SESSION['username'] ?? 'system'
                    ];
                    
                    metodPost($insertConfigQuery, "SELECT LAST_INSERT_ID() as id", $configParams, 'barcode_config');
                }
            }

            return ['status' => 'success', 'message' => 'Barcode configuration updated successfully'];
        } catch (Exception $e) {
            throw new Exception("Error updating barcode configuration: " . $e->getMessage());
        } finally {
            disconnect();
        }
    }
}

// Request handling
try {
    $barcodeService = new BarcodeService();

    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        if (!isset($_GET['reference'])) {
            throw new Exception("Reference parameter is required");
        }

        $result = $barcodeService->getProductBarcode($_GET['reference']);
        echo json_encode(['status' => 'success', 'data' => $result]);
    }
    elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['reference'])) {
            throw new Exception("Reference parameter is required");
        }

        $result = $barcodeService->updateBarcodeConfig($data);
        echo json_encode($result);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'error' => $e->getMessage()]);
}
?>