<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit;
}

// Database Configuration
$host = 'localhost';
$db   = 'kemetrof_db';
$user = 'kemetrof_admin';
$pass = 'SUKSESabadijaya2026';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    echo json_encode(['error' => 'Database Connection Failed: ' . $e->getMessage()]);
    exit;
}

// Increase limits for large data restores
ini_set('memory_limit', '256M');
set_time_limit(300);

// Simple Router
$request_uri = $_SERVER['REQUEST_URI'];
$base_path = '/api'; // Adjust if your api is in a subfolder
$path = str_replace($base_path, '', $request_uri);
$path = explode('?', $path)[0]; // Remove query strings
$path = rtrim($path, '/');

// Helper to convert snake_case to camelCase
function toCamelCase($data) {
    if (!$data) return $data;
    $result = [];
    foreach ($data as $key => $value) {
        $camelKey = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));
        $result[$camelKey] = $value;
    }
    return $result;
}

// Helper to convert camelCase to snake_case
function toSnakeCase($data) {
    $result = [];
    foreach ($data as $key => $value) {
        $snakeKey = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $key));
        $result[$snakeKey] = $value;
    }
    return $result;
}

// API Routes
switch ($path) {
    case '/login':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $stmt = $pdo->prepare("SELECT * FROM admins WHERE username = ? AND password = ?");
            $stmt->execute([$input['username'], $input['password']]);
            $user = $stmt->fetch();
            
            if ($user) {
                $token = bin2hex(random_bytes(16)) . time();
                $pdo->prepare("UPDATE admins SET last_login = NOW() WHERE id = ?")->execute([$user['id']]);
                echo json_encode(['success' => true, 'token' => $token, 'user' => ['username' => $user['username']]]);
            } else {
                http_response_code(401);
                echo json_encode(['error' => 'Username atau password salah']);
            }
        }
        break;

    case '/settings':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            $stmt = $pdo->query("SELECT * FROM settings WHERE id = 1");
            $row = $stmt->fetch();
            echo json_encode(toCamelCase($row));
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $data = toSnakeCase($input);
            unset($data['updated_at']);
            unset($data['id']);
            
            $cols = [];
            foreach ($data as $key => $val) {
                $cols[] = "$key = :$key";
            }
            $sql = "UPDATE settings SET " . implode(', ', $cols) . " WHERE id = 1";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($data);
            echo json_encode(['success' => true]);
        }
        break;

    case '/slots':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            $stmt = $pdo->query("SELECT * FROM slots");
            $rows = $stmt->fetchAll();
            echo json_encode(array_map('toCamelCase', $rows));
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $slots = json_decode(file_get_contents('php://input'), true);
            foreach ($slots as $slot) {
                $data = toSnakeCase($slot);
                $keys = array_keys($data);
                $placeholders = array_map(function($k) { return ":$k"; }, $keys);
                $updates = array_map(function($k) { return "$k = VALUES($k)"; }, $keys);
                
                $sql = "INSERT INTO slots (" . implode(',', $keys) . ") VALUES (" . implode(',', $placeholders) . ") 
                        ON DUPLICATE KEY UPDATE " . implode(',', $updates);
                $pdo->prepare($sql)->execute($data);
            }
            echo json_encode(['success' => true]);
        }
        break;

    case '/tenants':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            $stmt = $pdo->query("SELECT * FROM tenants ORDER BY submitted_at DESC");
            $rows = $stmt->fetchAll();
            echo json_encode(array_map('toCamelCase', $rows));
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $data = toSnakeCase($input);
            $keys = array_keys($data);
            $placeholders = array_map(function($k) { return ":$k"; }, $keys);
            $updates = array_map(function($k) { return "$k = VALUES($k)"; }, $keys);
            
            $sql = "INSERT INTO tenants (" . implode(',', $keys) . ") VALUES (" . implode(',', $placeholders) . ")
                    ON DUPLICATE KEY UPDATE " . implode(', ', $updates);
            $pdo->prepare($sql)->execute($data);
            echo json_encode(['success' => true, 'id' => $input['id'] ?? null]);
        }
        break;

    case '/tiers':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            $stmt = $pdo->query("SELECT * FROM partnership_tiers ORDER BY price DESC");
            $rows = $stmt->fetchAll();
            echo json_encode(array_map('toCamelCase', $rows));
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $tiers = json_decode(file_get_contents('php://input'), true);
            foreach ($tiers as $tier) {
                $data = toSnakeCase($tier);
                $keys = array_keys($data);
                $placeholders = array_map(function($k) { return ":$k"; }, $keys);
                $updates = array_map(function($k) { return "$k = VALUES($k)"; }, $keys);
                
                $sql = "INSERT INTO partnership_tiers (" . implode(',', $keys) . ") VALUES (" . implode(',', $placeholders) . ") 
                        ON DUPLICATE KEY UPDATE " . implode(',', $updates);
                $pdo->prepare($sql)->execute($data);
            }
            echo json_encode(['success' => true]);
        }
        break;

    case '/experiences':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            $stmt = $pdo->query("SELECT * FROM experiences ORDER BY created_at DESC");
            $rows = $stmt->fetchAll();
            echo json_encode(array_map('toCamelCase', $rows));
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $exps = json_decode(file_get_contents('php://input'), true);
            foreach ($exps as $exp) {
                $data = toSnakeCase($exp);
                $keys = array_keys($data);
                $placeholders = array_map(function($k) { return ":$k"; }, $keys);
                $updates = array_map(function($k) { return "$k = VALUES($k)"; }, $keys);
                
                $sql = "INSERT INTO experiences (" . implode(',', $keys) . ") VALUES (" . implode(',', $placeholders) . ") 
                        ON DUPLICATE KEY UPDATE " . implode(',', $updates);
                $pdo->prepare($sql)->execute($data);
            }
            echo json_encode(['success' => true]);
        }
        break;

    case '/partners':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            $stmt = $pdo->query("SELECT * FROM partners ORDER BY added_at DESC");
            $rows = $stmt->fetchAll();
            echo json_encode(array_map('toCamelCase', $rows));
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $data = toSnakeCase($input);
            $keys = array_keys($data);
            $placeholders = array_map(function($k) { return ":$k"; }, $keys);
            $updates = array_map(function($k) { return "$k = VALUES($k)"; }, $keys);

            $sql = "INSERT INTO partners (" . implode(',', $keys) . ") VALUES (" . implode(',', $placeholders) . ") 
                    ON DUPLICATE KEY UPDATE " . implode(',', $updates);
            $pdo->prepare($sql)->execute($data);
            echo json_encode(['success' => true]);
        }
        break;

    default:
        http_response_code(404);
        echo json_encode(['error' => 'Endpoint Not Found', 'path' => $path]);
        break;
}
