<?php
session_start();

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

require_once("definitions.php");

// Create connection
$conn = new mysqli(PACKAGE_LOG_DB_SERVER, PACKAGE_LOG_DB_USER, PACKAGE_LOG_DB_PASS, PACKAGE_LOG_DB_NAME);

// Check connection
if ($conn->connect_error) {
    echo json_encode([
        "data" => [],
        "error" => "Connection failed: " . $conn->connect_error
    ]);
    exit;
}

$storeKey = isset($_SESSION['storekey']) ? intval($_SESSION['storekey']) : 0;

if ($storeKey === 0) {
    echo json_encode([
        "data" => [],
        "error" => "Invalid store key"
    ]);
    exit;
}

// Prepare SQL
$sql = "SELECT mp.plan_key,
               ma.name AS attribute_name,
               mp.name AS plan_name,
               mp.pkglimit_mo,
               mp.price_1mo, mp.price_12mo,
               mp.businesses
        FROM mailbox_plans mp
        LEFT JOIN mailbox_attributes ma
            ON mp.mailbox_attribute_key = ma.mailbox_attributes_key
            AND mp.store_key = ma.store_key
        WHERE mp.store_key = ?
        ORDER BY ma.name ASC, mp.name ASC";

$stmt = $conn->prepare($sql);
if ($stmt === false) {
    echo json_encode([
        "data" => [],
        "error" => "Prepare failed: " . $conn->error
    ]);
    exit;
}

$stmt->bind_param("i", $storeKey);
$stmt->execute();
$result = $stmt->get_result();

$data = [];

if ($result !== false && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // Sanitize and prepare fields
        $attributeName = htmlspecialchars($row['attribute_name'] ?? 'N/A');
        $planName = htmlspecialchars($row['plan_name']);

        // Package limit logic
        $pkgLimitRaw = $row['pkglimit_mo'];
        if (is_numeric($pkgLimitRaw) && $pkgLimitRaw > 1000) {
            $pkgLimit = 'Unlimited';
        } else {
            $pkgLimit = is_numeric($pkgLimitRaw) ? $pkgLimitRaw : '';
        }

        $oneMo = is_numeric($row['price_1mo']) ? '$' . number_format($row['price_1mo'], 2) : '';
        $twelveMo = is_numeric($row['price_12mo']) ? '$' . number_format($row['price_12mo'], 2) : '';
        $noBusinesses = $row['businesses'] ? 'Yes' : 'No';
        $planKey = intval($row['plan_key']);

        // Actions HTML with data-plan-key attribute
        $actions = "<a href='javascript:void(0);' class='text-info fs-14 lh-1 editPlanBtn' data-plan-key='{$planKey}'>
                        <i class='ri-edit-line'></i>
                    </a>
                    <a href='javascript:void(0);' class='text-danger fs-14 lh-1 deletePlanBtn' data-plan-key='{$planKey}'>
                        <i class='ri-delete-bin-5-line'></i>
                    </a>";

        $data[] = [
            $attributeName,
            $planName,
            $pkgLimit,
            $oneMo,
            $twelveMo,
            $noBusinesses,
            $actions
        ];
    }
}

$stmt->close();
$conn->close();

echo json_encode([
    "data" => $data
]);