<?php
// index.php - Fix NULL Values in Demander and DemanderCode_str
// Using form-based approach instead of AJAX

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Database connection
$servername = "localhost";
$username   = "root";
$password   = "";
$dbname     = "paymentpack";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$conn->set_charset("utf8mb4");

// ---- Handle messages ----
$message = '';
$message_type = '';
if (isset($_GET['msg']) && isset($_GET['msgtype'])) {
    $message = urldecode($_GET['msg']);
    $message_type = $_GET['msgtype'];
}

// ---- Handle POST: Update NULL values with selected del_point ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_records') {
    $selected_facility = isset($_POST['facility']) ? trim($_POST['facility']) : '';
    $del_point_selected = isset($_POST['del_point']) ? trim($_POST['del_point']) : '';
    
    if (empty($selected_facility)) {
        header("Location: index.php?msg=" . urlencode("No facility selected.") . "&msgtype=warning");
        exit;
    }
    
    if (empty($del_point_selected)) {
        header("Location: index.php?msg=" . urlencode("Please select a delivery point to update with.") . "&msgtype=warning");
        exit;
    }
    
    // Get the dem_name for the selected del_point
    $del_sql = "SELECT dem_name FROM del_point WHERE del_point = ?";
    $del_stmt = $conn->prepare($del_sql);
    $del_stmt->bind_param("s", $del_point_selected);
    $del_stmt->execute();
    $del_result = $del_stmt->get_result();
    $del_row = $del_result->fetch_assoc();
    $del_stmt->close();
    
    if (!$del_row) {
        header("Location: index.php?msg=" . urlencode("Invalid delivery point selected.") . "&msgtype=error");
        exit;
    }
    
    $dem_name = $del_row['dem_name'];
    
    // Update all NULL records for the facility
    $conn->begin_transaction();
    try {
        $update_sql = "UPDATE receipts 
                      SET Demander = ?, DemanderCode_str = ? 
                      WHERE facility = ? 
                      AND (Demander IS NULL OR Demander = '' OR DemanderCode_str IS NULL OR DemanderCode_str = '')";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("sss", $dem_name, $del_point_selected, $selected_facility);
        $update_stmt->execute();
        $updated_count = $update_stmt->affected_rows;
        $update_stmt->close();
        
        $conn->commit();
        
        $msg = "Successfully updated " . $updated_count . " record(s) for facility: " . $selected_facility;
        $msg .= " with Demander = '" . $dem_name . "' and DemanderCode_str = '" . $del_point_selected . "'";
        $type = 'success';
        
        header("Location: index.php?msg=" . urlencode($msg) . "&msgtype=" . $type . "&updated=" . $updated_count . "&facility=" . urlencode($selected_facility));
        exit;
        
    } catch (Exception $e) {
        $conn->rollback();
        header("Location: index.php?msg=" . urlencode("Error: " . $e->getMessage()) . "&msgtype=error");
        exit;
    }
}

// ---- Get facilities with NULL Demander or DemanderCode_str ----
$null_facilities = [];
$facility_counts = [];

$sql = "SELECT facility, COUNT(*) as count 
        FROM receipts 
        WHERE (Demander IS NULL OR Demander = '' OR DemanderCode_str IS NULL OR DemanderCode_str = '')
        AND facility IS NOT NULL AND facility != ''
        GROUP BY facility 
        ORDER BY facility";
$result = $conn->query($sql);
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $null_facilities[] = $row['facility'];
        $facility_counts[$row['facility']] = $row['count'];
    }
}

// ---- Get selected facility from URL ----
$selected_facility = isset($_GET['facility']) ? trim($_GET['facility']) : '';
$selected_facility_display = '';

// ---- If a facility is selected, get its records ----
$records = [];
$record_count = 0;
$del_point_list = [];
$selected_del_point = isset($_GET['del_point']) ? trim($_GET['del_point']) : '';

if (!empty($selected_facility)) {
    // Get all delivery points for the dropdown
    $dp_sql = "SELECT del_point, dem_name FROM del_point ORDER BY dem_name";
    $dp_result = $conn->query($dp_sql);
    if ($dp_result) {
        while ($row = $dp_result->fetch_assoc()) {
            $del_point_list[] = $row;
        }
    }
    
    // Get records with NULL values for this facility
    $record_sql = "SELECT id, InvoiceNo_str, del_point, Demander, DemanderCode_str, facility, 
                   upload_date, OrderNo_str, packDescription_Str, QtyReceived_int
                   FROM receipts 
                   WHERE facility = ? 
                   AND (Demander IS NULL OR Demander = '' OR DemanderCode_str IS NULL OR DemanderCode_str = '')
                   ORDER BY id DESC";
    $record_stmt = $conn->prepare($record_sql);
    $record_stmt->bind_param("s", $selected_facility);
    $record_stmt->execute();
    $record_result = $record_stmt->get_result();
    $records = $record_result->fetch_all(MYSQLI_ASSOC);
    $record_count = count($records);
    $record_stmt->close();
    
    // Get facility display name from first record or use selected
    if ($record_count > 0) {
        $selected_facility_display = $records[0]['facility'];
    } else {
        $selected_facility_display = $selected_facility;
    }
}

// ---- Get total records with NULL values ----
$total_null_sql = "SELECT COUNT(*) as total 
                   FROM receipts 
                   WHERE (Demander IS NULL OR Demander = '' OR DemanderCode_str IS NULL OR DemanderCode_str = '')";
$total_result = $conn->query($total_null_sql);
$total_null_records = 0;
if ($total_result) {
    $total_null_records = $total_result->fetch_assoc()['total'];
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fix NULL Values | KZN Health</title>
    <link href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f0f4fb;
            padding: 30px 20px;
            min-height: 100vh;
            display: flex;
            justify-content: center;
        }
        .container {
            max-width: 1400px;
            width: 100%;
            background: #fff;
            border-radius: 32px;
            box-shadow: 0 20px 60px rgba(0,20,40,0.15);
            padding: 32px 28px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 12px;
            margin-bottom: 8px;
        }
        h1 {
            font-size: 28px;
            font-weight: 700;
            color: #0b1b2f;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .sub {
            color: #5e6f88;
            font-size: 14px;
            margin-bottom: 24px;
        }
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 24px;
            border-radius: 12px;
            font-weight: 600;
            font-size: 14px;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            font-family: inherit;
            text-decoration: none;
        }
        .btn-primary {
            background: #1a4f8a;
            color: #fff;
        }
        .btn-primary:hover {
            background: #0f3d6b;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(26, 79, 138, 0.3);
        }
        .btn-success {
            background: #1a8a4a;
            color: #fff;
        }
        .btn-success:hover {
            background: #12703b;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(26, 138, 74, 0.3);
        }
        .btn-success:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        .btn-secondary {
            background: #eef3fa;
            color: #1a2d44;
        }
        .btn-secondary:hover {
            background: #e2ecf9;
        }
        .btn-outline {
            background: transparent;
            color: #1a4f8a;
            border: 1.5px solid #d0d9e6;
        }
        .btn-outline:hover {
            background: #f0f6fe;
            border-color: #1a4f8a;
        }
        .btn-danger {
            background: #c0392b;
            color: #fff;
        }
        .btn-danger:hover {
            background: #a93226;
        }
        .btn-warning {
            background: #f39c12;
            color: #fff;
        }
        .btn-warning:hover {
            background: #d68910;
        }
        .message {
            padding: 14px 18px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 500;
            margin: 16px 0 20px 0;
        }
        .message.success {
            background: #e6f5ed;
            color: #0f6e3a;
            border: 1px solid #b8e0cc;
        }
        .message.error {
            background: #fde9e9;
            color: #a32d2d;
            border: 1px solid #f5cdcd;
        }
        .message.warning {
            background: #fef7e0;
            color: #8a6d1b;
            border: 1px solid #f5e3b8;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }
        .stat-card {
            background: #f8faff;
            border-radius: 16px;
            padding: 20px;
            border: 1px solid #e9eef4;
        }
        .stat-card .label {
            font-size: 13px;
            color: #5e6f88;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.03em;
        }
        .stat-card .value {
            font-size: 32px;
            font-weight: 700;
            color: #0b1b2f;
            margin-top: 4px;
        }
        .stat-card .value.danger { color: #c0392b; }
        .stat-card .value.success { color: #1a8a4a; }
        .stat-card .value.warning { color: #f39c12; }
        .stat-card .value.info { color: #17a2b8; }
        .info-box {
            background: #f8faff;
            border: 1px solid #e9eef4;
            border-radius: 16px;
            padding: 20px 24px;
            margin-bottom: 24px;
        }
        .info-box h3 {
            font-size: 16px;
            color: #0b1b2f;
            margin-bottom: 8px;
        }
        .info-box p {
            color: #5e6f88;
            font-size: 14px;
            line-height: 1.6;
        }
        .info-box ul {
            margin: 8px 0 0 20px;
            color: #1a2d44;
            font-size: 14px;
            line-height: 1.8;
        }
        .facility-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 12px;
            margin: 16px 0 20px 0;
        }
        .facility-item {
            background: #fafcff;
            border: 2px solid #e9eef4;
            border-radius: 12px;
            padding: 14px 18px;
            display: flex;
            align-items: center;
            gap: 12px;
            transition: all 0.2s ease;
            cursor: pointer;
            text-decoration: none;
            color: inherit;
        }
        .facility-item:hover {
            border-color: #1a4f8a;
            background: #e6edf8;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(26, 79, 138, 0.1);
        }
        .facility-item .facility-info {
            flex: 1;
        }
        .facility-item .facility-name {
            font-weight: 600;
            color: #0b1b2f;
            font-size: 14px;
        }
        .facility-item .facility-badge {
            font-size: 12px;
            font-weight: 600;
            padding: 2px 10px;
            border-radius: 20px;
            background: #fde9e9;
            color: #c0392b;
        }
        .facility-item .facility-arrow {
            color: #1a4f8a;
            font-size: 20px;
        }
        .badge {
            display: inline-block;
            padding: 2px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            background: #e6edf8;
            color: #1a4f8a;
        }
        .badge-success {
            background: #e6f5ed;
            color: #0f6e3a;
        }
        .badge-danger {
            background: #fde9e9;
            color: #c0392b;
        }
        .back-link {
            display: inline-block;
            color: #1a4f8a;
            text-decoration: none;
            font-weight: 600;
            font-size: 14px;
            margin-top: 12px;
        }
        .back-link:hover {
            text-decoration: underline;
        }
        .selection-area {
            background: #f8faff;
            border: 2px solid #e9eef4;
            border-radius: 16px;
            padding: 24px;
            margin: 20px 0;
        }
        .selection-area .label {
            font-weight: 600;
            color: #0b1b2f;
            font-size: 14px;
            display: block;
            margin-bottom: 8px;
        }
        .selection-area select {
            width: 100%;
            max-width: 500px;
            padding: 12px 16px;
            border: 2px solid #d0d9e6;
            border-radius: 10px;
            font-size: 14px;
            background: #fff;
            transition: border-color 0.2s;
        }
        .selection-area select:focus {
            border-color: #1a4f8a;
            outline: none;
            box-shadow: 0 0 0 4px rgba(26, 79, 138, 0.1);
        }
        .records-section {
            margin: 20px 0;
        }
        .records-section .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 12px;
            margin-bottom: 16px;
            padding: 12px 0;
            border-bottom: 2px solid #e9eef4;
        }
        .records-section .table-header h3 {
            font-size: 18px;
            color: #0b1b2f;
        }
        .records-section .table-header .badge-count {
            background: #1a4f8a;
            color: #fff;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 600;
        }
        .dataTables_wrapper {
            padding: 0;
        }
        .dataTables_wrapper .dataTables_filter input {
            border: 1.5px solid #d0d9e6;
            border-radius: 8px;
            padding: 6px 12px;
            margin-left: 8px;
        }
        .dataTables_wrapper .dataTables_length select {
            border: 1.5px solid #d0d9e6;
            border-radius: 8px;
            padding: 4px 8px;
        }
        .dataTables_wrapper .dataTables_info {
            color: #5e6f88;
            font-size: 14px;
        }
        .dataTables_wrapper .dataTables_paginate .paginate_button {
            padding: 4px 12px;
            border-radius: 6px;
            border: 1px solid #d0d9e6;
            margin: 0 2px;
        }
        .dataTables_wrapper .dataTables_paginate .paginate_button.current {
            background: #1a4f8a;
            color: #fff !important;
            border-color: #1a4f8a;
        }
        table.dataTable {
            border-radius: 12px;
            overflow: hidden;
            border: 1px solid #e9eef4;
        }
        table.dataTable thead th {
            background: #eef3fa;
            color: #1a2d44;
            font-weight: 600;
            padding: 12px 14px;
            border-bottom: 2px solid #d6e0eb;
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.03em;
        }
        table.dataTable tbody td {
            padding: 10px 14px;
            border-bottom: 1px solid #eef3f8;
            color: #1f334a;
            vertical-align: middle;
            font-size: 14px;
        }
        table.dataTable tbody tr:hover td {
            background: #f8fbff;
        }
        .status-badge {
            display: inline-block;
            padding: 2px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        .status-badge.null {
            background: #fde9e9;
            color: #c0392b;
        }
        .status-badge.filled {
            background: #e6f5ed;
            color: #0f6e3a;
        }
        .update-area {
            background: #e6f5ed;
            border: 2px solid #b8e0cc;
            border-radius: 16px;
            padding: 24px;
            margin: 20px 0;
        }
        .update-area .update-label {
            font-weight: 600;
            color: #0b1b2f;
            font-size: 15px;
            margin-bottom: 12px;
        }
        .update-area .update-info {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            align-items: center;
        }
        .update-area .update-info .info-item {
            background: #fff;
            padding: 10px 16px;
            border-radius: 8px;
            border: 1px solid #d0e6d8;
        }
        .update-area .update-info .info-item strong {
            color: #0b1b2f;
        }
        .update-area .update-info .info-item .value {
            color: #1a8a4a;
            font-weight: 600;
        }
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #5e6f88;
        }
        .empty-state .icon {
            font-size: 64px;
            margin-bottom: 16px;
        }
        .empty-state h3 {
            color: #0b1b2f;
            margin-bottom: 8px;
        }
        .empty-state p {
            font-size: 15px;
            line-height: 1.6;
        }
        .steps-container {
            margin: 24px 0;
            padding: 20px;
            background: #f8faff;
            border-radius: 16px;
            border: 1px solid #e9eef4;
        }
        .steps-container h3 {
            font-size: 16px;
            color: #0b1b2f;
            margin-bottom: 16px;
        }
        .step {
            display: flex;
            align-items: flex-start;
            gap: 16px;
            margin-bottom: 12px;
            padding: 12px 16px;
            border-radius: 10px;
            background: #fff;
            border: 1px solid #e9eef4;
            transition: all 0.3s ease;
        }
        .step.active {
            border-color: #1a4f8a;
            background: #e6edf8;
        }
        .step.completed {
            border-color: #1a8a4a;
            background: #e6f5ed;
        }
        .step .step-number {
            flex-shrink: 0;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: #eef3fa;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 14px;
            color: #5e6f88;
        }
        .step.active .step-number {
            background: #1a4f8a;
            color: #fff;
        }
        .step.completed .step-number {
            background: #1a8a4a;
            color: #fff;
        }
        .step .step-content {
            flex: 1;
        }
        .step .step-content .step-title {
            font-weight: 600;
            color: #0b1b2f;
            font-size: 14px;
        }
        .step .step-content .step-desc {
            color: #5e6f88;
            font-size: 13px;
            margin-top: 2px;
        }
        .step .step-status {
            font-size: 20px;
            flex-shrink: 0;
        }
        @media (max-width: 600px) {
            .container { padding: 20px 12px; }
            .facility-grid { grid-template-columns: 1fr; }
            .stats-grid { grid-template-columns: 1fr; }
            .header { flex-direction: column; align-items: flex-start; }
            .update-area .update-info { flex-direction: column; align-items: stretch; }
            table.dataTable { font-size: 12px; }
            table.dataTable thead th, table.dataTable tbody td { padding: 6px 8px; }
        }
    </style>
</head>
<body>
<div class="container">
    <!-- Header -->
    <div class="header">
        <div>
            <h1>🔧 Fix NULL Values</h1>
            <p class="sub">Populate missing <strong>Demander</strong> and <strong>DemanderCode_str</strong> fields using delivery point data.</p>
        </div>
        <div style="display:flex; gap:10px; flex-wrap:wrap;">
            <a href="index.php" class="btn btn-secondary">🏠 Dashboard</a>
            <a href="delete.php" class="btn btn-outline">📋 Manage Records</a>
        </div>
    </div>

    <!-- Message -->
    <?php if ($message): ?>
        <div class="message <?php echo $message_type; ?>">
            <?php echo htmlspecialchars($message); ?>
            <?php if (isset($_GET['updated']) && $_GET['updated'] > 0): ?>
                <br><small>✅ <?php echo number_format($_GET['updated']); ?> records were successfully updated.</small>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <!-- Stats -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="label">Total Records with NULL</div>
            <div class="value danger"><?php echo number_format($total_null_records); ?></div>
        </div>
        <div class="stat-card">
            <div class="label">Facilities Affected</div>
            <div class="value warning"><?php echo number_format(count($null_facilities)); ?></div>
        </div>
        <div class="stat-card">
            <div class="label">Selected Facility Records</div>
            <div class="value info" id="recordCountDisplay"><?php echo number_format($record_count); ?></div>
        </div>
    </div>

    <!-- Steps -->
    <div class="steps-container">
        <h3>📋 Process Steps</h3>
        <div class="step <?php echo !empty($selected_facility) ? 'completed' : 'active'; ?>" id="step1">
            <div class="step-number">1</div>
            <div class="step-content">
                <div class="step-title">Select a Facility</div>
                <div class="step-desc">Choose a facility from the list below that has NULL values</div>
            </div>
            <div class="step-status"><?php echo !empty($selected_facility) ? '✅' : '⏳'; ?></div>
        </div>
        <div class="step <?php echo !empty($selected_facility) && $record_count > 0 ? 'active' : ''; ?>" id="step2">
            <div class="step-number">2</div>
            <div class="step-content">
                <div class="step-title">Review Records</div>
                <div class="step-desc">View all records with NULL values for the selected facility</div>
            </div>
            <div class="step-status"><?php echo !empty($selected_facility) && $record_count > 0 ? '👁️' : '⏳'; ?></div>
        </div>
        <div class="step <?php echo !empty($selected_facility) && $record_count > 0 ? 'active' : ''; ?>" id="step3">
            <div class="step-number">3</div>
            <div class="step-content">
                <div class="step-title">Choose Delivery Point</div>
                <div class="step-desc">Select a delivery point to populate the NULL fields</div>
            </div>
            <div class="step-status"><?php echo !empty($selected_facility) && $record_count > 0 ? '📦' : '⏳'; ?></div>
        </div>
        <div class="step" id="step4">
            <div class="step-number">4</div>
            <div class="step-content">
                <div class="step-title">Update Records</div>
                <div class="step-desc">Click the update button to populate all NULL values</div>
            </div>
            <div class="step-status" id="step4Status"><?php echo isset($_GET['updated']) && $_GET['updated'] > 0 ? '🎉' : '⏳'; ?></div>
        </div>
    </div>

    <!-- Info Box -->
    <div class="info-box">
        <h3>📌 How It Works</h3>
        <p>
            This tool identifies records where <strong>Demander</strong> or <strong>DemanderCode_str</strong> is NULL or empty.
        </p>
        <ul>
            <li><strong>Step 1:</strong> Select a facility from the list below</li>
            <li><strong>Step 2:</strong> Review the records that have NULL values</li>
            <li><strong>Step 3:</strong> Choose a delivery point from the dropdown</li>
            <li><strong>Step 4:</strong> Click "Update Records" to populate all NULL fields</li>
            <li><strong>DemanderCode_str</strong> ← <code>del_point</code> (selected from dropdown)</li>
            <li><strong>Demander</strong> ← <code>dem_name</code> (automatically mapped from del_point)</li>
        </ul>
    </div>

    <?php if (empty($null_facilities)): ?>
        <!-- Empty State -->
        <div class="empty-state">
            <div class="icon">🎉</div>
            <h3>No NULL Values Found</h3>
            <p>All records have valid <strong>Demander</strong> and <strong>DemanderCode_str</strong> values.<br>
            No action is required at this time.</p>
            <a href="index.php" class="btn btn-primary" style="margin-top:16px;">Return to Dashboard</a>
        </div>
    <?php else: ?>
        <!-- Facility Selection -->
        <div style="margin-bottom:20px;">
            <h3 style="font-size:18px; color:#0b1b2f; margin-bottom:12px;">
                🏥 Select a Facility
                <span class="badge"><?php echo count($null_facilities); ?> facilities with NULL values</span>
            </h3>
            
            <div class="facility-grid">
                <?php foreach ($null_facilities as $facility): 
                    $count = $facility_counts[$facility] ?? 0;
                    $is_selected = ($selected_facility === $facility);
                ?>
                    <a href="?facility=<?php echo urlencode($facility); ?>" 
                       class="facility-item <?php echo $is_selected ? 'selected' : ''; ?>"
                       style="<?php echo $is_selected ? 'border-color:#1a4f8a; background:#e6edf8;' : ''; ?>">
                        <div class="facility-info">
                            <div class="facility-name"><?php echo htmlspecialchars($facility); ?></div>
                        </div>
                        <span class="facility-badge"><?php echo number_format($count); ?> records</span>
                        <span class="facility-arrow"><?php echo $is_selected ? '✓' : '→'; ?></span>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Records Display -->
        <?php if (!empty($selected_facility) && $record_count > 0): ?>
            <div class="records-section">
                <div class="table-header">
                    <div>
                        <h3>📄 Records for <span style="color:#1a4f8a;"><?php echo htmlspecialchars($selected_facility_display); ?></span></h3>
                        <span class="badge-count"><?php echo $record_count; ?> records with NULL values</span>
                    </div>
                    <div>
                        <a href="index.php" class="btn btn-secondary">✕ Clear Selection</a>
                    </div>
                </div>
                
                <table id="recordsTable" class="display" style="width:100%;">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Invoice No.</th>
                            <th>Order No.</th>
                            <th>Description</th>
                            <th>Qty Received</th>
                            <th>Current Demander</th>
                            <th>Current DemanderCode</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($records as $record): ?>
                            <tr>
                                <td><strong><?php echo $record['id']; ?></strong></td>
                                <td><?php echo htmlspecialchars($record['InvoiceNo_str'] ?? 'N/A'); ?></td>
                                <td><?php echo htmlspecialchars($record['OrderNo_str'] ?? 'N/A'); ?></td>
                                <td><?php echo htmlspecialchars(substr($record['packDescription_Str'] ?? '', 0, 50)) . (strlen($record['packDescription_Str'] ?? '') > 50 ? '...' : ''); ?></td>
                                <td><?php echo number_format($record['QtyReceived_int'] ?? 0); ?></td>
                                <td><span style="color:#c0392b;"><?php echo $record['Demander'] ? htmlspecialchars($record['Demander']) : 'NULL'; ?></span></td>
                                <td><span style="color:#c0392b;"><?php echo $record['DemanderCode_str'] ? htmlspecialchars($record['DemanderCode_str']) : 'NULL'; ?></span></td>
                                <td><span class="status-badge null">⚠️ NULL</span></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Update Form -->
            <form method="post" action="index.php" onsubmit="return confirmUpdate()">
                <input type="hidden" name="action" value="update_records">
                <input type="hidden" name="facility" value="<?php echo htmlspecialchars($selected_facility); ?>">
                
                <div class="update-area">
                    <div class="update-label">📦 Step 3: Select Delivery Point to Populate NULL Fields</div>
                    
                    <div style="margin:16px 0;">
                        <label style="font-weight:600; color:#0b1b2f; display:block; margin-bottom:8px;">
                            Choose a Delivery Point:
                        </label>
                        <select name="del_point" id="delPointSelect" required style="width:100%; max-width:500px; padding:12px 16px; border:2px solid #d0d9e6; border-radius:10px; font-size:14px;">
                            <option value="">-- Select Delivery Point --</option>
                            <?php foreach ($del_point_list as $dp): ?>
                                <option value="<?php echo htmlspecialchars($dp['del_point']); ?>" 
                                        data-demname="<?php echo htmlspecialchars($dp['dem_name']); ?>">
                                    <?php echo htmlspecialchars($dp['dem_name']); ?> (<?php echo htmlspecialchars($dp['del_point']); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div id="mappingPreview" style="display:none; background:#fff; padding:12px 16px; border-radius:8px; margin:12px 0; border:1px solid #d0e6d8;">
                        <strong>Preview Mapping:</strong><br>
                        <span id="previewDemander" style="color:#1a8a4a; font-weight:600;"></span>
                        <span style="margin:0 8px;">←</span>
                        <span id="previewDemanderCode" style="color:#1a4f8a; font-weight:600;"></span>
                    </div>
                    
                    <div class="update-info">
                        <div class="info-item">
                            <strong>Facility:</strong> 
                            <span class="value"><?php echo htmlspecialchars($selected_facility_display); ?></span>
                        </div>
                        <div class="info-item">
                            <strong>Records to Update:</strong> 
                            <span class="value"><?php echo $record_count; ?></span>
                        </div>
                        <div class="info-item">
                            <strong>Will Update:</strong><br>
                            <span style="color:#1a8a4a;">Demander ← dem_name</span><br>
                            <span style="color:#1a4f8a;">DemanderCode_str ← del_point</span>
                        </div>
                    </div>
                    
                    <div style="margin-top:16px;">
                        <button type="submit" class="btn btn-success" style="font-size:16px; padding:12px 32px;">
                            ⚡ Update <?php echo $record_count; ?> Records
                        </button>
                        <button type="button" class="btn btn-secondary" onclick="window.location.href='index.php'">
                            Cancel
                        </button>
                    </div>
                </div>
            </form>

        <?php elseif (!empty($selected_facility) && $record_count == 0): ?>
            <div class="message warning">
                ⚠️ No records with NULL values found for facility: <strong><?php echo htmlspecialchars($selected_facility_display); ?></strong>
                <br><a href="index.php" class="btn btn-secondary" style="margin-top:8px; display:inline-block;">← Back to Facilities</a>
            </div>
        <?php endif; ?>
    <?php endif; ?>

    <a href="index.php" class="back-link">← Return to Dashboard</a>
</div>

<script>
$(document).ready(function() {
    // Initialize DataTable if records exist
    <?php if (!empty($selected_facility) && $record_count > 0): ?>
    $('#recordsTable').DataTable({
        pageLength: 25,
        responsive: true,
        order: [[0, 'desc']],
        language: {
            search: "Search:",
            lengthMenu: "Show _MENU_ entries",
            info: "Showing _START_ to _END_ of _TOTAL_ entries"
        }
    });
    <?php endif; ?>
    
    // Preview mapping when selecting delivery point
    $('#delPointSelect').on('change', function() {
        const selected = $(this).find('option:selected');
        const demName = selected.data('demname');
        const delPoint = selected.val();
        
        if (delPoint) {
            $('#previewDemander').text(demName);
            $('#previewDemanderCode').text(delPoint);
            $('#mappingPreview').show();
        } else {
            $('#mappingPreview').hide();
        }
    });
    
    // Update step 4 status if we have a success message
    <?php if (isset($_GET['updated']) && $_GET['updated'] > 0): ?>
    $('#step4').addClass('completed');
    $('#step4Status').text('🎉');
    <?php endif; ?>
});

// Confirm update
function confirmUpdate() {
    const delPoint = document.getElementById('delPointSelect');
    if (!delPoint.value) {
        alert('Please select a delivery point first.');
        return false;
    }
    
    const selectedOption = delPoint.options[delPoint.selectedIndex];
    const demName = selectedOption.dataset.demname;
    const recordCount = <?php echo $record_count; ?>;
    
    return confirm(
        '⚠️ WARNING: You are about to update ' + recordCount + ' record(s).\n\n' +
        'Facility: <?php echo htmlspecialchars($selected_facility_display); ?>\n' +
        'Demander will be set to: ' + demName + '\n' +
        'DemanderCode_str will be set to: ' + delPoint.value + '\n\n' +
        'This action is permanent and cannot be undone.\n\n' +
        '✅ Proceed with update?'
    );
}
</script>
</body>
</html>