#!/bin/bash

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

# Functions for colored output
print_step() {
    echo -e "${BLUE}===> $1 ${NC}"
}

print_success() {
    echo -e "${GREEN}✓ $1 ${NC}"
}

print_error() {
    echo -e "${RED}✗ $1 ${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠ $1 ${NC}"
}

# Project directory
PROJECT="id-saude"

print_step "Starting setup for ID Saúde project: $PROJECT"

echo -e "${BLUE}Interactive setup. Press Enter for defaults where applicable.${NC}\n"

# Interactive inputs
read -p "Enter DB Host (default: localhost): " DB_HOST
DB_HOST=${DB_HOST:-localhost}

read -p "Enter DB Name: " 

read -p "Enter DB Username: " 

read -s -p "Enter DB Password: " 
echo

read -p "Enter APP_NAME (default: ID Saúde): " APP_NAME
APP_NAME=${APP_NAME:-"ID Saúde"}

echo 

# 1. Create project structure
print_step "1. Creating project folder structure..."

if [ -d "$PROJECT" ]; then
    print_warning "Directory $PROJECT already exists. Please remove it and run again."
    exit 1
fi

mkdir -p "$PROJECT"/{assets/{css,js},views,controllers,models,logs}
print_success "Folder structure created."

# 2. Create files
print_step "2. Creating PHP, HTML, CSS, JS files..."

# index.php (with HTML structure)
cat > "$PROJECT/index.php" << 'EOF'
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo APP_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <header>
        <h1><?php echo APP_NAME; ?></h1>
    </header>
    <main>
        <p>Bem-vindo ao ID Saúde!</p>
    </main>
    <script src="assets/js/main.js"></script>
</body>
</html>
EOF

# config.php
cat > "$PROJECT/config.php" << EOF
<?php
// Database configuration
define('APP_NAME', '$APP_NAME');
define('DB_HOST', '$DB_HOST');
define('DB_NAME', '$DB_NAME');
define('DB_USER', '$DB_USER');
define('DB_PASS', '$DB_PASS');

// Example DB connection
function getDBConnection() {
    try {
        return new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
    } catch(PDOException $e) {
        die("Connection failed: " . $e->getMessage());
    }
}
?>
EOF

# .htaccess
cat > "$PROJECT/.htaccess" << 'EOF'
RewriteEngine On

# Remove index.php from URLs
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

# Security: Deny access to config.php
<Files "config.php">
    Order allow,deny
    Deny from all
</Files>

# Hide logs
<Directory "logs">
    Order deny,allow
    Deny from all
</Directory>
EOF

# CSS
cat > "$PROJECT/assets/css/style.css" << 'EOF'
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 20px;
    background-color: #f4f4f4;
}

h1 {
    color: #2c5aa0;
}
EOF

# JS
cat > "$PROJECT/assets/js/main.js" << 'EOF'
document.addEventListener('DOMContentLoaded', function() {
    console.log('ID Saúde JavaScript loaded successfully!');
    // Add interactivity here
});
EOF

# Example PHP controller
cat > "$PROJECT/controllers/HomeController.php" << 'EOF'
<?php
require_once '../config.php';

class HomeController {
    public function index() {
        include '../views/home.php';
    }
}
?>
EOF

# Example view (HTML/PHP)
cat > "$PROJECT/views/home.php" << 'EOF'
<div>
    <h2>Página Inicial</h2>
    <p>Conteúdo dinâmico aqui.</p>
</div>
EOF

print_success "Core files (PHP, HTML, CSS, JS) created."

# 3. Set permissions
print_step "3. Configuring permissions (755 for dirs, 644 for files)..."

find "$PROJECT" -type d -exec chmod 755 {} \;
find "$PROJECT" -type f -exec chmod 644 {} \;
chmod 755 "$PROJECT/logs"

print_success "Permissions configured."

# 4. Database instructions
print_step "4. Database setup instructions:"
echo -e "${YELLOW}   1. Login to MySQL: mysql -h $DB_HOST -u $DB_USER -p$DB_PASS${NC}"
echo -e "${YELLOW}   2. Create database: CREATE DATABASE \"$DB_NAME\";${NC}"
echo -e "${YELLOW}   3. Use database: USE \"$DB_NAME\";${NC}"
echo -e "${YELLOW}   4. Run your SQL schema (create tables, etc.):${NC}"
echo -e "${YELLOW}      SOURCE /path/to/your/schema.sql;${NC}"
echo -e "${YELLOW}   Or via command line: mysql -h $DB_HOST -u $DB_USER -p$DB_PASS $DB_NAME < schema.sql${NC}\n"
print_success "Instructions displayed."

# 5. Validate
print_step "5. Validating setup..."

errors=0
required=(
    "$PROJECT"
    "$PROJECT/index.php"
    "$PROJECT/config.php"
    "$PROJECT/.htaccess"
    "$PROJECT/assets/css/style.css"
    "$PROJECT/assets/js/main.js"
    "$PROJECT/controllers/HomeController.php"
    "$PROJECT/views/home.php"
    "$PROJECT/logs"
)

for item in "${required[@]}"; do
    if [ ! -e "$item" ]; then
        print_error "$item not found."
        errors=1
    else
        print_success "✓ $item exists."
    fi
done

if [ $errors -eq 0 ]; then
    print_success "VALIDATION PASSED! Everything created correctly."
    echo -e "\n${GREEN}🚀 Setup complete!${NC}"
    echo -e "${YELLOW}To run locally:${NC}"
    echo -e "   cd $PROJECT"
    echo -e "   php -S localhost:8000"
    echo -e "   Open http://localhost:8000 ${NC}"
else
    print_error "Validation failed. Check errors above."
    exit 1
fi