<?php
error_reporting(0);
header('Content-Type: application/json');
include 'config.php';
$conn->set_charset("utf8mb4");

session_start();

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

// ---------- Admin Login API ----------
if ($action === 'login') {
    $admin_username = $_POST['admin_username'] ?? '';
    $admin_password = $_POST['admin_password'] ?? '';
    
    $stmt = $conn->prepare("SELECT id FROM admin WHERE username=? AND password=? LIMIT 1");
    $stmt->bind_param("ss", $admin_username, $admin_password);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $_SESSION['admin_logged_in'] = true;
        echo json_encode(["status" => "success", "message" => "Login Successful"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Invalid Admin Credentials!"]);
    }
    $stmt->close();
    exit;
}

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Access Denied. Please login."]);
    exit;
}

// ---------- Get All Products ----------
if ($action === 'get_products') {
    $sql = "SELECT p.*, pi.image_link as extra_images_json 
            FROM products p 
            LEFT JOIN product_images pi ON p.id = pi.product_id 
            ORDER BY p.id DESC";
    $result = $conn->query($sql);
    $products = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            // JSON string কে array তে কনভার্ট করে নিচ্ছি
            $row['extra_images'] = json_decode($row['extra_images_json'], true) ?: [];
            unset($row['extra_images_json']); 
            $products[] = $row;
        }
    }
    echo json_encode(["status" => "success", "data" => $products]);
    exit;
}

// ---------- Add New Product ----------
if ($action === 'add_product') {
    $title = $_POST['title'] ?? '';
    $amount = (float)($_POST['amount'] ?? 0);
    $discount = (float)($_POST['discount'] ?? 0);
    $stock = (int)($_POST['stock'] ?? 0);
    $sold = (int)($_POST['sold'] ?? 0);
    $description = $_POST['description'] ?? '';
    $main_image = $_POST['image_link'] ?? '';
    
    // এক্সট্রা ইমেজের Array রিসিভ করা (যা JSON হবে)
    $extra_images = $_POST['extra_images'] ?? [];
    
    if (empty($title) || empty($amount)) {
        echo json_encode(["status" => "error", "message" => "Title and Amount are required!"]);
        exit;
    }

    try {
        // ১. Insert into products table
        $stmt = $conn->prepare("INSERT INTO products (title, discount, amount, stock, description, sold, image_link) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sddisis", $title, $discount, $amount, $stock, $description, $sold, $main_image);
        
        if ($stmt->execute()) {
            $product_id = $stmt->insert_id;
            $stmt->close();

            // ২. Insert into product_images table (JSON Format)
            if (!empty($extra_images)) {
                // ফাঁকা লিঙ্কগুলো বাদ দেওয়া হচ্ছে
                $filtered_images = array_values(array_filter($extra_images)); 
                if (count($filtered_images) > 0) {
                    $json_images = json_encode($filtered_images); // JSON এ কনভার্ট
                    $stmt_img = $conn->prepare("INSERT INTO product_images (product_id, image_link) VALUES (?, ?)");
                    $stmt_img->bind_param("is", $product_id, $json_images);
                    $stmt_img->execute();
                    $stmt_img->close();
                }
            }

            echo json_encode(["status" => "success", "message" => "Product added successfully!"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to add product."]);
        }
    } catch (Exception $e) {
        echo json_encode(["status" => "error", "message" => "Database Error: " . $e->getMessage()]);
    }
    exit;
}

// ---------- Delete Product ----------
if ($action === 'delete_product') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
        // product_images ডিলিট হবে
        $conn->query("DELETE FROM product_images WHERE product_id = $id");
        // products ডিলিট হবে
        $conn->query("DELETE FROM products WHERE id = $id");
        echo json_encode(["status" => "success", "message" => "Product deleted!"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Invalid Product ID"]);
    }
    exit;
}

echo json_encode(["status" => "error", "message" => "Invalid Action Request"]);
$conn->close();
?>