#!/bin/bash

# =============================================
# PUPPET MUSEUM WEBSITE INSTALLATION SCRIPT
# NO ROOT NEEDED - Uses provided credentials
# =============================================

# Configuration
DB_NAME="tanahtin_museumdb"
DB_USER="tanahtin_museumdbuser"
DB_PASS="tjokrodisastro"
WEBROOT="/home/tanahtin/museum.pondoktingal.com"
ADMIN_USER="admin"
ADMIN_PASS="admin"
DOMAIN="museum.pondoktingal.com"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Puppet Museum Installation Script${NC}"
echo -e "${GREEN}========================================${NC}"

# =============================================
# STEP 1: Create directories
# =============================================
echo -e "\n${YELLOW}[1/7] Creating directories...${NC}"

mkdir -p $WEBROOT/admin/{countries,districts,characters,collections,images,users,css,js}
mkdir -p $WEBROOT/includes
mkdir -p $WEBROOT/assets/{css,js}
mkdir -p $WEBROOT/uploads
mkdir -p $WEBROOT/cache

echo -e "${GREEN}✓ Directories created${NC}"

# =============================================
# STEP 2: Set permissions
# =============================================
echo -e "\n${YELLOW}[2/7] Setting permissions...${NC}"

chmod 755 $WEBROOT
chmod 755 $WEBROOT/admin
chmod 777 $WEBROOT/uploads
chmod 777 $WEBROOT/cache

echo -e "${GREEN}✓ Permissions set${NC}"

# =============================================
# STEP 3: Create .htaccess files
# =============================================
echo -e "\n${YELLOW}[3/7] Creating .htaccess files...${NC}"

# Root .htaccess
cat > $WEBROOT/.htaccess << 'HTACCESS'
RewriteEngine On

# Prevent access to sensitive directories
RedirectMatch 403 ^/includes/.*$
RedirectMatch 403 ^/cache/.*\.php$

# Security headers
<IfModule mod_headers.c>
    Header set X-Content-Type-Options "nosniff"
    Header set X-Frame-Options "DENY"
</IfModule>
HTACCESS

# Uploads .htaccess (prevent PHP execution)
cat > $WEBROOT/uploads/.htaccess << 'HTACCESS'
# Allow only image files
<FilesMatch "\.(jpg|jpeg|png|gif|webp)$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

# Deny PHP files
<FilesMatch "\.(php|php3|php4|php5|phtml|inc)$">
    Order Deny,Allow
    Deny from all
</FilesMatch>
HTACCESS

# Cache .htaccess
cat > $WEBROOT/cache/.htaccess << 'HTACCESS'
<FilesMatch "\.(jpg|jpeg|png|gif|webp)$">
    Order Allow,Deny
    Allow from all
</FilesMatch>
HTACCESS

echo -e "${GREEN}✓ .htaccess files created${NC}"

# =============================================
# STEP 4: Create database tables
# =============================================
echo -e "\n${YELLOW}[4/7] Creating database tables...${NC}"

mysql -u $DB_USER -p$DB_PASS $DB_NAME << MYSQL
-- Users table
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    full_name VARCHAR(100) NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    salt VARCHAR(255) NOT NULL,
    role ENUM('admin', 'editor') NOT NULL DEFAULT 'editor',
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    last_login TIMESTAMP NULL,
    INDEX idx_username (username),
    INDEX idx_role (role),
    INDEX idx_is_active (is_active)
);

-- Countries table
CREATE TABLE IF NOT EXISTS countries (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL UNIQUE,
    INDEX idx_name (name)
);

-- Districts table
CREATE TABLE IF NOT EXISTS districts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    country_id INT NOT NULL,
    name VARCHAR(100) NOT NULL,
    FOREIGN KEY (country_id) REFERENCES countries(id) ON DELETE CASCADE,
    UNIQUE KEY unique_country_district (country_id, name),
    INDEX idx_country_id (country_id)
);

-- Characters table
CREATE TABLE IF NOT EXISTS characters (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL UNIQUE,
    type VARCHAR(50),
    description TEXT,
    INDEX idx_name (name),
    INDEX idx_type (type)
);

-- Collections table (Crates)
CREATE TABLE IF NOT EXISTS collections (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    crate_number INT NOT NULL,
    country_id INT NOT NULL,
    district_id INT NULL,
    description TEXT,
    total_puppets INT NOT NULL DEFAULT 0,
    FOREIGN KEY (country_id) REFERENCES countries(id) ON DELETE RESTRICT,
    FOREIGN KEY (district_id) REFERENCES districts(id) ON DELETE SET NULL,
    UNIQUE KEY unique_crate_number (crate_number),
    INDEX idx_crate_number (crate_number),
    INDEX idx_country_id (country_id)
);

-- Images table
CREATE TABLE IF NOT EXISTS images (
    id INT AUTO_INCREMENT PRIMARY KEY,
    collection_id INT NOT NULL,
    character_id INT NULL,
    filename VARCHAR(255) NOT NULL,
    file_path VARCHAR(500) NOT NULL,
    is_primary BOOLEAN NOT NULL DEFAULT FALSE,
    sort_order INT NOT NULL DEFAULT 0,
    uploaded_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE,
    FOREIGN KEY (character_id) REFERENCES characters(id) ON DELETE SET NULL,
    INDEX idx_collection_id (collection_id),
    INDEX idx_character_id (character_id),
    INDEX idx_is_primary (is_primary)
);
MYSQL

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Tables created${NC}"
else
    echo -e "${RED}✗ Failed to create tables${NC}"
    exit 1
fi

# =============================================
# STEP 5: Create admin user with salted password
# =============================================
echo -e "\n${YELLOW}[5/7] Creating admin user...${NC}"

# Generate salt and hash using PHP
ADMIN_HASH=$(php -r "
\$salt = bin2hex(random_bytes(32));
\$password_hash = hash('sha256', \$salt . '$ADMIN_PASS');
echo \$salt . ':' . \$password_hash;
")

ADMIN_SALT=$(echo $ADMIN_HASH | cut -d':' -f1)
ADMIN_PASS_HASH=$(echo $ADMIN_HASH | cut -d':' -f2)

mysql -u $DB_USER -p$DB_PASS $DB_NAME << MYSQL
INSERT INTO users (username, full_name, password_hash, salt, role, is_active)
VALUES ('$ADMIN_USER', 'Administrator', '$ADMIN_PASS_HASH', '$ADMIN_SALT', 'admin', TRUE)
ON DUPLICATE KEY UPDATE
    full_name = 'Administrator',
    password_hash = '$ADMIN_PASS_HASH',
    salt = '$ADMIN_SALT',
    role = 'admin',
    is_active = TRUE;
MYSQL

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Admin user created (username: admin, password: admin)${NC}"
else
    echo -e "${RED}✗ Failed to create admin user${NC}"
    exit 1
fi

# =============================================
# STEP 6: Create PHP files
# =============================================
echo -e "\n${YELLOW}[6/7] Creating PHP files...${NC}"

# ========== includes/config.php ==========
cat > $WEBROOT/includes/config.php << 'CONFIG'
<?php
// Database configuration
define('DB_HOST', 'localhost');
define('DB_NAME', 'tanahtin_museumdb');
define('DB_USER', 'tanahtin_museumdbuser');
define('DB_PASS', 'tjokrodisastro');

// Paths
define('BASE_URL', 'https://museum.pondoktingal.com');
define('BASE_PATH', dirname(__DIR__));
define('UPLOAD_DIR', BASE_PATH . '/uploads/');
define('UPLOAD_URL', BASE_URL . '/uploads/');
define('CACHE_DIR', BASE_PATH . '/cache/');
define('CACHE_URL', BASE_URL . '/cache/');

// Watermark configuration
define('WATERMARK_TEXT', 'Property Of Pondok Tingal');
define('WATERMARK_OPACITY', 30); // 0-100
define('WATERMARK_SPACING_X', 200);
define('WATERMARK_SPACING_Y', 80);

// Thumbnail configuration
define('THUMB_WIDTH', 200);
define('THUMB_HEIGHT', 200);
define('MAX_IMAGE_WIDTH', 1200);

// Start session
session_start();
?>
CONFIG

# ========== includes/functions.php ==========
cat > $WEBROOT/includes/functions.php << 'FUNCTIONS'
<?php
require_once __DIR__ . '/config.php';

function getDB() {
    static $db = null;
    if ($db === null) {
        $db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($db->connect_error) {
            die("Connection failed: " . $db->connect_error);
        }
        $db->set_charset("utf8mb4");
    }
    return $db;
}

function hashPassword($password, $salt) {
    return hash('sha256', $salt . $password);
}

function generateSalt() {
    return bin2hex(random_bytes(32));
}

function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function hasRole($role) {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === $role;
}

function requireAdmin() {
    if (!isLoggedIn() || !hasRole('admin')) {
        header('Location: ../login.php?error=unauthorized');
        exit();
    }
}

function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: ../login.php');
        exit();
    }
}

function escape($value) {
    $db = getDB();
    return $db->real_escape_string($value);
}

function getCountries() {
    $db = getDB();
    $result = $db->query("SELECT * FROM countries ORDER BY name");
    return $result->fetch_all(MYSQLI_ASSOC);
}

function getDistricts($country_id = null) {
    $db = getDB();
    $sql = "SELECT d.*, c.name as country_name FROM districts d 
            JOIN countries c ON d.country_id = c.id";
    if ($country_id) {
        $sql .= " WHERE d.country_id = " . intval($country_id);
    }
    $sql .= " ORDER BY c.name, d.name";
    $result = $db->query($sql);
    return $result->fetch_all(MYSQLI_ASSOC);
}

function getCharacters() {
    $db = getDB();
    $result = $db->query("SELECT * FROM characters ORDER BY name");
    return $result->fetch_all(MYSQLI_ASSOC);
}

function getCollections() {
    $db = getDB();
    $result = $db->query("SELECT c.*, co.name as country_name, d.name as district_name 
                          FROM collections c
                          LEFT JOIN countries co ON c.country_id = co.id
                          LEFT JOIN districts d ON c.district_id = d.id
                          ORDER BY c.crate_number");
    return $result->fetch_all(MYSQLI_ASSOC);
}
?>
FUNCTIONS

# ========== includes/watermark.php ==========
cat > $WEBROOT/includes/watermark.php << 'WATERMARK'
<?php
/**
 * Add diagonal repeating text watermark to image
 * FAST method using built-in GD font
 */

function addWatermark($sourcePath, $outputPath = null, $opacity = WATERMARK_OPACITY) {
    if (!file_exists($sourcePath)) {
        return false;
    }
    
    $info = getimagesize($sourcePath);
    if (!$info) return false;
    
    $width = $info[0];
    $height = $info[1];
    $type = $info[2];
    
    // Load source image
    switch ($type) {
        case IMAGETYPE_JPEG:
            $image = imagecreatefromjpeg($sourcePath);
            break;
        case IMAGETYPE_PNG:
            $image = imagecreatefrompng($sourcePath);
            break;
        case IMAGETYPE_GIF:
            $image = imagecreatefromgif($sourcePath);
            break;
        default:
            return false;
    }
    
    if (!$image) return false;
    
    // Create watermark layer
    $watermarkLayer = imagecreatetruecolor($width, $height);
    imagealphablending($watermarkLayer, false);
    imagesavealpha($watermarkLayer, true);
    $transparent = imagecolorallocatealpha($watermarkLayer, 0, 0, 0, 127);
    imagefill($watermarkLayer, 0, 0, $transparent);
    
    // Calculate alpha (0 = opaque, 127 = transparent)
    $alpha = 127 - floor(127 * $opacity / 100);
    $textColor = imagecolorallocatealpha($watermarkLayer, 255, 255, 255, $alpha);
    
    // Built-in font (font 5 is largest built-in)
    $charWidth = imagefontwidth(5);
    $charHeight = imagefontheight(5);
    $textLength = strlen(WATERMARK_TEXT);
    $textBlockWidth = $textLength * $charWidth;
    
    // Spacing
    $spacingX = $textBlockWidth + WATERMARK_SPACING_X;
    $spacingY = $charHeight * 8;
    
    // Draw diagonal repeating pattern
    for ($x = -$width; $x <= $width * 1.2; $x += $spacingX) {
        for ($y = -$height; $y <= $height * 1.2; $y += $spacingY) {
            // Diagonal offset
            $offset = ($x + $y) / 2;
            $tx = $x + ($offset % 60) - 30;
            $ty = $y;
            
            imagestring($watermarkLayer, 5, $tx, $ty, WATERMARK_TEXT, $textColor);
        }
    }
    
    // Merge watermark onto image
    imagecopy($image, $watermarkLayer, 0, 0, 0, 0, $width, $height);
    
    // Save output
    if (!$outputPath) {
        $outputPath = $sourcePath;
    }
    
    $result = imagejpeg($image, $outputPath, 90);
    
    imagedestroy($image);
    imagedestroy($watermarkLayer);
    
    return $result;
}
?>
WATERMARK

# ========== includes/thumbnail.php ==========
cat > $WEBROOT/includes/thumbnail.php << 'THUMBNAIL'
<?php
/**
 * Create thumbnail from image (with watermark)
 */

require_once __DIR__ . '/watermark.php';

function createThumbnail($sourcePath, $thumbPath, $width = THUMB_WIDTH, $height = THUMB_HEIGHT) {
    if (!file_exists($sourcePath)) {
        return false;
    }
    
    $info = getimagesize($sourcePath);
    if (!$info) return false;
    
    $origWidth = $info[0];
    $origHeight = $info[1];
    $type = $info[2];
    
    // Load source image
    switch ($type) {
        case IMAGETYPE_JPEG:
            $source = imagecreatefromjpeg($sourcePath);
            break;
        case IMAGETYPE_PNG:
            $source = imagecreatefrompng($sourcePath);
            break;
        case IMAGETYPE_GIF:
            $source = imagecreatefromgif($sourcePath);
            break;
        default:
            return false;
    }
    
    // Calculate crop dimensions (center crop for square)
    $cropX = 0;
    $cropY = 0;
    $cropW = $origWidth;
    $cropH = $origHeight;
    
    if ($origWidth > $origHeight) {
        $cropW = $origHeight;
        $cropX = ($origWidth - $origHeight) / 2;
    } elseif ($origHeight > $origWidth) {
        $cropH = $origWidth;
        $cropY = ($origHeight - $origWidth) / 2;
    }
    
    // Create thumbnail
    $thumb = imagecreatetruecolor($width, $height);
    imagecopyresampled($thumb, $source, 0, 0, $cropX, $cropY, $width, $height, $cropW, $cropH);
    
    // Add watermark to thumbnail
    $tempPath = sys_get_temp_dir() . '/thumb_temp_' . uniqid() . '.jpg';
    imagejpeg($thumb, $tempPath, 85);
    addWatermark($tempPath, $thumbPath, 20); // Lighter opacity for thumbnails
    
    imagedestroy($source);
    imagedestroy($thumb);
    
    if (file_exists($tempPath)) {
        unlink($tempPath);
    }
    
    return file_exists($thumbPath);
}
?>
THUMBNAIL

# ========== image.php (public watermark handler) ==========
cat > $WEBROOT/image.php << 'IMAGEHANDLER'
<?php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/thumbnail.php';
require_once __DIR__ . '/includes/watermark.php';

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$size = isset($_GET['size']) ? $_GET['size'] : 'large';

if (!$id) {
    header('HTTP/1.0 404 Not Found');
    die('Image not found');
}

// Get image info from database
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$stmt = $db->prepare("SELECT file_path, filename FROM images WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$image = $result->fetch_assoc();

if (!$image) {
    header('HTTP/1.0 404 Not Found');
    die('Image not found');
}

$originalPath = UPLOAD_DIR . $image['file_path'];
if (!file_exists($originalPath)) {
    header('HTTP/1.0 404 Not Found');
    die('Image file missing');
}

// Determine cache path
$cacheKey = md5($originalPath . '_' . $size);
$cachePath = CACHE_DIR . $cacheKey . '.jpg';

// Serve from cache if exists
if (file_exists($cachePath) && filemtime($cachePath) > filemtime($originalPath)) {
    header('Content-Type: image/jpeg');
    header('Cache-Control: public, max-age=86400');
    readfile($cachePath);
    exit;
}

// Generate watermarked image
if ($size === 'thumb') {
    createThumbnail($originalPath, $cachePath);
} else {
    // Copy original and add watermark
    copy($originalPath, $cachePath);
    addWatermark($cachePath, $cachePath);
}

// Serve the image
header('Content-Type: image/jpeg');
header('Cache-Control: public, max-age=86400');
readfile($cachePath);
?>
IMAGEHANDLER

# ========== admin/login.php ==========
cat > $WEBROOT/admin/login.php << 'LOGIN'
<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';

// Redirect if already logged in
if (isLoggedIn()) {
    header('Location: index.php');
    exit();
}

$error = isset($_GET['error']) ? $_GET['error'] : '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin Login - Puppet Museum</title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
    <div class="login-container">
        <h1>🎭 Puppet Museum Admin</h1>
        <?php if ($error === 'invalid'): ?>
            <div class="error">Invalid username or password</div>
        <?php elseif ($error === 'inactive'): ?>
            <div class="error">Account is disabled. Contact administrator.</div>
        <?php elseif ($error === 'unauthorized'): ?>
            <div class="error">Unauthorized access</div>
        <?php endif; ?>
        
        <form method="POST" action="authenticate.php">
            <div class="form-group">
                <label>Username</label>
                <input type="text" name="username" required autofocus>
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" required>
            </div>
            <button type="submit">Login</button>
        </form>
    </div>
</body>
</html>
LOGIN

# ========== admin/authenticate.php ==========
cat > $WEBROOT/admin/authenticate.php << 'AUTH'
<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';

session_start();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: login.php');
    exit();
}

$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';

$db = getDB();
$stmt = $db->prepare("SELECT id, username, full_name, password_hash, salt, role, is_active FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if ($user && $user['is_active'] == 1) {
    $hash = hashPassword($password, $user['salt']);
    
    if ($hash === $user['password_hash']) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['username'];
        $_SESSION['user_fullname'] = $user['full_name'];
        $_SESSION['user_role'] = $user['role'];
        
        // Update last login
        $update = $db->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
        $update->bind_param("i", $user['id']);
        $update->execute();
        
        header('Location: index.php');
        exit();
    }
}

// Invalid login
header('Location: login.php?error=invalid');
?>
AUTH

# ========== admin/logout.php ==========
cat > $WEBROOT/admin/logout.php << 'LOGOUT'
<?php
session_start();
session_destroy();
header('Location: login.php');
exit();
?>
LOGOUT

# ========== admin/session_check.php ==========
cat > $WEBROOT/admin/session_check.php << 'SESSIONCHECK'
<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';

if (!isLoggedIn()) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['user_role'];
$user_fullname = $_SESSION['user_fullname'];
?>
SESSIONCHECK

# ========== admin/index.php (Dashboard) ==========
cat > $WEBROOT/admin/index.php << 'DASHBOARD'
<?php
require_once 'session_check.php';
require_once '../includes/functions.php';

$db = getDB();

// Get counts
$countryCount = $db->query("SELECT COUNT(*) as c FROM countries")->fetch_assoc()['c'];
$collectionCount = $db->query("SELECT COUNT(*) as c FROM collections")->fetch_assoc()['c'];
$characterCount = $db->query("SELECT COUNT(*) as c FROM characters")->fetch_assoc()['c'];
$imageCount = $db->query("SELECT COUNT(*) as c FROM images")->fetch_assoc()['c'];

include 'header.php';
?>
<div class="dashboard">
    <h1>Welcome, <?php echo htmlspecialchars($user_fullname); ?></h1>
    <p>Role: <?php echo $user_role; ?></p>
    
    <div class="stats">
        <div class="stat-card">
            <h3><?php echo $countryCount; ?></h3>
            <p>Countries</p>
        </div>
        <div class="stat-card">
            <h3><?php echo $collectionCount; ?></h3>
            <p>Collections (Crates)</p>
        </div>
        <div class="stat-card">
            <h3><?php echo $characterCount; ?></h3>
            <p>Characters</p>
        </div>
        <div class="stat-card">
            <h3><?php echo $imageCount; ?></h3>
            <p>Images</p>
        </div>
    </div>
    
    <div class="menu-grid">
        <a href="countries/" class="menu-item">🌍 Countries</a>
        <a href="districts/" class="menu-item">🗺️ Districts</a>
        <a href="characters/" class="menu-item">🎭 Characters</a>
        <a href="collections/" class="menu-item">📦 Collections</a>
        <a href="images/" class="menu-item">🖼️ Images</a>
        <?php if (hasRole('admin')): ?>
        <a href="users/" class="menu-item">👥 Users</a>
        <?php endif; ?>
    </div>
</div>
<?php include 'footer.php'; ?>
DASHBOARD

# ========== admin/header.php ==========
cat > $WEBROOT/admin/header.php << 'HEADER'
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Puppet Museum Admin</title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
    <div class="admin-header">
        <strong>🎭 Puppet Museum Admin</strong>
        <div>
            <?php echo htmlspecialchars($user_fullname); ?> (<?php echo $user_role; ?>) | 
            <a href="logout.php">Logout</a>
        </div>
    </div>
    <div class="container">
HEADER

# ========== admin/footer.php ==========
cat > $WEBROOT/admin/footer.php << 'FOOTER'
    </div>
</body>
</html>
FOOTER

echo -e "${GREEN}✓ PHP files created${NC}"

# =============================================
# STEP 7: Create admin CSS
# =============================================
echo -e "\n${YELLOW}[7/7] Creating CSS files...${NC}"

cat > $WEBROOT/admin/css/admin.css << 'CSS'
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    background: #f5f5f5;
}

.login-container {
    max-width: 400px;
    margin: 100px auto;
    background: white;
    padding: 30px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.login-container h1 {
    margin-bottom: 20px;
    text-align: center;
}

.form-group {
    margin-bottom: 15px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
}

.form-group input, .form-group select, .form-group textarea {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

button, .button {
    background: #4CAF50;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
}

button:hover, .button:hover {
    background: #45a049;
}

.error {
    background: #ffebee;
    color: #c62828;
    padding: 10px;
    border-radius: 4px;
    margin-bottom: 15px;
}

.success {
    background: #e8f5e9;
    color: #2e7d32;
    padding: 10px;
    border-radius: 4px;
    margin-bottom: 15px;
}

.admin-header {
    background: #333;
    color: white;
    padding: 15px 20px;
    display: flex;
    justify-content: space-between;
}

.admin-header a {
    color: white;
    text-decoration: none;
}

.container {
    padding: 20px;
}

table {
    width: 100%;
    background: white;
    border-collapse: collapse;
}

table th, table td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #ddd;
}

table th {
    background: #f5f5f5;
}

.stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin: 30px 0;
}

.stat-card {
    background: white;
    padding: 20px;
    text-align: center;
    border-radius: 8px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.stat-card h3 {
    font-size: 36px;
    color: #4CAF50;
}

.menu-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
    margin-top: 30px;
}

.menu-item {
    background: white;
    padding: 20px;
    text-align: center;
    text-decoration: none;
    color: #333;
    border-radius: 8px;
    transition: transform 0.2s;
}

.menu-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}
CSS

echo -e "${GREEN}✓ CSS files created${NC}"

# =============================================
# COMPLETION
# =============================================
echo -e "\n${GREEN}========================================${NC}"
echo -e "${GREEN}INSTALLATION COMPLETE!${NC}"
echo -e "${GREEN}========================================${NC}"
echo -e "\n📁 Webroot: $WEBROOT"
echo -e "🔗 URL: https://$DOMAIN"
echo -e "🔐 Admin login: https://$DOMAIN/admin/"
echo -e "\n👤 Default admin credentials:"
echo -e "   Username: ${GREEN}admin${NC}"
echo -e "   Password: ${GREEN}admin${NC}"
echo -e "\n⚠️  IMPORTANT: Change your password after first login!"
echo -e "\n📸 Next steps:"
echo -e "   1. Login to admin panel"
echo -e "   2. Add countries and districts"
echo -e "   3. Add characters"
echo -e "   4. Create collections (crates)"
echo -e "   5. Upload puppet images"
echo -e "\n✅ Installation successful!"