setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Create DB if not exists $pdo->exec("CREATE DATABASE IF NOT EXISTS `" . DB_NAME . "` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"); $pdo->exec("USE `" . DB_NAME . "`"); // Create tables $pdo->exec(" CREATE TABLE IF NOT EXISTS `websites` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `url` text NOT NULL, `status` enum('normal','cancelled','maintenance') NOT NULL DEFAULT 'normal', `logo_url` text NULL, `click_count` int(11) NOT NULL DEFAULT 0, `display_order` int(11) NOT NULL DEFAULT 0, `is_mock` tinyint(1) NOT NULL DEFAULT 0, `created_at` timestamp NOT NULL DEFAULT current_timestamp(), PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; "); // Add new columns to existing table for V2 upgrade backward compatibility try { $pdo->exec("ALTER TABLE `websites` ADD COLUMN `status` ENUM('normal', 'cancelled', 'maintenance') NOT NULL DEFAULT 'normal' AFTER `url`"); } catch (PDOException $e) {} try { $pdo->exec("ALTER TABLE `websites` ADD COLUMN `logo_url` TEXT NULL AFTER `status`"); } catch (PDOException $e) {} try { $pdo->exec("ALTER TABLE `websites` ADD COLUMN `click_count` INT(11) NOT NULL DEFAULT 0 AFTER `logo_url`"); } catch (PDOException $e) {} $pdo->exec(" CREATE TABLE IF NOT EXISTS `activity_logs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `action` varchar(255) NOT NULL, `details` text NOT NULL, `ip_address` varchar(45) NOT NULL, `created_at` timestamp NOT NULL DEFAULT current_timestamp(), PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; "); // Create Settings table $pdo->exec(" CREATE TABLE IF NOT EXISTS `settings` ( `setting_key` varchar(50) NOT NULL, `setting_value` text NOT NULL, PRIMARY KEY (`setting_key`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; "); // Insert default settings $stmt = $pdo->prepare("INSERT IGNORE INTO `settings` (`setting_key`, `setting_value`) VALUES ('site_name', 'ศูนย์รวมเว็บหน่วยงาน'), ('site_subtitle', 'One Stop Web Service')"); $stmt->execute(); // Fetch settings globally $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings"); $globalSettings = []; while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $globalSettings[$row['setting_key']] = $row['setting_value']; } } catch (PDOException $e) { die("Database Connection failed. Please check config.php: " . $e->getMessage()); } function logAction($pdo, $action, $details) { $ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'; $stmt = $pdo->prepare("INSERT INTO activity_logs (action, details, ip_address) VALUES (?, ?, ?)"); $stmt->execute([$action, $details, $ip]); } function requireLogin() { if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) { header("Location: login.php"); exit; } }