#!/bin/bash
# ============================================================
# SPOTFIX Field Operations — Production Installer v2.1
# ============================================================
set -euo pipefail

RED='\033[0;31m'; GREEN='\033[0;32m'; GOLD='\033[0;33m'; CYAN='\033[0;36m'; NC='\033[0m'

echo -e "${GOLD}"
echo "╔══════════════════════════════════════════════╗"
echo "║  SPOTFIX Field Operations — Installer v2.1   ║"
echo "╚══════════════════════════════════════════════╝"
echo -e "${NC}"

INSTALL_DIR="/var/www/spotfix-field"
DB_NAME="spotfix_field"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

read -p "Domain (e.g. field.spotfix.co.ke): " DOMAIN
DOMAIN="${DOMAIN:-field.spotfix.co.ke}"

read -p "MySQL root password: " -s MYSQL_ROOT_PASS; echo
DB_PASS="$(openssl rand -base64 24 | tr -d '/+=' | head -c 24)"
echo -e "${GREEN}Generated DB password (saved to .env)${NC}"

# #5: Enforce strong admin password
while true; do
    read -p "Set admin password (min 12 chars, upper+lower+digit+special): " -s ADMIN_PASS; echo
    if [ ${#ADMIN_PASS} -lt 12 ]; then echo -e "${RED}Min 12 characters.${NC}"; continue; fi
    if ! echo "$ADMIN_PASS" | grep -qP '[A-Z]'; then echo -e "${RED}Need uppercase letter.${NC}"; continue; fi
    if ! echo "$ADMIN_PASS" | grep -qP '[a-z]'; then echo -e "${RED}Need lowercase letter.${NC}"; continue; fi
    if ! echo "$ADMIN_PASS" | grep -qP '[0-9]'; then echo -e "${RED}Need a digit.${NC}"; continue; fi
    if ! echo "$ADMIN_PASS" | grep -qP '[^A-Za-z0-9]'; then echo -e "${RED}Need a special character.${NC}"; continue; fi
    break
done

read -p "Admin phone number (e.g. +254712345678): " ADMIN_PHONE
ADMIN_PHONE="${ADMIN_PHONE:-+254712345678}"

read -p "Admin name: " ADMIN_NAME
ADMIN_NAME="${ADMIN_NAME:-Administrator}"

APP_KEY="$(openssl rand -hex 32)"

echo -e "\n${CYAN}[1/9] Installing packages...${NC}"
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq nginx mariadb-server php8.2-fpm php8.2-mysql php8.2-mbstring php8.2-xml php8.2-curl php8.2-gd php8.2-zip unzip curl certbot python3-certbot-nginx > /dev/null 2>&1 || \
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq nginx mariadb-server php-fpm php-mysql php-mbstring php-xml php-curl php-gd php-zip unzip curl certbot python3-certbot-nginx > /dev/null 2>&1
echo -e "${GREEN}✓ Packages installed${NC}"

echo -e "\n${CYAN}[2/9] Configuring database...${NC}"
mysql -u root -p"${MYSQL_ROOT_PASS}" <<EOSQL
CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
DROP USER IF EXISTS 'spotfix'@'localhost';
CREATE USER 'spotfix'@'localhost' IDENTIFIED BY '${DB_PASS}';
GRANT ALL PRIVILEGES ON \`${DB_NAME}\`.* TO 'spotfix'@'localhost';
FLUSH PRIVILEGES;
SET GLOBAL event_scheduler = ON;
EOSQL
echo -e "${GREEN}✓ Database created${NC}"

echo -e "\n${CYAN}[3/9] Importing schema...${NC}"
mysql -u root -p"${MYSQL_ROOT_PASS}" "${DB_NAME}" < "${SCRIPT_DIR}/database/schema.sql"
mysql -u root -p"${MYSQL_ROOT_PASS}" "${DB_NAME}" < "${SCRIPT_DIR}/database/security_migration.sql"
echo -e "${GREEN}✓ Schema imported${NC}"

echo -e "\n${CYAN}[4/9] Creating admin account...${NC}"
# #2: Use PHP with PDO for parameterized insert — no SQL interpolation
php -r '
    $dsn = "mysql:host=127.0.0.1;dbname='"${DB_NAME}"';charset=utf8mb4";
    $pdo = new PDO($dsn, "root", $argv[1], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    $hash = password_hash($argv[2], PASSWORD_BCRYPT, ["cost" => 12]);
    // #8: Delete any existing admin, insert fresh — no ID assumption
    $pdo->prepare("DELETE FROM users WHERE phone = ?")->execute([$argv[4]]);
    $stmt = $pdo->prepare("INSERT INTO users (name, email, phone, password, role_id, branch_id, status, must_change_password) VALUES (?, ?, ?, ?, 1, 1, \"active\", 0)");
    $stmt->execute([$argv[3], "admin@spotfix.co.ke", $argv[4], $hash]);
    echo "Admin created: " . $argv[4] . "\n";
' -- "${MYSQL_ROOT_PASS}" "${ADMIN_PASS}" "${ADMIN_NAME}" "${ADMIN_PHONE}"
echo -e "${GREEN}✓ Admin account created (no default credentials)${NC}"

echo -e "\n${CYAN}[5/9] Deploying files...${NC}"
mkdir -p "${INSTALL_DIR}"/{logs,backend/uploads}
cp -r "${SCRIPT_DIR}/backend" "${INSTALL_DIR}/"
cp -r "${SCRIPT_DIR}/frontend" "${INSTALL_DIR}/"

cat > "${INSTALL_DIR}/.env" <<ENVEOF
DB_HOST=127.0.0.1
DB_PORT=3306
DB_NAME=${DB_NAME}
DB_USER=spotfix
DB_PASS=${DB_PASS}
APP_URL=https://${DOMAIN}
APP_ENV=production
APP_KEY=${APP_KEY}
FORCE_HTTPS=true
CORS_ORIGINS=https://${DOMAIN}
SMS_API_URL=https://pate.myfreezone.co.ke/smsapi.php
ENVEOF

chmod 640 "${INSTALL_DIR}/.env"
echo -e "${GREEN}✓ Files deployed, .env created${NC}"

echo -e "\n${CYAN}[6/9] Setting permissions...${NC}"
chown -R www-data:www-data "${INSTALL_DIR}"
chmod -R 755 "${INSTALL_DIR}"
chmod -R 775 "${INSTALL_DIR}/backend/uploads"
chmod 750 "${INSTALL_DIR}/logs"
chown root:www-data "${INSTALL_DIR}/.env"
echo -e "${GREEN}✓ Permissions set${NC}"

echo -e "\n${CYAN}[7/9] Configuring Nginx...${NC}"
PHP_SOCK=$(find /run/php/ -name "php*-fpm.sock" 2>/dev/null | head -1)
PHP_SOCK="${PHP_SOCK:-/run/php/php8.2-fpm.sock}"

# Temp HTTP config for certbot
cat > /etc/nginx/sites-available/spotfix-field-temp <<TEMPEOF
server {
    listen 80;
    server_name ${DOMAIN};
    root /var/www/spotfix-field/frontend;
    location / { try_files \$uri \$uri/ /index.html; }
    location /api/v1/ {
        fastcgi_pass unix:${PHP_SOCK};
        fastcgi_param SCRIPT_FILENAME /var/www/spotfix-field/backend/index.php;
        include fastcgi_params;
        fastcgi_param REQUEST_URI \$request_uri;
        fastcgi_param REQUEST_METHOD \$request_method;
        fastcgi_param CONTENT_TYPE \$content_type;
        fastcgi_param CONTENT_LENGTH \$content_length;
        fastcgi_param REMOTE_ADDR \$remote_addr;
        fastcgi_param HTTP_AUTHORIZATION \$http_authorization;
        fastcgi_param HTTP_USER_AGENT \$http_user_agent;
    }
}
TEMPEOF
ln -sf /etc/nginx/sites-available/spotfix-field-temp /etc/nginx/sites-enabled/spotfix-field
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl reload nginx
echo -e "${GREEN}✓ Nginx configured${NC}"

echo -e "\n${CYAN}[8/9] Setting up SSL...${NC}"
certbot --nginx -d "${DOMAIN}" --non-interactive --agree-tos --register-unsafely-without-email 2>/dev/null && {
    cp "${SCRIPT_DIR}/nginx.conf" "/etc/nginx/sites-available/spotfix-field"
    sed -i "s|unix:/run/php/php8.2-fpm.sock|unix:${PHP_SOCK}|g" "/etc/nginx/sites-available/spotfix-field"
    sed -i "s|field.spotfix.co.ke|${DOMAIN}|g" "/etc/nginx/sites-available/spotfix-field"
    ln -sf /etc/nginx/sites-available/spotfix-field /etc/nginx/sites-enabled/spotfix-field
    rm -f /etc/nginx/sites-available/spotfix-field-temp
    nginx -t && systemctl reload nginx
    echo -e "${GREEN}✓ SSL installed${NC}"
} || {
    echo -e "${GOLD}⚠ SSL skipped (DNS not pointed?). Run: certbot --nginx -d ${DOMAIN}${NC}"
}

echo -e "\n${CYAN}[9/9] Cron jobs & backup...${NC}"
cat > /root/.my.cnf.spotfix <<MYCNF
[client]
user=spotfix
password=${DB_PASS}
MYCNF
chmod 600 /root/.my.cnf.spotfix

cat > "${INSTALL_DIR}/backup.sh" <<'BAKEOF'
#!/bin/bash
set -euo pipefail
DIR="/var/backups/spotfix-field"; mkdir -p "$DIR"
F="$DIR/spotfix_$(date +%Y%m%d_%H%M%S).sql.gz"
mysqldump --defaults-extra-file=/root/.my.cnf.spotfix spotfix_field | gzip > "$F"
gzip -t "$F" 2>/dev/null || { echo "BACKUP CORRUPT: $F" >&2; rm -f "$F"; exit 1; }
S=$(stat -c%s "$F")
[ "$S" -lt 1024 ] && { echo "BACKUP TOO SMALL: $F ($S bytes)" >&2; exit 1; }
find "$DIR" -name "*.sql.gz" -mtime +30 -delete
echo "$(date) — OK: $F ($S bytes)"
BAKEOF
chmod 700 "${INSTALL_DIR}/backup.sh"

cat > "${INSTALL_DIR}/cron-dormancy.php" <<'CRONEOF'
<?php
require_once __DIR__ . '/backend/core.php';
$threshold = (int)getSetting('dormancy_threshold_days', 30);
$cutoff = date('Y-m-d', strtotime("-{$threshold} days"));
$dormant = DB::fetchAll(
    "SELECT c.id, c.last_payment_at FROM customers c
     LEFT JOIN dormant_customers d ON d.customer_id = c.id AND d.status NOT IN ('reactivated','closed')
     WHERE c.status = 'active' AND c.last_payment_at IS NOT NULL AND c.last_payment_at < ?
       AND c.installed_at IS NOT NULL AND d.id IS NULL AND c.deleted_at IS NULL", [$cutoff]);
$n = 0;
foreach ($dormant as $c) {
    $days = (int)((time() - strtotime($c['last_payment_at'])) / 86400);
    DB::insert('dormant_customers', ['customer_id'=>$c['id'],'days_inactive'=>$days,'last_payment_date'=>date('Y-m-d',strtotime($c['last_payment_at'])),'status'=>'new']);
    DB::update('customers', ['status'=>'dormant'], 'id = ?', [$c['id']]);
    $n++;
}
echo date('Y-m-d H:i:s') . " — $n dormant detected\n";
CRONEOF

(crontab -l 2>/dev/null || true; echo "
# SPOTFIX Field Operations
0 2 * * * php ${INSTALL_DIR}/cron-dormancy.php >> ${INSTALL_DIR}/logs/dormancy.log 2>&1
0 3 * * * ${INSTALL_DIR}/backup.sh >> ${INSTALL_DIR}/logs/backup.log 2>&1
") | sort -u | crontab -
echo -e "${GREEN}✓ Cron jobs installed${NC}"

echo -e "\n${GOLD}╔══════════════════════════════════════════════╗"
echo "║          INSTALLATION COMPLETE                ║"
echo "╚══════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  ${GREEN}URL:${NC}        https://${DOMAIN}"
echo -e "  ${GREEN}Admin:${NC}      ${ADMIN_PHONE}"
echo -e "  ${GREEN}Env:${NC}        ${INSTALL_DIR}/.env"
echo -e "  ${GREEN}Backups:${NC}    /var/backups/spotfix-field/"
echo ""
echo -e "  ${CYAN}Next:${NC}"
echo "  1. Log in and create technician accounts"
echo "  2. Set monthly KPI targets"
echo "  3. Technicians: open https://${DOMAIN} → Add to Home Screen"
echo ""
