<?php
// AJAX endpoint — search consumer by meter/connection number
require_once __DIR__ . '/../../includes/init.php';
middleware(['mr','je','sdo','exn','super_admin']);

header('Content-Type: application/json');

$q    = trim($_GET['q'] ?? '');
$type = $_GET['type'] ?? 'kcc';

if (strlen($q) < 2) {
    echo json_encode(['success' => false, 'message' => 'Query too short']);
    exit;
}

try {
    $db = getDBConnection();

    // Check columns
    $cols    = array_column($db->query("SHOW COLUMNS FROM consumers")->fetchAll(PDO::FETCH_ASSOC), 'Field');
    $hasType = in_array('type', $cols);

    $typeFilter = '';
    if ($hasType) {
        $typeFilter = ($type === 'solar')
            ? "AND type IN ('solar','both')"
            : "AND type IN ('kcc','both')";
    }
    $selectType = $hasType ? ', type' : ", 'kcc' AS type";

    // ── Division filter for MR only ───────────────────────────
    $divFilter = '';
    $divParams = [];

    if (getSession('role') === 'mr') {
        // Always fetch from DB so admin division changes apply immediately
        $freshDiv = dbRow($db, "SELECT division FROM users WHERE id=?", [(int)getSession('user_id')]);
        $rawDiv   = $freshDiv['division'] ?? '';
        if ($rawDiv !== (getSession('division') ?? '')) setSession('division', $rawDiv);

        // 'All' or empty = no restriction
        if ($rawDiv && $rawDiv !== 'All') {
            // Try JSON array first (new format)
            $decoded  = json_decode($rawDiv, true);
            $assigned = is_array($decoded) ? $decoded : [$rawDiv];
            $assigned = array_filter($assigned); // remove empty

            if (!empty($assigned)) {
                $placeholders = implode(',', array_fill(0, count($assigned), '?'));
                $divFilter    = "AND division IN ({$placeholders})";
                $divParams    = array_values($assigned);
            }
        }
    }

    $params   = array_merge([$q, $q], $divParams);
    $consumer = dbRow($db,
        "SELECT id, consumer_name, meter_number, connection_number, address, division {$selectType}
         FROM consumers
         WHERE (meter_number = ? OR connection_number = ?) AND is_active = 1 {$typeFilter} {$divFilter}
         LIMIT 1",
        $params
    );

    if ($consumer) {
        // Check for duplicate bill this month if requested
        if (($_GET['check_bill'] ?? '') === '1') {
            $existingBill = dbRow($db,
                "SELECT b.created_at, u.full_name AS mr_name
                 FROM bills b
                 LEFT JOIN users u ON u.id = b.user_id
                 WHERE b.consumer_id = ?
                   AND YEAR(b.created_at)  = YEAR(CURDATE())
                   AND MONTH(b.created_at) = MONTH(CURDATE())
                 ORDER BY b.created_at DESC LIMIT 1",
                [$consumer['id']]
            );
            if ($existingBill) {
                $consumer['bill_this_month'] = true;
                $consumer['bill_mr_name']    = $existingBill['mr_name'] ?? 'Unknown';
                $consumer['bill_date']       = date('d M Y', strtotime($existingBill['created_at']));
                $consumer['bill_month_label']= date('F Y');
            } else {
                $consumer['bill_this_month'] = false;
            }
        }
        echo json_encode(['success' => true, 'consumer' => $consumer]);
    } else {
        $msg = (!empty($divFilter))
            ? 'Consumer not found in your assigned division.'
            : 'Consumer not found.';
        echo json_encode(['success' => false, 'message' => $msg]);
    }

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
