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

APP="/home/cghggujarat/laravel_apps/cghg_portal"
PHP82="/opt/cpanel/ea-php82/root/usr/bin/php"
OWNER="cghggujarat:cghggujarat"
STAMP="$(date +%Y%m%d-%H%M%S)"
SAFETY="$APP/_migration_backups/restore-pre-old-layout-v11-$STAMP"

COMPANY="Parshwa Padme Solutions Private Limited"
SUPPORT_PHONE="9016465901"

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 "$APP/resources/views/website" ] || fail "website views missing"

cd "$APP"

say "1/8 SAFETY BACKUP CURRENT WEBSITE"
mkdir -p "$SAFETY"
cp -a resources/views/website "$SAFETY/website-current"
cp -a routes/web.php "$SAFETY/web.php.current"

cat > "$SAFETY/ROLLBACK.sh" <<ROLLBACK
#!/usr/bin/env bash
set -e
APP="$APP"
SAFE="$SAFETY"
rm -rf "\$APP/resources/views/website"
cp -a "\$SAFE/website-current" "\$APP/resources/views/website"
cp -af "\$SAFE/web.php.current" "\$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 "$SAFETY/ROLLBACK.sh"

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

say "2/8 FIND BACKUP FROM BEFORE OLD-LAYOUT CONVERSION"

RESTORE_DIR="$(find "$APP/_migration_backups" -maxdepth 1 -type d -name 'website-old-exact-v9-*' -printf '%T@ %p\n' 2>/dev/null     | sort -nr | awk 'NR==1{$1=""; sub(/^ /,""); print; exit}')"

if [ -z "$RESTORE_DIR" ] || [ ! -d "$RESTORE_DIR/website-views.before" ]; then
    echo "Could not find the pre-old-layout V9 backup."
    echo "Available related backups:"
    find "$APP/_migration_backups" -maxdepth 1 -type d       \( -name 'website-old-exact-v9-*' -o -name 'website-highlight-v8-*' -o -name 'website-executive-light-v7-*' \)       -printf '%TY-%Tm-%Td %TH:%TM %p\n' 2>/dev/null | sort -r | head -30
    fail "Nothing changed. Send this output so the correct restore point can be selected."
fi

echo "RESTORE_FROM=$RESTORE_DIR"

say "3/8 RESTORE MODERN LIGHT WEBSITE FROM BEFORE OLD LAYOUT"
rm -rf resources/views/website
cp -a "$RESTORE_DIR/website-views.before" resources/views/website

say "4/8 ADD TECHNICAL SUPPORT / MAINTENANCE DETAILS"

export APP COMPANY SUPPORT_PHONE
python3 - <<'PY'
from pathlib import Path
import os, re

app = Path(os.environ["APP"])
company = os.environ["COMPANY"]
phone = os.environ["SUPPORT_PHONE"]

layout = app / "resources/views/website/layout.blade.php"
if not layout.exists():
    raise SystemExit("layout.blade.php missing after restore")

s = layout.read_text()

START = "<!-- CGHG_TECH_SUPPORT_V11_START -->"
END   = "<!-- CGHG_TECH_SUPPORT_V11_END -->"

if START in s and END in s:
    a = s.index(START)
    b = s.index(END) + len(END)
    s = s[:a] + s[b:]

support_block = (
    f'\n{START}\n'
    '<style>\n'
    '.cghg-tech-support-v11{margin-top:18px;padding:13px 15px;'
    'border:1px solid rgba(19,136,8,.16);border-left:4px solid #138808;'
    'border-radius:12px;background:linear-gradient(90deg,#fff8ef,#fff,#f3faf4);'
    'color:#556159;font-size:12px;line-height:1.55;}\n'
    '.cghg-tech-support-v11 strong{color:#243127;font-weight:800;}\n'
    '.cghg-tech-support-v11 a{color:#0b6531;font-weight:800;white-space:nowrap;}\n'
    '</style>\n'
    '<div class="cghg-tech-support-v11">\n'
    '<strong>Technical Support &amp; Maintenance:</strong> '
    + company +
    ' &nbsp;·&nbsp; '
    f'<a href="tel:+91{phone}">+91 {phone}</a>\n'
    '</div>\n'
    f'{END}\n'
)

matches = list(re.finditer(r'</footer\s*>', s, flags=re.I))
if matches:
    pos = matches[-1].start()
    s = s[:pos] + support_block + s[pos:]
else:
    m = re.search(r'</body\s*>', s, flags=re.I)
    if not m:
        raise SystemExit("Could not find footer/body insertion point")
    pos = m.start()
    s = s[:pos] + support_block + s[pos:]

layout.write_text(s)

note = (
    '\n<!-- CGHG_SUPPORT_NOTE_V11 -->\n'
    '<div class="policy-note" style="margin-top:18px">\n'
    '<strong>Technical Support &amp; Maintenance:</strong> '
    + company +
    '<br>Support Contact: '
    f'<a href="tel:+91{phone}">+91 {phone}</a>\n'
    '</div>\n'
)

candidate_names = [
    "contact.blade.php",
    "privacy.blade.php",
    "privacy-policy.blade.php",
    "terms.blade.php",
    "terms-and-conditions.blade.php",
]

patched = []
for name in candidate_names:
    p = app / "resources/views/website" / name
    if not p.exists():
        continue
    text = p.read_text()
    if "CGHG_SUPPORT_NOTE_V11" not in text:
        if "@endsection" in text:
            text = text.replace("@endsection", note + "\n@endsection", 1)
        else:
            text += note
        p.write_text(text)
    patched.append(name)

print("POLICY_CONTACT_PATCHED=" + ",".join(patched))
PY

say "5/8 REMOVE PLACEHOLDER SUPPORT NUMBERS IF PRESENT"

python3 - <<'PY'
from pathlib import Path

root = Path("/home/cghggujarat/laravel_apps/cghg_portal/resources/views/website")
replacements = {
    "+91-12345-67890": "+91 9016465901",
    "+91 12345 67890": "+91 9016465901",
}

for p in root.rglob("*.blade.php"):
    s = p.read_text()
    old = s
    for a,b in replacements.items():
        s = s.replace(a,b)
    if s != old:
        p.write_text(s)
        print("UPDATED", p.relative_to(root))
PY

say "6/8 OWNERSHIP + SYNTAX"
chown -R "$OWNER" resources/views/website
find resources/views/website -type f -exec chmod 644 {} \;
"$PHP82" -l routes/web.php

say "7/8 LARAVEL CACHE VALIDATION"
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 VERIFY"
grep -Rni "Parshwa Padme Solutions Private Limited" resources/views/website | head -20
grep -Rni "9016465901" resources/views/website | head -20

echo
echo "RESTORED_PRE_OLD_LAYOUT=OK"
echo "MODERN_LIGHT_WEBSITE=RESTORED"
echo "TECHNICAL_SUPPORT_COMPANY=$COMPANY"
echo "SUPPORT_PHONE=$SUPPORT_PHONE"
echo "OFFICER_LOGIN_AUTH=UNTOUCHED"
echo "SAFETY_BACKUP=$SAFETY"
echo "ROLLBACK=bash $SAFETY/ROLLBACK.sh"
echo
echo "PREVIEW=https://cghggujarat.in/new/portalarea-laravel-preview/website"
echo "CGHG RESTORE PRE-OLD-LAYOUT + SUPPORT V11 COMPLETE"
