#!/bin/bash
# PH2-16 Emergency Full Revert Script
# Reverts all changes made during PH2-16 revived-record test:
#   - orders_items (tracking, carrier, current_status) — 5 rows
#   - meyer_orders (processed, meyer_error) — 5 rows
#   - b2b_cartItems (trackingN, trackingUpdated, updated_at, carrier) — 5 rows
# Usage: bash FULL_REVERT.sh
set -e
cd /home/centralgoparts/public_html
echo "=== PH2-16 FULL REVERT starting ==="
PHP_INI_SCAN_DIR="/opt/cpanel/ea-php83/root/etc:/home/centralgoparts/php-cli-conf" /opt/cpanel/ea-php83/root/usr/bin/php artisan tinker --execute='
$dir = "/home/centralgoparts/public_html/backups/ph2-fix-14Apr2026/ph216-test-20260415";
$sql1 = file_get_contents("$dir/REVERT.sql");
foreach (explode("\n", $sql1) as $line) {
    $line = trim($line);
    if (!$line || str_starts_with($line, "--")) continue;
    DB::statement($line);
    echo "[mysql] " . substr($line,0,80) . "\n";
}
$sql2 = file_get_contents("$dir/REVERT_b2b_cartItems.sql");
foreach (explode("\n", $sql2) as $line) {
    $line = trim($line);
    if (!$line || str_starts_with($line, "--")) continue;
    DB::connection("goparts_goparts")->statement($line);
    echo "[b2b] " . substr($line,0,80) . "\n";
}
echo "=== REVERT COMPLETE ===\n";
// Verify
$items = DB::select("SELECT order_item_id, tracking, carrier, current_status FROM orders_items WHERE order_item_id IN (1024012, 1024029, 1024071, 1024078, 1023218) ORDER BY order_item_id");
foreach ($items as $r) echo "  item $r->order_item_id tracking=" . substr($r->tracking ?? "NULL",0,20) . " carrier=" . ($r->carrier ?? "NULL") . " status=$r->current_status\n";
$mos = DB::select("SELECT id, processed, meyer_error FROM meyer_orders WHERE id IN (16317, 16318, 16320, 16321, 16314) ORDER BY id");
foreach ($mos as $r) echo "  meyer $r->id processed=$r->processed error=\x27" . ($r->meyer_error ?? "") . "\x27\n";
'
echo "=== Verify above output matches pre-test state ==="
