#!/usr/bin/env bash
set -Eeuo pipefail

APP="/home/cghggujarat/laravel_apps/cghg_portal"
PREVIEW="/home/cghggujarat/public_html/new/portalarea-laravel-preview"
OLD="/home/cghggujarat/public_html/website"
PHP82="/opt/cpanel/ea-php82/root/usr/bin/php"
OWNER="cghggujarat:cghggujarat"
STAMP="$(date +%Y%m%d-%H%M%S)"
BACKUP="$APP/_migration_backups/website-old-structure-modern-v10-$STAMP"

fail(){ echo "ERROR: $*" >&2; exit 1; }
say(){ printf '\n===== %s =====\n' "$1"; }

[ -d "$APP" ] || fail "Laravel app missing: $APP"
[ -f "$APP/artisan" ] || fail "artisan missing"
[ -d "$OLD" ] || fail "Old website folder missing: $OLD"
[ -d "$PREVIEW" ] || fail "Preview public folder missing: $PREVIEW"

cd "$APP"

say "1/8 BACKUP"
mkdir -p "$BACKUP"
[ -d resources/views/website ] && cp -a resources/views/website "$BACKUP/website-views.before"
cp -a routes/web.php "$BACKUP/web.php.before"

cat > "$BACKUP/ROLLBACK.sh" <<ROLLBACK
#!/usr/bin/env bash
set -e
APP="$APP"
BACKUP="$BACKUP"

if [ -d "\$BACKUP/website-views.before" ]; then
  rm -rf "\$APP/resources/views/website"
  cp -a "\$BACKUP/website-views.before" "\$APP/resources/views/website"
fi

cp -af "\$BACKUP/web.php.before" "\$APP/routes/web.php"

chown -R $OWNER "\$APP/resources/views/website" "\$APP/routes/web.php" 2>/dev/null || true

cd "\$APP"
runuser -u cghggujarat -- env HOME=/home/cghggujarat "$PHP82" artisan optimize:clear >/dev/null 2>&1 || true

echo "ROLLBACK COMPLETE"
ROLLBACK
chmod 750 "$BACKUP/ROLLBACK.sh"

rollback_on_error(){
  code=$?
  echo
  echo "V10 FAILED - restoring previous website..."
  bash "$BACKUP/ROLLBACK.sh" || true
  exit "$code"
}
trap rollback_on_error ERR

say "2/8 FIND OLD WEBSITE ENTRY"
OLD_INDEX=""
for f in "$OLD/index.php" "$OLD/index.html" "$OLD/index.htm"; do
  if [ -f "$f" ]; then
    OLD_INDEX="$f"
    break
  fi
done

[ -n "$OLD_INDEX" ] || fail "Old website index not found"
echo "OLD_INDEX=$OLD_INDEX"

say "3/8 COPY OLD WEBSITE ASSETS"

APP_ASSETS="$APP/public/assets/website-old"
PREVIEW_ASSETS="$PREVIEW/assets/website-old"

rm -rf "$APP_ASSETS" "$PREVIEW_ASSETS"
mkdir -p "$APP_ASSETS" "$PREVIEW_ASSETS"

if command -v rsync >/dev/null 2>&1; then
  rsync -a     --exclude='*.php'     --exclude='*.phtml'     --exclude='*.phar'     --exclude='*.htaccess'     --exclude='.env*'     --exclude='*.sql'     --exclude='*.zip'     --exclude='*.tar'     --exclude='*.gz'     "$OLD/" "$APP_ASSETS/"

  rsync -a "$APP_ASSETS/" "$PREVIEW_ASSETS/"
else
  python3 - <<'PY'
from pathlib import Path
import shutil

src = Path("/home/cghggujarat/public_html/website")
dests = [
    Path("/home/cghggujarat/laravel_apps/cghg_portal/public/assets/website-old"),
    Path("/home/cghggujarat/public_html/new/portalarea-laravel-preview/assets/website-old"),
]
blocked_suffix = {".php",".phtml",".phar",".sql",".zip",".tar",".gz"}

for p in src.rglob("*"):
    if not p.is_file():
        continue
    if p.suffix.lower() in blocked_suffix:
        continue
    if p.name == ".htaccess" or p.name.startswith(".env"):
        continue

    rel = p.relative_to(src)
    for d in dests:
        t = d / rel
        t.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(p,t)
PY
fi

chown -R "$OWNER" "$APP_ASSETS" "$PREVIEW_ASSETS" 2>/dev/null || true
find "$APP_ASSETS" "$PREVIEW_ASSETS" -type d -exec chmod 755 {} \;
find "$APP_ASSETS" "$PREVIEW_ASSETS" -type f -exec chmod 644 {} \;

echo "OLD_ASSET_COUNT=$(find "$APP_ASSETS" -type f | wc -l)"

say "4/8 RENDER OLD WEBSITE STRUCTURE"

RAW="$BACKUP/old-home-rendered.html"

if curl -LfsS --max-time 30 "https://cghggujarat.in/website/" -o "$RAW" && [ -s "$RAW" ]; then
  echo "SOURCE=LIVE_OLD_WEBSITE"
else
  echo "Live render unavailable. Using local old website source."
  case "$OLD_INDEX" in
    *.php)
      (
        cd "$OLD"
        "$PHP82" "$(basename "$OLD_INDEX")"
      ) > "$RAW" 2>"$BACKUP/local-render.stderr" || true
      ;;
    *)
      cp -af "$OLD_INDEX" "$RAW"
      ;;
  esac
fi

[ -s "$RAW" ] || fail "Unable to render old website"
echo "OLD_HTML_BYTES=$(wc -c < "$RAW")"

say "5/8 KEEP OLD STRUCTURE + INSTALL MODERN LIGHT UI"

mkdir -p resources/views/website

export RAW
python3 - <<'PY'
from pathlib import Path
import os, re

raw = Path(os.environ["RAW"])
html = raw.read_text(errors="replace")

base = '<base href="https://cghggujarat.in/website/">'

modern_css = r'''
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Anek+Gujarati:wght@400;500;600;700;800&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">

<style id="CGHG_OLD_STRUCTURE_MODERN_V10">
:root{
  --cghg-orange:#f18b2d;
  --cghg-orange-soft:#fff4e8;
  --cghg-green:#138746;
  --cghg-green-soft:#eff9f2;
  --cghg-ink:#233027;
  --cghg-muted:#68736b;
  --cghg-line:#e5ebe6;
  --cghg-white:#ffffff;
  --cghg-soft:#fafcf9;
  --cghg-shadow:0 12px 30px rgba(37,73,46,.08);
  --cghg-radius:18px;
}

html{scroll-behavior:smooth}
body{
  background:#fff !important;
  color:var(--cghg-ink) !important;
  font-family:Inter,"Anek Gujarati","Nirmala UI",sans-serif !important;
  line-height:1.6 !important;
}

:lang(gu),[lang="gu"],.gujarati,.guj{
  font-family:"Anek Gujarati",Inter,sans-serif !important;
}

body:before{
  content:"";
  display:block;
  height:6px;
  background:linear-gradient(90deg,#ff9933 0 33.33%,#fff 33.33% 66.66%,#138808 66.66%);
  position:relative;
  z-index:9999;
}

header,
.navbar,
nav,
.main-header,
.header,
.top-header{
  background:rgba(255,255,255,.98) !important;
  border-color:var(--cghg-line) !important;
  box-shadow:0 5px 20px rgba(34,67,40,.05) !important;
}

.navbar a,
nav a,
header a{
  color:#465249 !important;
  font-weight:700 !important;
}

.navbar a:hover,
nav a:hover,
header a:hover{
  color:var(--cghg-green) !important;
}

.navbar-brand img,
.logo img,
header img{
  object-fit:contain;
}

section{position:relative}
section:nth-of-type(even){background:var(--cghg-soft)}

.hero,
.banner,
.welcome,
#home,
.home-section,
.jumbotron{
  background:
    radial-gradient(circle at 8% 20%,rgba(241,139,45,.12),transparent 28%),
    radial-gradient(circle at 92% 78%,rgba(19,135,70,.10),transparent 30%),
    linear-gradient(135deg,#fff9f3,#fff 48%,#f4fbf6) !important;
  color:var(--cghg-ink) !important;
  border-bottom:1px solid var(--cghg-line) !important;
}

h1,h2,h3,h4,h5,h6{
  color:var(--cghg-ink) !important;
  font-weight:800 !important;
}

h1{letter-spacing:-.035em !important}

h2{
  position:relative;
  padding-bottom:10px;
}

h2:after{
  content:"";
  display:block;
  width:78px;
  height:4px;
  margin-top:8px;
  border-radius:999px;
  background:linear-gradient(90deg,var(--cghg-orange) 0 50%,var(--cghg-green) 50%);
}

.card,
.box,
.service-box,
.mission-box,
.feature-box,
.info-box,
.content-box{
  background:#fff !important;
  border:1px solid var(--cghg-line) !important;
  border-radius:var(--cghg-radius) !important;
  box-shadow:var(--cghg-shadow) !important;
}

.card:nth-child(odd),
.box:nth-child(odd),
.mission-box:nth-child(odd){
  background:linear-gradient(145deg,var(--cghg-orange-soft),#fff 65%) !important;
}

.card:nth-child(even),
.box:nth-child(even),
.mission-box:nth-child(even){
  background:linear-gradient(145deg,var(--cghg-green-soft),#fff 65%) !important;
}

.badge,
.number,
.counter,
.icon-box{
  border-radius:12px !important;
}

.team-member,
.leader,
.leader-card,
.member,
.profile-card{
  background:#fff !important;
  border:1px solid var(--cghg-line) !important;
  border-radius:18px !important;
  box-shadow:var(--cghg-shadow) !important;
  overflow:hidden !important;
}

.team-member img,
.leader img,
.leader-card img,
.member img,
.profile-card img{
  object-fit:cover !important;
}

.btn,
button,
input[type="submit"],
a.button{
  border-radius:11px !important;
  font-weight:800 !important;
  transition:.18s ease !important;
}

.btn:hover,
button:hover,
a.button:hover{
  transform:translateY(-2px);
}

.btn-primary,
.btn-success,
.login-btn,
a[href*="login"]{
  background:linear-gradient(135deg,var(--cghg-green),#0d6736) !important;
  border-color:transparent !important;
  color:#fff !important;
  box-shadow:0 9px 22px rgba(19,135,70,.18) !important;
}

.btn-warning,
.btn-orange,
.download-btn{
  background:linear-gradient(135deg,#ffa555,var(--cghg-orange)) !important;
  border-color:transparent !important;
  color:#2c2114 !important;
}

footer,
.footer{
  background:linear-gradient(135deg,#fff9f2,#fff 48%,#f3faf5) !important;
  color:#4e5b52 !important;
  border-top:5px solid var(--cghg-orange) !important;
}

footer a,
.footer a{
  color:var(--cghg-green) !important;
}

img{max-width:100%}

table{
  background:#fff !important;
  border-radius:12px;
  overflow:hidden;
}

table th{
  background:var(--cghg-green-soft) !important;
  color:var(--cghg-green) !important;
}

.form-control,
input,
select,
textarea{
  border-radius:10px !important;
  border-color:#dfe6e0 !important;
}

.form-control:focus,
input:focus,
select:focus,
textarea:focus{
  border-color:var(--cghg-green) !important;
  box-shadow:0 0 0 3px rgba(19,135,70,.09) !important;
}

@media (prefers-reduced-motion:no-preference){
  .card,.box,.team-member,.leader,.profile-card{
    transition:transform .2s ease,box-shadow .2s ease;
  }
  .card:hover,.box:hover,.team-member:hover,.leader:hover,.profile-card:hover{
    transform:translateY(-3px);
    box-shadow:0 18px 38px rgba(37,73,46,.11) !important;
  }
}

@media(max-width:768px){
  body{font-size:15px}
  h1{font-size:clamp(32px,10vw,46px)!important}
  h2{font-size:clamp(25px,8vw,34px)!important}
}
</style>
'''

if re.search(r'</head\s*>', html, re.I):
    html = re.sub(
        r'</head\s*>',
        base + '
' + modern_css + '
</head>',
        html,
        count=1,
        flags=re.I
    )
else:
    html = base + '
' + modern_css + '
' + html

route_by_text = {
    "Login Portal": "login",
    "Officer Login": "login",
    "About Us": "website.about",
    "Contact Us": "website.contact",
    "Manuals & Guides": "website.manuals",
    "Privacy Policy": "website.privacy",
    "Terms & Conditions": "website.terms",
    "Data Deletion Policy": "website.data-deletion",
    "Software Used": "website.software",
}

for label, route in route_by_text.items():
    pattern = re.compile(
        r'(<a[^>]*href\s*=\s*)(["'])(.*?)()([^>]*>.*?' +
        re.escape(label) + r'.*?</a>)',
        re.I | re.S
    )
    html, _ = pattern.subn(
        lambda m, route=route:
            m.group(1) + m.group(2) + "{{ route('" + route + "') }}" +
            m.group(4) + m.group(5),
        html,
        count=1
    )

html = re.sub(
    r'href=(["'])(?:\.\./)?portalarea/login/index\.php',
    'href="{{ route('login') }}"',
    html,
    flags=re.I
)

html = "<!-- CGHG_OLD_STRUCTURE_MODERN_UI_V10 -->
" + html

out = Path("/home/cghggujarat/laravel_apps/cghg_portal/resources/views/website/home.blade.php")
out.write_text(html)

print(f"HOME_BLADE_BYTES={out.stat().st_size}")
PY

say "6/8 ENSURE WEBSITE HOME ROUTE"

python3 - <<'PY'
from pathlib import Path
import re

p = Path("/home/cghggujarat/laravel_apps/cghg_portal/routes/web.php")
s = p.read_text()

replacement = "Route::view('/website', 'website.home')->name('website.home');"

patterns = [
    r"Route::view\(\s*['"]/website/?['"]\s*,\s*['"][^'"]+['"]\s*\)\s*->name\(\s*['"]website\.home['"]\s*\)\s*;",
    r"Route::get\(\s*['"]/website/?['"]\s*,\s*function\s*\([^)]*\)\s*\{.*?\}\s*\)\s*->name\(\s*['"]website\.home['"]\s*\)\s*;",
    r"Route::get\(\s*['"]/website/?['"]\s*,\s*fn\s*\([^)]*\)\s*=>.*?\)\s*->name\(\s*['"]website\.home['"]\s*\)\s*;",
]

changed = False
for pat in patterns:
    ns, count = re.subn(pat, replacement, s, count=1, flags=re.S)
    if count:
        s = ns
        changed = True
        break

if not changed:
    if "->name('website.home')" not in s and '->name("website.home")' not in s:
        s += "
// CGHG_OLD_STRUCTURE_MODERN_UI_V10
" + replacement + "
"
        changed = True

p.write_text(s)
print("HOME_ROUTE=" + ("PATCHED" if changed else "EXISTING"))
PY

say "7/8 VALIDATE + CACHE"

chown -R "$OWNER" resources/views/website routes/web.php "$APP_ASSETS" "$PREVIEW_ASSETS" 2>/dev/null || true
chmod 644 resources/views/website/home.blade.php routes/web.php

"$PHP82" -l routes/web.php

grep -q "CGHG_OLD_STRUCTURE_MODERN_UI_V10" resources/views/website/home.blade.php
grep -q "Anek+Gujarati" resources/views/website/home.blade.php
grep -q "Our Mission" resources/views/website/home.blade.php
grep -q "Privacy Policy" resources/views/website/home.blade.php

runuser -u cghggujarat -- env HOME=/home/cghggujarat "$PHP82" artisan optimize:clear
runuser -u cghggujarat -- env HOME=/home/cghggujarat "$PHP82" artisan view:cache

say "8/8 DONE"

echo "OLD_STRUCTURE=KEPT"
echo "OLD_FUNCTIONALITY=KEPT"
echo "OLD_SECTION_ORDER=KEPT"
echo "UI_DESIGN=MODERN_LIGHT_WHITE_ORANGE_GREEN"
echo "ANEK_GUJARATI=OK"
echo "LARAVEL_OFFICER_LOGIN=CONNECTED"
echo "OFFICER_AUTH_AND_DASHBOARDS=UNTOUCHED"
echo
echo "PREVIEW=https://cghggujarat.in/new/portalarea-laravel-preview/website"
echo "BACKUP=$BACKUP"
echo "ROLLBACK=bash $BACKUP/ROLLBACK.sh"
echo
echo "CGHG OLD STRUCTURE + MODERN UI V10 INSTALLED"
