<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once("definitions.php");

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

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

if ($storeKey === 0) {
    echo json_encode([
        "draw" => intval($_GET['draw'] ?? 0),
        "recordsTotal" => 0,
        "recordsFiltered" => 0,
        "data" => [],
        "error" => "Invalid store key"
    ]);
    exit;
}

// ======================================================
// DATATABLES PARAMETERS
// ======================================================
$draw = intval($_GET['draw'] ?? 0);
$start = intval($_GET['start'] ?? 0);
$length = intval($_GET['length'] ?? 10);

$orderColumnIndex = $_GET['order'][0]['column'] ?? 0;
$orderDir = strtolower($_GET['order'][0]['dir'] ?? 'asc');
$orderDir = ($orderDir === 'desc') ? 'DESC' : 'ASC';

$searchValue = trim($_GET['search']['value'] ?? '');

// ======================================================
// ORDERABLE COLUMNS (match DataTable)
// ======================================================
$columns = [
    "b.business_name",
    "b.legal_name",
    "b.tax_id",
    "b.active",
    "total_packages"
];

$orderColumn = $columns[$orderColumnIndex] ?? $columns[0];

// ======================================================
// REDIS INIT
// ======================================================
$redis = null;
try {
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
} catch (Exception $e) {
    $redis = null;
}

// ======================================================
// CACHE HELPER
// ======================================================
function generateCacheKey($storeKey, $prefix, $params = []) {
    $key = "store_{$storeKey}_{$prefix}";
    if (!empty($params)) {
        $key .= '_' . md5(json_encode($params));
    }
    return $key;
}

$cacheExpiry = 300;

// ======================================================
// BASE QUERY
// ======================================================
$sqlFrom = "

FROM businesses b

LEFT JOIN packages p
    ON b.business_key = p.business_key

";

// ======================================================
// WHERE CLAUSES
// ======================================================
$whereClauses = [
    "b.store_key = ?"
];

$params = [$storeKey];
$paramTypes = "i";

// SEARCH
if (!empty($searchValue)) {

    $whereClauses[] = "(
        b.business_name LIKE ?
        OR b.legal_name LIKE ?
        OR b.tax_id LIKE ?
    )";

    $searchTerm = '%' . $searchValue . '%';

    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;

    $paramTypes .= "sss";
}

$whereSql = "WHERE " . implode(" AND ", $whereClauses);

// ======================================================
// DB CONNECTION
// ======================================================
$conn = new mysqli(
    PACKAGE_LOG_DB_SERVER,
    PACKAGE_LOG_DB_USER,
    PACKAGE_LOG_DB_PASS,
    PACKAGE_LOG_DB_NAME
);

if ($conn->connect_error) {
    echo json_encode([
        "draw" => $draw,
        "recordsTotal" => 0,
        "recordsFiltered" => 0,
        "data" => [],
        "error" => "Database connection failed"
    ]);
    exit;
}

// ======================================================
// TOTAL RECORDS
// ======================================================
$totalCacheKey = generateCacheKey($storeKey, 'businesses_total');

if ($redis && ($cached = $redis->get($totalCacheKey)) !== false) {

    $recordsTotal = intval($cached);

} else {

    $query = "
        SELECT COUNT(*)
        FROM businesses
        WHERE store_key = ?
    ";

    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $storeKey);
    $stmt->execute();
    $stmt->bind_result($recordsTotal);
    $stmt->fetch();
    $stmt->close();

    if ($redis) {
        $redis->setex($totalCacheKey, $cacheExpiry, $recordsTotal);
    }
}

// ======================================================
// FILTERED COUNT
// ======================================================
$filteredCacheKey = generateCacheKey(
    $storeKey,
    'businesses_filtered',
    [
        'search' => $searchValue
    ]
);

if ($redis && ($cached = $redis->get($filteredCacheKey)) !== false) {

    $recordsFiltered = intval($cached);

} else {

    if (empty($searchValue)) {
        $recordsFiltered = $recordsTotal;
    } else {

        $query = "SELECT COUNT(*) $sqlFrom $whereSql";

        $stmt = $conn->prepare($query);
        $stmt->bind_param($paramTypes, ...$params);
        $stmt->execute();
        $stmt->bind_result($recordsFiltered);
        $stmt->fetch();
        $stmt->close();

        if ($redis) {
            $redis->setex($filteredCacheKey, $cacheExpiry, $recordsFiltered);
        }
    }
}

// ======================================================
// DATA QUERY
// ======================================================
$dataCacheKey = generateCacheKey(
    $storeKey,
    'businesses_data',
    [
        'search' => $searchValue,
        'start' => $start,
        'length' => $length,
        'orderColumn' => $orderColumn,
        'orderDir' => $orderDir
    ]
);

$data = [];

if ($redis && ($cached = $redis->get($dataCacheKey)) !== false) {

    $data = json_decode($cached, true);

} else {

    $query = "
        SELECT
            b.business_name,
            b.legal_name,
            b.tax_id,
            b.active,
            b.industry,
            b.company_size,
            b.business_key,
            COUNT(p.package_key) AS total_packages

        $sqlFrom
        $whereSql
        ORDER BY $orderColumn $orderDir
        LIMIT ?, ?
    ";

    $stmt = $conn->prepare($query);

    if (!$stmt) {
        echo json_encode([
            "draw" => $draw,
            "recordsTotal" => $recordsTotal,
            "recordsFiltered" => $recordsFiltered,
            "data" => [],
            "error" => "Prepare failed: " . $conn->error
        ]);
        exit;
    }

    // Bind params + limit
    $paramTypesWithLimit = $paramTypes . "ii";
    $paramsWithLimit = array_merge($params, [$start, $length]);

    $refs = [];
    foreach ($paramsWithLimit as $k => $v) {
        $refs[$k] = &$paramsWithLimit[$k];
    }

    call_user_func_array([$stmt, 'bind_param'], array_merge([$paramTypesWithLimit], $refs));

    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {

        $tags = '<div class="d-flex align-items-center flex-wrap gap-1">';

// ------------------------------------------------------
// INDUSTRY TAG (consistent styling)
// ------------------------------------------------------
if (!empty($row['industry'])) {

    $tags .= '<span class="badge bg-primary-transparent" title="Industry">'
          . htmlspecialchars($row['industry'])
          . '</span>';
    }

    // ------------------------------------------------------
    // COMPANY SIZE TAG (color varies)
    // ------------------------------------------------------
    if (!empty($row['company_size'])) {

        $size = strtolower($row['company_size']);
        $sizeClass = 'bg-light text-default'; // fallback

        switch ($size) {

            case 'micro':
            case 'micro business':
                $sizeClass = 'bg-info-transparent';
                break;

            case 'small':
            case 'small business':
                $sizeClass = 'bg-danger-transparent';
                break;

            case 'medium':
            case 'medium business':
                $sizeClass = 'bg-warning-transparent';
                break;

            case 'corporate':
            case 'large':
            case 'large enterprise':
                $sizeClass = 'bg-primary-transparent';
                break;

            case 'startup':
                $sizeClass = 'bg-success-transparent';
                break;

            case 'franchise':
                $sizeClass = 'bg-secondary-transparent';
                break;

            default:
                $sizeClass = 'bg-dark-transparent';
                break;
        }

        $tags .= '<span class="badge ' . $sizeClass . '" title="Company Size">'
            . htmlspecialchars($row['company_size'])
            . '</span>';
    }

    $tags .= '</div>';

        $actions = '
            <div class="btn-list">

                <a data-bs-toggle="offcanvas"
                href="#offcanvasExample"
                role="button"
                aria-controls="offcanvasExample"
                class="btn btn-sm btn-warning-light btn-icon view-business"
                data-key="' . intval($row['business_key']) . '">
                    <i class="ri-eye-line"></i>
                </a>

                <button class="btn btn-sm btn-info-light btn-icon edit-business"
                        data-key="' . intval($row['business_key']) . '">
                    <i class="ri-pencil-line"></i>
                </button>

                <button class="btn btn-sm btn-danger-light btn-icon contact-delete"
                        data-key="' . intval($row['business_key']) . '">
                    <i class="ri-delete-bin-line"></i>
                </button>

            </div>';

        $status = ($row['active']) ? 'Active' : 'Inactive';

        
        $data[] = [
            htmlspecialchars($row['business_name']),
            $packageBadge,
            $status,
            $tags,  
            $actions,
            intval($row['business_key'])
        ];
        

    }

    $stmt->close();

    if ($redis) {
        $redis->setex($dataCacheKey, $cacheExpiry, json_encode($data));
    }
}

// ======================================================
// CLOSE DB
// ======================================================
$conn->close();

// ======================================================
// OUTPUT
// ======================================================
echo json_encode([
    "draw" => $draw,
    "recordsTotal" => $recordsTotal,
    "recordsFiltered" => $recordsFiltered,
    "data" => $data
]);