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

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

try {
    // Log the incoming request data for debugging
    error_log("Received POST data: " . print_r($_POST, true));

    $requestId = $_POST['request_id'] ?? null;
    
    if (!$requestId) {
        throw new Exception('Request ID is required');
    }

    // Start transaction early
    $pdo->beginTransaction();

    try {
        // Get the request data first to get the original image path
        $stmt = $pdo->prepare("SELECT product_image_url FROM {$tables['product_requests']} WHERE id = ?");
        $stmt->execute([$requestId]);
        $request = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$request) {
            throw new Exception('Request not found');
        }

        // Log the request data for debugging
        error_log("Request data: " . print_r($request, true));

        // Handle image upload
        $imagePath = ''; // Initialize with empty string instead of null
        if (isset($_FILES['productImageFile']) && $_FILES['productImageFile']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = '../uploads/products/';
            
            // Create products directory if it doesn't exist
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $fileName = uniqid() . '_' . basename($_FILES['productImageFile']['name']);
            $targetPath = $uploadDir . $fileName;

            if (move_uploaded_file($_FILES['productImageFile']['tmp_name'], $targetPath)) {
                $imagePath = $fileName; // Store only the filename
            } else {
                throw new Exception('Failed to upload product image');
            }
        } else {
            // Use the original request image
            $originalImagePath = $request['product_image_url'] ?? '';
            error_log("Original image path from request: " . $originalImagePath);

            if (!empty($originalImagePath)) {
                if (!str_starts_with($originalImagePath, 'http')) {
                    // First try the uploads/requests directory
                    $sourcePath = '../uploads/requests/' . basename($originalImagePath);
                    error_log("Attempting to access source path: " . $sourcePath);
                    error_log("File exists check: " . (file_exists($sourcePath) ? 'true' : 'false'));

                    if (file_exists($sourcePath)) {
                        // Create products directory if it doesn't exist
                        $uploadDir = '../uploads/products/';
                        if (!file_exists($uploadDir)) {
                            mkdir($uploadDir, 0777, true);
                        }

                        // Generate new filename and target path
                        $fileName = uniqid() . '_' . basename($originalImagePath);
                        $targetPath = $uploadDir . $fileName;
                        error_log("Target path for copy: " . $targetPath);

                        // Copy the file from requests to products folder
                        if (copy($sourcePath, $targetPath)) {
                            $imagePath = $fileName;
                            // Delete the original file from requests folder
                            unlink($sourcePath);
                            error_log("Successfully copied and deleted original file");
                        } else {
                            error_log("Failed to copy file. PHP error: " . error_get_last()['message']);
                            throw new Exception('Failed to move product image to products folder');
                        }
                    } else {
                        // Try alternative paths as fallback
                        $possiblePaths = [
                            $sourcePath,
                            '../' . $originalImagePath,
                            $originalImagePath
                        ];
                        
                        error_log("Checking possible paths: " . print_r($possiblePaths, true));
                        
                        foreach ($possiblePaths as $path) {
                            error_log("Checking path: " . $path . " - Exists: " . (file_exists($path) ? 'true' : 'false'));
                            if (file_exists($path)) {
                                $sourcePath = $path;
                                // Create products directory if it doesn't exist
                                $uploadDir = '../uploads/products/';
                                if (!file_exists($uploadDir)) {
                                    mkdir($uploadDir, 0777, true);
                                }

                                // Generate new filename and target path
                                $fileName = uniqid() . '_' . basename($originalImagePath);
                                $targetPath = $uploadDir . $fileName;
                                error_log("Found file at: " . $path);
                                error_log("Target path for copy: " . $targetPath);

                                // Copy the file from requests to products folder
                                if (copy($sourcePath, $targetPath)) {
                                    $imagePath = $fileName;
                                    // Delete the original file from requests folder
                                    unlink($sourcePath);
                                    error_log("Successfully copied and deleted original file");
                                    break;
                                } else {
                                    error_log("Failed to copy file. PHP error: " . error_get_last()['message']);
                                    throw new Exception('Failed to move product image to products folder');
                                }
                            }
                        }
                        
                        if (!file_exists($sourcePath)) {
                            // Instead of throwing an exception, just log the error and continue with empty image
                            error_log("Original image file not found in requests folder. Path checked: " . $sourcePath);
                            $imagePath = ''; // Set empty string for missing image
                        }
                    }
                } else {
                    // If it's a URL, just use it as is
                    $imagePath = $originalImagePath;
                    error_log("Using URL as image path: " . $imagePath);
                }
            } else {
                error_log("No image path found in request data");
                $imagePath = ''; // Set empty string for no image
            }
        }

        // Handle alternative product images
        $altImagePaths = [];
        for ($i = 1; $i <= 3; $i++) {
            if (isset($_FILES["altimg{$i}"]) && $_FILES["altimg{$i}"]['error'] === UPLOAD_ERR_OK) {
                $uploadDir = '../uploads/products/';
                if (!file_exists($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }
                $fileName = uniqid() . '_' . basename($_FILES["altimg{$i}"]['name']);
                $targetPath = $uploadDir . $fileName;
                if (move_uploaded_file($_FILES["altimg{$i}"]['tmp_name'], $targetPath)) {
                    $altImagePaths[$i] = $fileName;
                } else {
                    $altImagePaths[$i] = '';
                }
            } elseif (!empty($_POST["altimg{$i}"])) {
                $altImagePaths[$i] = $_POST["altimg{$i}"];
            } else {
                $altImagePaths[$i] = '';
            }
        }

        // Use barcode if provided, otherwise null
        $barcode = !empty($_POST['barcode']) ? $_POST['barcode'] : null;
        $productName = $_POST['name'] ?? '';

        // Check if product name already exists
        if ($productName) {
            $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM {$tables['products']} WHERE ProductName = ?");
            $checkStmt->execute([$productName]);
            if ($checkStmt->fetchColumn() > 0) {
                throw new Exception('A product with this name already exists');
            }
        }

        // Check if barcode already exists (if barcode is provided)
        if ($barcode !== null) {
            $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM {$tables['products']} WHERE Barcode = ?");
            $checkStmt->execute([$barcode]);
            if ($checkStmt->fetchColumn() > 0) {
                throw new Exception('A product with this barcode already exists');
            }
        }

        // Insert into products table using form data
        $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
        )");

        $params = [
            ':image' => $imagePath ?: '', // Ensure empty string if null
            ':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'] ?? ''
        ];

        // Log the parameters for debugging
        error_log("SQL Parameters: " . print_r($params, true));

        $stmt->execute($params);

        // Delete from products_req table
        $stmt = $pdo->prepare("DELETE FROM {$tables['product_requests']} WHERE id = ?");
        $stmt->execute([$requestId]);

        // Commit transaction
        $pdo->commit();

        echo json_encode(['success' => true, 'message' => 'Product request approved successfully']);

    } catch (Exception $e) {
        // Rollback transaction if it's still active
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        error_log("Error in approve_product_request.php: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
} catch (Exception $e) {
    error_log("Error in approve_product_request.php: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?> 