<?php
require_once '../config/database.php';

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

$action = $_POST['action'] ?? '';

if (empty($action)) {
    echo json_encode(['success' => false, 'message' => 'Action is required']);
    exit;
}

// Function to handle image upload
function handleImageUpload($file, $type = 'main') {
    if (!isset($file) || $file['error'] !== UPLOAD_ERR_OK) {
        return '';
    }

    $uploadDir = '../uploads/products/';
    $fileName = uniqid() . '_' . basename($file['name']);
    $targetPath = $uploadDir . $fileName;

    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        return $fileName;  // Return just the filename without the path
    }
    return '';
}

// Function to delete image file
function deleteImageFile($fileName) {
    if (empty($fileName)) return;
    
    $filePath = '../uploads/products/' . $fileName;
    if (file_exists($filePath)) {
        unlink($filePath);
    }
}

try {
    switch($action) {
        case 'add':
            // Use barcode if provided, otherwise null
            $barcode = !empty($_POST['barcode']) ? $_POST['barcode'] : null;
            
            // Handle main product image
            $imagePath = '';
            if (isset($_FILES['productImageFile']) && $_FILES['productImageFile']['error'] === UPLOAD_ERR_OK) {
                $imagePath = handleImageUpload($_FILES['productImageFile'], 'main');
            } elseif (!empty($_POST['image'])) {
                $imagePath = $_POST['image']; // For URL-based images
            }

            // Handle alternative product images
            $altImagePaths = [];
            for ($i = 1; $i <= 3; $i++) {
                if (isset($_FILES["altimg{$i}"]) && $_FILES["altimg{$i}"]['error'] === UPLOAD_ERR_OK) {
                    $altImagePaths[$i] = handleImageUpload($_FILES["altimg{$i}"], "alt{$i}");
                } elseif (!empty($_POST["altimg{$i}"])) {
                    $altImagePaths[$i] = $_POST["altimg{$i}"]; // For URL-based images
                } else {
                    $altImagePaths[$i] = '';
                }
            }
            
            $stmt = $pdo->prepare("INSERT INTO {$tables['products']} (
                ProductImage, ProductName, ProductBrand, ProductCategory, SubCategory, 
                Barcode, MoreInfo, Report, BoycottCount,
                AlternativeImage1, AlternativeName1, AlternativeBrand1, AlternativeBarcode1,
                AlternativeImage2, AlternativeName2, AlternativeBrand2, AlternativeBarcode2,
                AlternativeImage3, AlternativeName3, AlternativeBrand3, AlternativeBarcode3
            ) VALUES (
                :image, :name, :brand, :category, :subcategory,
                :barcode, :moreinfo, 0, 0,
                :altimg1, :altname1, :altbrand1, :altbarcode1,
                :altimg2, :altname2, :altbrand2, :altbarcode2,
                :altimg3, :altname3, :altbrand3, :altbarcode3
            )");
            
            $stmt->execute([
                ':image' => $imagePath,
                ':name' => $_POST['name'] ?? '',
                ':brand' => $_POST['brand'] ?? '',
                ':category' => $_POST['category'] ?? '',
                ':subcategory' => $_POST['subcategory'] ?? '',
                ':barcode' => $barcode,
                ':moreinfo' => $_POST['moreinfo'] ?? '',
                ':altimg1' => $altImagePaths[1] ?? '',
                ':altname1' => $_POST['altname1'] ?? '',
                ':altbrand1' => $_POST['altbrand1'] ?? '',
                ':altbarcode1' => $_POST['altbarcode1'] ?? '',
                ':altimg2' => $altImagePaths[2] ?? '',
                ':altname2' => $_POST['altname2'] ?? '',
                ':altbrand2' => $_POST['altbrand2'] ?? '',
                ':altbarcode2' => $_POST['altbarcode2'] ?? '',
                ':altimg3' => $altImagePaths[3] ?? '',
                ':altname3' => $_POST['altname3'] ?? '',
                ':altbrand3' => $_POST['altbrand3'] ?? '',
                ':altbarcode3' => $_POST['altbarcode3'] ?? ''
            ]);
            
            echo json_encode(['success' => true, 'message' => 'Product added successfully']);
            break;

        case 'edit':
            $barcode = !empty($_POST['barcode']) ? $_POST['barcode'] : null;
            $originalId = !empty($_POST['original_id']) ? $_POST['original_id'] : null;
            
            if (!$originalId) {
                echo json_encode(['success' => false, 'message' => 'Product ID is required for editing']);
                exit;
            }
            
            // Check if new barcode already exists (if barcode is being changed)
            if ($barcode !== null) {
                $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM {$tables['products']} WHERE Barcode = ? AND ID != ?");
                $checkStmt->execute([$barcode, $originalId]);
                if ($checkStmt->fetchColumn() > 0) {
                    echo json_encode(['success' => false, 'message' => 'A product with this barcode already exists']);
                    exit;
                }
            }

            // Check if product name already exists (excluding current product)
            $productName = $_POST['name'] ?? '';
            if ($productName) {
                $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM {$tables['products']} WHERE ProductName = ? AND ID != ?");
                $checkStmt->execute([$productName, $originalId]);
                if ($checkStmt->fetchColumn() > 0) {
                    echo json_encode(['success' => false, 'message' => 'A product with this name already exists']);
                    exit;
                }
            }

            // Handle main product image
            $imagePath = '';
            if (isset($_FILES['productImageFile']) && $_FILES['productImageFile']['error'] === UPLOAD_ERR_OK) {
                $imagePath = handleImageUpload($_FILES['productImageFile'], 'main');
            } elseif (isset($_POST['existing_image']) && !empty($_POST['existing_image'])) {
                $imagePath = $_POST['existing_image'];
            }

            // Handle alternative product images
            $altImagePaths = [];
            for ($i = 1; $i <= 3; $i++) {
                if (isset($_FILES["altimg{$i}"]) && $_FILES["altimg{$i}"]['error'] === UPLOAD_ERR_OK) {
                    $altImagePaths[$i] = handleImageUpload($_FILES["altimg{$i}"], "alt{$i}");
                } elseif (isset($_POST["existing_altimg{$i}"]) && !empty($_POST["existing_altimg{$i}"])) {
                    $altImagePaths[$i] = $_POST["existing_altimg{$i}"];
                } else {
                    $altImagePaths[$i] = '';
                }
            }

            $sql = "UPDATE {$tables['products']} SET 
                    ProductName = ?, 
                    ProductBrand = ?, 
                    ProductCategory = ?, 
                    SubCategory = ?, 
                    Barcode = ?, 
                    MoreInfo = ?,
                    ProductImage = ?,
                    AlternativeImage1 = ?,
                    AlternativeName1 = ?,
                    AlternativeBrand1 = ?,
                    AlternativeBarcode1 = ?,
                    AlternativeImage2 = ?,
                    AlternativeName2 = ?,
                    AlternativeBrand2 = ?,
                    AlternativeBarcode2 = ?,
                    AlternativeImage3 = ?,
                    AlternativeName3 = ?,
                    AlternativeBrand3 = ?,
                    AlternativeBarcode3 = ?
                    WHERE ID = ?";
            
            $stmt = $pdo->prepare($sql);
            $result = $stmt->execute([
                $_POST['name'] ?? '',
                $_POST['brand'] ?? '',
                $_POST['category'] ?? '',
                $_POST['subcategory'] ?? '',
                $barcode,
                $_POST['moreinfo'] ?? '',
                $imagePath,
                $altImagePaths[1] ?? '',
                $_POST['altname1'] ?? '',
                $_POST['altbrand1'] ?? '',
                $_POST['altbarcode1'] ?? '',
                $altImagePaths[2] ?? '',
                $_POST['altname2'] ?? '',
                $_POST['altbrand2'] ?? '',
                $_POST['altbarcode2'] ?? '',
                $altImagePaths[3] ?? '',
                $_POST['altname3'] ?? '',
                $_POST['altbrand3'] ?? '',
                $_POST['altbarcode3'] ?? '',
                $originalId
            ]);
            
            if ($result) {
                echo json_encode(['success' => true, 'message' => 'Product updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update product']);
            }
            break;

        case 'delete':
            $id = $_POST['id'] ?? null;
            
            if (!$id) {
                echo json_encode(['success' => false, 'message' => 'Product ID is required for deletion']);
                exit;
            }

            // First get the product to get image filenames
            $stmt = $pdo->prepare("SELECT ProductImage, AlternativeImage1, AlternativeImage2, AlternativeImage3 FROM {$tables['products']} WHERE ID = ?");
            $stmt->execute([$id]);
            $product = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($product) {
                // Delete all associated images
                deleteImageFile($product['ProductImage']);
                deleteImageFile($product['AlternativeImage1']);
                deleteImageFile($product['AlternativeImage2']);
                deleteImageFile($product['AlternativeImage3']);

                // Delete the product from database
            $stmt = $pdo->prepare("DELETE FROM {$tables['products']} WHERE ID = ?");
            $result = $stmt->execute([$id]);
            
            if ($result) {
                    echo json_encode(['success' => true, 'message' => 'Product and associated images deleted successfully']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to delete product']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'Product not found']);
            }
            break;

        case 'get':
            $id = $_POST['id'] ?? null;
            
            if (!$id) {
                echo json_encode(['success' => false, 'message' => 'Product ID is required']);
                exit;
            }

            $stmt = $pdo->prepare("SELECT * FROM {$tables['products']} WHERE ID = ?");
            $stmt->execute([$id]);
            $product = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($product) {
                echo json_encode($product);
            } else {
                echo json_encode(['success' => false, 'message' => 'Product not found']);
            }
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
} catch(PDOException $e) {
    error_log("Database error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error occurred']);
} catch(Exception $e) {
    error_log("General error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'An error occurred']);
}
?> 