<?php
// config.php
// Sesuaikan dengan environment lo

define('DB_HOST', 'localhost');
define('DB_NAME', 'medp2337_pos_artaboga');
define('DB_USER', 'medp2337');
define('DB_PASS', '#wp*6G238*KPy9UQ');

// Base URL API (untuk image path dll)
define('BASE_URL', 'https://mediawana.com/apps/backend');

// Upload directory (relative ke base)
define('UPLOAD_DIR', 'uploads/products/');
define('UPLOAD_MAX_SIZE', 2 * 1024 * 1024); // 2MB

function getDB(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $pdo = new PDO(
            'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
            DB_USER,
            DB_PASS,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
        );
    }
    return $pdo;
}

// Simple auth - token based
// Di production pakai JWT atau session yang lebih proper
function checkAuth(): ?array {
    $authHeader = '';

    if (function_exists('getallheaders')) {
        foreach (getallheaders() as $k => $v) {
            if (strcasecmp($k, 'Authorization') === 0) {
                $authHeader = $v;
                break;
            }
        }
    }
    if (empty($authHeader) && isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $authHeader = $_SERVER['HTTP_AUTHORIZATION'];
    }
    if (empty($authHeader) && isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
        $authHeader = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
    }
    if (empty($authHeader)) {
        return null;
    }
    // Format: Bearer {email}
    $token = trim(str_replace('Bearer ', '', $authHeader));
    if (empty($token)) {
        return null;
    }
    $db = getDB();
    $stmt = $db->prepare('SELECT * FROM users WHERE email = ?');
    $stmt->execute([$token]);
    return $stmt->fetch() ?: null;
}

function jsonResponse($data, int $code = 200): void {
    http_response_code($code);
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

function requireAuth(): array {
    $user = checkAuth();
    if (!$user) {
        jsonResponse(['status' => 'error', 'message' => 'Unauthorized'], 401);
    }
    return $user;
}

function requireAdmin(): array {
    $user = requireAuth();
    if ($user['role'] !== 'admin') {
        jsonResponse(['status' => 'error', 'message' => 'Admin only'], 403);
    }
    return $user;
}
