import os
import re

filepath = r'c:\xampp\htdocs\Procurement\dashboard\index.php'
with open(filepath, 'r', encoding='utf-8') as f:
    content = f.read()

# 1. ADD PHP LOGIC
php_logic = """
// ─── DATE FILTER LOGIC ─────────────────────────────────────────────
$f_inicio = $_GET['inicio'] ?? '';
$f_fin = $_GET['fin'] ?? '';
$df = "";
$dp = [];
if ($f_inicio && $f_fin) {
    $df = " AND fecha_creacion >= :inicio AND fecha_creacion <= :fin ";
    $dp = [':inicio' => $f_inicio . ' 00:00:00', ':fin' => $f_fin . ' 23:59:59'];
} elseif ($f_inicio) {
    $df = " AND fecha_creacion >= :inicio ";
    $dp = [':inicio' => $f_inicio . ' 00:00:00'];
} elseif ($f_fin) {
    $df = " AND fecha_creacion <= :fin ";
    $dp = [':fin' => $f_fin . ' 23:59:59'];
}
"""
content = content.replace("// ═══════════════════════════════════════════════════════════════════\n// DATA QUERIES - All sections", php_logic + "\n// ═══════════════════════════════════════════════════════════════════\n// DATA QUERIES - All sections")


# 2. INJECT SQL WHERE CLAUSES AND PARAMS
# All queries end with ");
# We can replace all `);` with `, $dp);` if they are `safeQuery` calls without params
def query_replacer(match):
    full_call = match.group(0)
    # Check if we already have params
    if ', $dp' in full_call:
        return full_call
        
    # Inject the WHERE clause $df
    full_call = full_call.replace('FROM v_proceso_completo\n    WHERE ', 'FROM v_proceso_completo\n    WHERE 1=1 " . $df . " AND ')
    full_call = full_call.replace('FROM v_proceso_completo WHERE ', 'FROM v_proceso_completo WHERE 1=1 " . $df . " AND ')
    
    # In one query we have: "FROM ( SELECT TIMESTAMPDIFF... FROM v_proceso_completo WHERE ...) t"
    # The replacement above covers it because it replaces "FROM v_proceso_completo\n    WHERE "
    
    # Replace ending to add $dp
    full_call = re.sub(r'("\s*\);)$', '", $dp);', full_call)
    return full_call

# Find all safeQuery and safeQuerySingle calls
content = re.sub(r'safeQuery(Single)?\(\$pdo, ".*?"\s*\);', query_replacer, content, flags=re.DOTALL)


# 3. ADD UI FILTERS TO HTML
ui_html = """
    <div class="page-header" style="display:flex; justify-content:space-between; align-items:center;">
        <div>
            <h2 id="section-title">Resumen Ejecutivo</h2>
            <p id="section-desc">Visión general de KPIs principales de compras y abastecimiento</p>
        </div>
        <div class="date-filters" style="background:rgba(20,20,50,0.8); padding:12px 20px; border-radius:12px; border:1px solid rgba(100,100,255,0.15); display:flex; gap:12px; align-items:center;">
            <form method="GET" action="" style="display:flex; gap:12px; align-items:center; margin:0;">
                <div style="display:flex; flex-direction:column;">
                    <label style="font-size:0.7rem; color:#94a3b8; margin-bottom:4px;">Desde:</label>
                    <input type="date" name="inicio" value="<?= htmlspecialchars($f_inicio) ?>" style="background:rgba(0,0,0,0.3); border:1px solid rgba(100,100,255,0.2); color:#e2e8f0; padding:6px 10px; border-radius:6px; font-family:'Inter'; font-size:0.8rem; outline:none;">
                </div>
                <div style="display:flex; flex-direction:column;">
                    <label style="font-size:0.7rem; color:#94a3b8; margin-bottom:4px;">Hasta:</label>
                    <input type="date" name="fin" value="<?= htmlspecialchars($f_fin) ?>" style="background:rgba(0,0,0,0.3); border:1px solid rgba(100,100,255,0.2); color:#e2e8f0; padding:6px 10px; border-radius:6px; font-family:'Inter'; font-size:0.8rem; outline:none;">
                </div>
                <button type="submit" style="margin-top:16px; background:#6366f1; border:none; color:white; padding:7px 14px; border-radius:6px; font-weight:600; cursor:pointer; font-size:0.8rem; transition:all 0.2s;">Filtrar</button>
                <?php if ($f_inicio || $f_fin): ?>
                <a href="index.php" style="margin-top:16px; color:#ef4444; text-decoration:none; font-size:0.8rem; font-weight:500; margin-left:8px;">Limpiar</a>
                <?php endif; ?>
            </form>
        </div>
    </div>
"""

# Replace the first page-header (for Resumen Ejecutivo)
content = content.replace("""    <div class="page-header">
        <h2>Resumen Ejecutivo</h2>
        <p>Visión general de KPIs principales de compras y abastecimiento</p>
    </div>""", ui_html)

# To make the title dynamic based on the section, we can update it via JS, but for now it's okay since the sidebar changes it via JS already. Wait, let's check how sections change.
# Section change is done via `showSection()` in JS. We need to move the date filter outside of `<div id="sec-resumen">` so it applies to all sections, OR we just let the JS update the title.
# Let's move the `date-filters` to be outside the section divs, at the very top of `.main`.
ui_global = """
    <!-- GLOBAL HEADER & DATE FILTERS -->
    <div class="global-header" style="display:flex; justify-content:space-between; align-items:center; margin-bottom:32px;">
        <div>
            <h2 id="global-section-title" style="font-size: 1.75rem; font-weight: 800; letter-spacing: -0.03em; background: linear-gradient(135deg, #fff, #94a3b8); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">Resumen Ejecutivo</h2>
            <p id="global-section-desc" style="color: #64748b; font-size: 0.88rem; margin-top: 4px;">Visión general de KPIs principales de compras y abastecimiento</p>
        </div>
        <div class="date-filters" style="background:rgba(20,20,50,0.8); backdrop-filter:blur(20px); padding:12px 20px; border-radius:12px; border:1px solid rgba(100,100,255,0.15); display:flex; gap:12px; align-items:center;">
            <form method="GET" action="" style="display:flex; gap:12px; align-items:center; margin:0;">
                <div style="display:flex; flex-direction:column;">
                    <label style="font-size:0.7rem; color:#94a3b8; margin-bottom:4px; font-weight:600;">Fecha Desde:</label>
                    <input type="date" name="inicio" value="<?= htmlspecialchars($f_inicio) ?>" style="background:rgba(0,0,0,0.4); border:1px solid rgba(100,100,255,0.2); color:#e2e8f0; padding:8px 12px; border-radius:8px; font-family:'Inter'; font-size:0.85rem; outline:none;">
                </div>
                <div style="display:flex; flex-direction:column;">
                    <label style="font-size:0.7rem; color:#94a3b8; margin-bottom:4px; font-weight:600;">Fecha Hasta:</label>
                    <input type="date" name="fin" value="<?= htmlspecialchars($f_fin) ?>" style="background:rgba(0,0,0,0.4); border:1px solid rgba(100,100,255,0.2); color:#e2e8f0; padding:8px 12px; border-radius:8px; font-family:'Inter'; font-size:0.85rem; outline:none;">
                </div>
                <button type="submit" style="margin-top:16px; background:linear-gradient(135deg, #6366f1, #4f46e5); border:none; color:white; padding:9px 18px; border-radius:8px; font-weight:700; cursor:pointer; font-size:0.85rem; box-shadow:0 4px 12px rgba(99,102,241,0.3); transition:all 0.2s;">Filtrar</button>
                <?php if ($f_inicio || $f_fin): ?>
                <a href="index.php" style="margin-top:16px; color:#ef4444; background:rgba(239,68,68,0.1); padding:9px 14px; border-radius:8px; text-decoration:none; font-size:0.85rem; font-weight:600; margin-left:4px; border:1px solid rgba(239,68,68,0.2);">X Limpiar</a>
                <?php endif; ?>
            </form>
        </div>
    </div>
"""

# Insert ui_global right after `<div class="main">`
content = content.replace('<div class="main">', '<div class="main">\n' + ui_global)

# Remove all individual `.page-header` divs from sections to avoid duplicate titles
content = re.sub(r'<div class="page-header">.*?</div>', '', content, flags=re.DOTALL)

# Add JS logic to update global title
js_logic = """
    // Update global title
    const titles = {
        'resumen': ['Resumen Ejecutivo', 'Visión general de KPIs principales de compras y abastecimiento'],
        'tiempos': ['Análisis de Tiempos', 'Desglose del ciclo de vida de compras por etapa'],
        'backlog': ['Backlog Operativo', 'Análisis de órdenes pendientes y antigüedad'],
        'proveedores': ['Scorecard Proveedores', 'Rendimiento y tiempos de entrega por proveedor'],
        'alertas': ['Alertas y Anomalías', 'Detección estadística de órdenes que exceden los tiempos normales'],
        'tendencias': ['Tendencias', 'Evolución temporal del rendimiento de compras'],
        'compradores': ['Compradores', 'Análisis de carga de trabajo y rendimiento por comprador']
    };
    if (titles[sectionId]) {
        document.getElementById('global-section-title').textContent = titles[sectionId][0];
        document.getElementById('global-section-desc').textContent = titles[sectionId][1];
    }
    
    // Add date filter params to sidebar links
    const urlParams = new URLSearchParams(window.location.search);
    const inicio = urlParams.get('inicio');
    const fin = urlParams.get('fin');
"""
content = content.replace("document.getElementById('sec-' + sectionId).classList.add('active');", "document.getElementById('sec-' + sectionId).classList.add('active');\n" + js_logic)


# Fix the JavaScript onclicks so they don't lose the query parameters
# The JS doesn't reload the page, it just hides/shows divs. So we don't need to append GET params to links. The form handles the GET params.

with open(filepath, 'w', encoding='utf-8') as f:
    f.write(content)

print("Dates applied!")
