    <?php
    // backend.php

    // ত্রুটি রিপোর্টিং কনফিগারেশন (প্রোডাকশনে বন্ধ রাখুন)
    // error_reporting(E_ALL);
    // ini_set('display_errors', 0); // প্রোডাকশনে 0 রাখুন
    // ini_set('log_errors', 1);
    // ini_set('error_log', __DIR__ . '/../logs/php-error.log'); // আপনার লগ ফাইলের পাথ

    // প্রয়োজনীয় ফাইলগুলো Include করুন
    require_once __DIR__ . '/includes/config.php'; // __DIR__ ব্যবহার করে সঠিক পাথ নিশ্চিত করুন
    require_once __DIR__ . '/includes/db.php';    // $conn ভেরিয়েবল এখান থেকে আসবে
    require_once __DIR__ . '/includes/auth.php';  // অথেন্টিকেশন ফাংশন এখান থেকে আসবে
    require_once __DIR__ . '/includes/helpers.php'; // সহায়ক ফাংশন এখান থেকে আসবে


    header('Content-Type: application/json'); // JSON রেসপন্স সেট করুন

    $action = $_POST['action'] ?? null; // POST ডেটা থেকে action নিন

    // public_actions array auth.php ফাইলের ভিতরে আছে
    $public_actions = ['login', 'check_auth'];

    // auth.php এর requireAuth ফাংশন ব্যবহার করে প্রোটেক্টেড অ্যাকশন চেক করুন
    if (!in_array($action, $public_actions)) {
        requireAuth(); // ব্যবহারকারী লগইন করা না থাকলে এই ফাংশন এক্সিট করবে
    }

    // action হ্যান্ডলিং
    switch ($action) {
        case 'login':
            $username = $_POST['username'] ?? '';
            $password = $_POST['password'] ?? '';
            $response = handleLogin($conn, $username, $password);
            echo json_encode($response);
            break;

        case 'logout':
            $response = handleLogout();
            echo json_encode($response);
            break;

        case 'check_auth':
             $response = handleCheckAuth();
             echo json_encode($response);
            break;

        case 'fetch_requests':
            // requireAuth() ইতিমধ্যেই কল করা হয়েছে যদি লগইন প্রয়োজন হয়
            try {
                $stmt = $conn->query("SELECT id, product_name, product_image_url, product_brand, product_category, sub_category, barcode FROM Products_Req ORDER BY id DESC");
                $requests = $stmt->fetchAll();
                echo json_encode(['success' => true, 'requests' => $requests]);
            } catch (PDOException $e) {
                 error_log("Error fetching requests: " . $e->getMessage());
                echo json_encode(['success' => false, 'message' => 'Error fetching requests.']);
            }
            break;

        case 'fetch_request_by_id':
             // requireAuth() ইতিমধ্যেই কল করা হয়েছে
             $id = filter_var($_POST['id'] ?? null, FILTER_SANITIZE_NUMBER_INT);

             if (!$id || !is_numeric($id)) {
                echo json_encode(['success' => false, 'message' => 'Invalid request ID provided.']);
                exit;
             }

            try {
                $stmt = $conn->prepare("SELECT * FROM Products_Req WHERE id = :id LIMIT 1");
                $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                $stmt->execute();
                $request = $stmt->fetch();

                if ($request) {
                    echo json_encode(['success' => true, 'request' => $request]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Request not found.']);
                }
            } catch (PDOException $e) {
                 error_log("Error fetching request details (ID: {$id}): " . $e->getMessage());
                echo json_encode(['success' => false, 'message' => 'Error fetching request details.']);
            }
            break;

        case 'approve_request':
            // requireAuth() ইতিমধ্যেই কল করা হয়েছে
             $requestId = filter_var($_POST['id'] ?? null, FILTER_SANITIZE_NUMBER_INT);
             $productName = filter_var(trim($_POST['ProductName'] ?? ''), FILTER_SANITIZE_STRING);
             $barcode = filter_var(trim($_POST['Barcode'] ?? ''), FILTER_SANITIZE_STRING);
             $productBrand = filter_var(trim($_POST['ProductBrand'] ?? ''), FILTER_SANITIZE_STRING);
             $productCategory = filter_var(trim($_POST['ProductCategory'] ?? ''), FILTER_SANITIZE_STRING);
             $subCategory = filter_var(trim($_POST['SubCategory'] ?? ''), FILTER_SANITIZE_STRING);
             $moreInfo = filter_var(trim($_POST['MoreInfo'] ?? ''), FILTER_SANITIZE_STRING); // অথবা FILTER_UNSAFE_RAW যদি HTML/বিশেষ ক্যারেক্টার রাখতে চান, তবে আউটপুট স্যানিটাইজেশন জরুরি
             $mainImageData = $_POST['ProductImage'] ?? null;
             $mainImageSource = $_POST['ProductImageSource'] ?? 'none';


            if (!$requestId || !is_numeric($requestId)) {
                echo json_encode(['success' => false, 'message' => "Invalid request ID."]);
                exit;
            }
             if (empty($productName)) {
                echo json_encode(['success' => false, 'message' => "Product Name is required for approval."]);
                exit;
             }

            try {
                $conn->beginTransaction();

                 // --- ফাইনাল ডুপ্লিকেট চেক ইনসারশনের আগে ---
                 $duplicates = checkExistingProduct($conn, $productName, $barcode);
                 $duplicateMessages = [];
                 if ($duplicates['isDuplicateName']) {
                     $duplicateMessages[] = "Product Name '{$productName}' already exists.";
                 }
                 // বারকোড খালি না হলে এবং ডুপ্লিকেট হলে বার্তা যোগ করুন
                 if (!empty($barcode) && $duplicates['isDuplicateBarcode']) {
                      $duplicateMessages[] = "Barcode '{$barcode}' already exists.";
                 }

                 if (!empty($duplicateMessages)) {
                     $conn->rollBack(); // ইনসার্ট হবে না, তাই রোলব্যাক
                     echo json_encode(['success' => false, 'message' => "Could not approve: " . implode(" ", $duplicateMessages)]);
                     exit;
                 }
                 // --- ফাইনাল ডুপ্লিকেট চেক শেষ ---


                // মেইন প্রোডাক্ট ইমেজ প্রসেস করুন
                $base64MainImage = getImageBase64($mainImageData, $mainImageSource);
                 if ($mainImageSource !== 'none' && $base64MainImage === null) {
                     $conn->rollBack();
                     $errorMsg = ($mainImageSource === 'url') ?
                                 "Failed to fetch or process main product image from URL. Please check the URL or try uploading a file." :
                                 "Failed to process main product image file.";
                     echo json_encode(['success' => false, 'message' => $errorMsg]);
                     exit;
                 }


                // অল্টারনেটিভ প্রোডাক্ট ডেটা এবং ইমেজ প্রসেসিং
                 $productData = [
                     'ProductName' => $productName,
                     'ProductImage' => $base64MainImage,
                     'ProductBrand' => $productBrand,
                     'ProductCategory' => $productCategory,
                     'SubCategory' => $subCategory,
                     'Barcode' => $barcode,
                     'MoreInfo' => $moreInfo,
                 ];

                for($i = 1; $i <= 3; $i++) {
                    $altName = filter_var(trim($_POST["AlternativeName{$i}"] ?? ''), FILTER_SANITIZE_STRING);
                    $altBrand = filter_var(trim($_POST["AlternativeBrand{$i}"] ?? ''), FILTER_SANITIZE_STRING);
                    $altBarcode = filter_var(trim($_POST["AlternativeBarcode{$i}"] ?? ''), FILTER_SANITIZE_STRING);
                    $altImageData = $_POST["AlternativeImage{$i}"] ?? null;
                    $altImageSource = $_POST["AlternativeImageSource{$i}"] ?? 'none';

                    $base64AltImage = null;
                    if (!empty($altImageData) && $altImageSource !== 'none') {
                        $base64AltImage = getImageBase64($altImageData, $altImageSource);
                        if ($base64AltImage === null) {
                             $conn->rollBack();
                              $errorMsg = ($altImageSource === 'url') ?
                                          "Failed to fetch or process image for Alternative {$i} from URL. Please check the URL or try uploading a file." :
                                          "Failed to process image file for Alternative {$i}.";
                             echo json_encode(['success' => false, 'message' => $errorMsg]);
                             exit;
                        }
                    }

                    $productData["AlternativeName{$i}"] = $altName;
                    $productData["AlternativeBrand{$i}"] = $altBrand;
                    $productData["AlternativeBarcode{$i}"] = $altBarcode;
                    $productData["AlternativeImage{$i}"] = $base64AltImage;
                }


                // Products টেবিলে ইনসার্ট করুন
                 $columns = implode(', ', array_keys($productData));
                 $placeholders = implode(', ', array_fill(0, count($productData), '?'));
                $insertSql = "INSERT INTO Products ($columns) VALUES ($placeholders)";
                $stmt = $conn->prepare($insertSql);
                $stmt->execute(array_values($productData));

                // Products_Req টেবিল থেকে ডিলিট করুন
                $deleteSql = "DELETE FROM Products_Req WHERE id = :id";
                $stmt = $conn->prepare($deleteSql);
                $stmt->bindParam(':id', $requestId, PDO::PARAM_INT);
                $stmt->execute();

                $conn->commit();

                echo json_encode(['success' => true, 'message' => 'Product request approved and added to products successfully.']);

            } catch (PDOException $e) {
                 $conn->rollBack();
                 error_log("Database error during approval (Req ID: {$requestId}): " . $e->getMessage());
                echo json_encode(['success' => false, 'message' => 'Database error during approval.']);
            } catch (Exception $e) {
                 $conn->rollBack();
                 error_log("General error during approval (Req ID: {$requestId}): " . $e->getMessage());
                 echo json_encode(['success' => false, 'message' => 'An unexpected error occurred during approval.']);
            }
            break;

        case 'add_product': // সরাসরি প্রোডাক্ট যোগ করার অ্যাকশন
             // requireAuth() ইতিমধ্যেই কল করা হয়েছে
             $productName = filter_var(trim($_POST['ProductName'] ?? ''), FILTER_SANITIZE_STRING);
             $barcode = filter_var(trim($_POST['Barcode'] ?? ''), FILTER_SANITIZE_STRING);
             $productBrand = filter_var(trim($_POST['ProductBrand'] ?? ''), FILTER_SANITIZE_STRING);
             $productCategory = filter_var(trim($_POST['ProductCategory'] ?? ''), FILTER_SANITIZE_STRING);
             $subCategory = filter_var(trim($_POST['SubCategory'] ?? ''), FILTER_SANITIZE_STRING);
             $moreInfo = filter_var(trim($_POST['MoreInfo'] ?? ''), FILTER_SANITIZE_STRING); // অথবা FILTER_UNSAFE_RAW
             $mainImageData = $_POST['ProductImage'] ?? null;
             $mainImageSource = $_POST['ProductImageSource'] ?? 'none';

             if (empty($productName)) {
                echo json_encode(['success' => false, 'message' => "Product Name is required."]);
                exit;
             }

             try {
                 // --- ফাইনাল ডুপ্লিকেট চেক ইনসারশনের আগে ---
                 $duplicates = checkExistingProduct($conn, $productName, $barcode);
                 $duplicateMessages = [];
                 if ($duplicates['isDuplicateName']) {
                     $duplicateMessages[] = "Product Name '{$productName}' already exists.";
                 }
                  // বারকোড খালি না হলে এবং ডুপ্লিকেট হলে বার্তা যোগ করুন
                 if (!empty($barcode) && $duplicates['isDuplicateBarcode']) {
                      $duplicateMessages[] = "Barcode '{$barcode}' already exists.";
                 }

                 if (!empty($duplicateMessages)) {
                     echo json_encode(['success' => false, 'message' => "Could not add product: " . implode(" ", $duplicateMessages)]);
                     exit;
                 }
                 // --- ফাইনাল ডুপ্লিকেট চেক শেষ ---


                 // মেইন প্রোডাক্ট ইমেজ প্রসেস করুন
                 $base64MainImage = getImageBase64($mainImageData, $mainImageSource);
                  if ($mainImageSource !== 'none' && $base64MainImage === null) {
                      $errorMsg = ($mainImageSource === 'url') ?
                                  "Failed to fetch or process main product image from URL. Please check the URL or try uploading a file." :
                                  "Failed to process main product image file.";
                      echo json_encode(['success' => false, 'message' => $errorMsg]);
                      exit;
                  }

                 // অল্টারনেটিভ প্রোডাক্ট ডেটা এবং ইমেজ প্রসেসিং
                  $productData = [
                      'ProductName' => $productName,
                      'ProductImage' => $base64MainImage,
                      'ProductBrand' => $productBrand,
                      'ProductCategory' => $productCategory,
                      'SubCategory' => $subCategory,
                      'Barcode' => $barcode,
                      'MoreInfo' => $moreInfo,
                  ];

                 for($i = 1; $i <= 3; $i++) {
                     $altName = filter_var(trim($_POST["AlternativeName{$i}"] ?? ''), FILTER_SANITIZE_STRING);
                     $altBrand = filter_var(trim($_POST["AlternativeBrand{$i}"] ?? ''), FILTER_SANITIZE_STRING);
                     $altBarcode = filter_var(trim($_POST["AlternativeBarcode{$i}"] ?? ''), FILTER_SANITIZE_STRING);
                     $altImageData = $_POST["AlternativeImage{$i}"] ?? null;
                     $altImageSource = $_POST["AlternativeImageSource{$i}"] ?? 'none';

                     $base64AltImage = null;
                     if (!empty($altImageData) && $altImageSource !== 'none') {
                         $base64AltImage = getImageBase64($altImageData, $altImageSource);
                         if ($base64AltImage === null) {
                              $errorMsg = ($altImageSource === 'url') ?
                                           "Failed to fetch or process image for Alternative {$i} from URL. Please check the URL or try uploading a file." :
                                           "Failed to process image file for Alternative {$i}.";
                              echo json_encode(['success' => false, 'message' => $errorMsg]);
                              exit;
                         }
                     }

                     $productData["AlternativeName{$i}"] = $altName;
                     $productData["AlternativeBrand{$i}"] = $altBrand;
                     $productData["AlternativeBarcode{$i}"] = $altBarcode;
                     $productData["AlternativeImage{$i}"] = $base64AltImage;
                 }


                 // Products টেবিলে ইনসার্ট করুন
                 $columns = implode(', ', array_keys($productData));
                 $placeholders = implode(', ', array_fill(0, count($productData), '?'));
                 $insertSql = "INSERT INTO Products ($columns) VALUES ($placeholders)";
                 $stmt = $conn->prepare($insertSql);
                 $stmt->execute(array_values($productData));

                 echo json_encode(['success' => true, 'message' => 'Product added successfully to the Products table.']);

             } catch (PDOException $e) {
                  error_log("Database error during direct product add: " . $e->getMessage());
                 echo json_encode(['success' => false, 'message' => 'Database error adding product.']);
             } catch (Exception $e) {
                 error_log("General error during direct product add: " . $e->getMessage());
                 echo json_encode(['success' => false, 'message' => 'An unexpected error occurred while adding the product.']);
             }

            break;

        case 'delete_request': // তালিকা থেকে ডিলিট বা মডাল থেকে রিজেক্ট
             // requireAuth() ইতিমধ্যেই কল করা হয়েছে
             $id = filter_var($_POST['id'] ?? null, FILTER_SANITIZE_NUMBER_INT);

             if (!$id || !is_numeric($id)) {
                echo json_encode(['success' => false, 'message' => 'Invalid request ID provided for deletion.']);
                exit;
             }

             try {
                 $stmt = $conn->prepare("DELETE FROM Products_Req WHERE id = :id");
                 $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                 $stmt->execute();

                 if ($stmt->rowCount() > 0) {
                      echo json_encode(['success' => true, 'message' => 'Request deleted successfully.']);
                 } else {
                      echo json_encode(['success' => false, 'message' => 'Request not found or already processed.']);
                 }

             } catch (PDOException $e) {
                 error_log("Error deleting request (ID: {$id}): " . $e->getMessage());
                 echo json_encode(['success' => false, 'message' => 'Database error during deletion.']);
             }
            break;

        case 'check_duplicate': // লাইভ ডুপ্লিকেট চেকিং
             // requireAuth() ইতিমধ্যেই কল করা হয়েছে
             $productName = filter_var(trim($_POST['ProductName'] ?? ''), FILTER_SANITIZE_STRING);
             $barcode = filter_var(trim($_POST['Barcode'] ?? ''), FILTER_SANITIZE_STRING);

             // অন্তত একটি ফিল্ড থাকতে হবে চেক করার জন্য
             if (empty($productName) && empty($barcode)) {
                  echo json_encode(['success' => false, 'message' => 'No data provided for duplicate check.']);
                  exit;
             }

             try {
                 $duplicates = checkExistingProduct($conn, $productName, $barcode);
                 echo json_encode([
                     'success' => true,
                     'isDuplicateName' => $duplicates['isDuplicateName'],
                     'isDuplicateBarcode' => $duplicates['isDuplicateBarcode']
                 ]);

             } catch (PDOException $e) {
                 error_log("Database error during duplicate check: " . $e->getMessage());
                 echo json_encode(['success' => false, 'message' => 'Database error during duplicate check.']);
             }
            break;


        default:
            // অজানা action
             echo json_encode(['success' => false, 'message' => 'Invalid action specified.']);
            break;
    }

    // সংযোগ বন্ধ করুন (PHP স্ক্রিপ্ট শেষ হলে স্বয়ংক্রিয়ভাবে বন্ধ হয়, তবে এক্সপ্লিসিটলি করা যেতে পারে)
    $conn = null;

    ?>
