<?php 
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php'); ;
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

// Get clientnumber from request
$clientnumber = isset($_REQUEST['clientnumber']) ? intval($_REQUEST['clientnumber']) : 0;

if (!$clientnumber) {
    echo json_encode([
        'success' => false,
        'message' => 'Client number is missing or invalid.',
    ]);
    exit;
}

try {
    // Fetch boards, location, postcode, and number of circuits
    $query = "
        SELECT 
            b.board_id,
            b.board_name,
            b.circuit_mode,
            l.locnumber,
            l.locname,
            l.postcode,
            (SELECT COUNT(c.circuit_id) 
             FROM elec_circuit c 
             WHERE c.board_id = b.board_id) AS circuits_count,
            (
                SELECT COUNT(er.report_id)
                FROM elec_report er
                WHERE er.board_id = b.board_id
                  AND er.status = 'active'
            ) AS active_reports
        FROM elec_board b
        LEFT JOIN locations l ON b.locnumber = l.locnumber
        WHERE b.clientnumber = ?
        GROUP BY b.board_id
        ORDER BY b.board_name ASC
    ";
    $stmt = $con->prepare($query);
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $result = $stmt->get_result();

    $boards = [];
    while ($row = $result->fetch_assoc()) {
        $boards[] = [
            'board_id' => $row['board_id'],
            'board_name' => $row['board_name'],
            'board_type' =>  ($row['circuit_mode'] == 'LV') ? '3 Phase' : 'Single Phase',
            'location_name' => $row['locname'],
            'postcode' => $row['postcode'],
            'circuits_count' => $row['circuits_count'],
            'link_chain' => $row['board_id']."|".$clientnumber."|".$row['locnumber'],
             'active_report_status'=> ($row['active_reports'] > 0) ? 'active' : ''
        ];
    }

    $stmt->close();

    // Return boards data as JSON
    echo json_encode([
        'success' => true,
        'boards' => $boards,
    ]);

} catch (Exception $e) {
    // Handle exceptions and log errors
    error_log("Error fetching client boards: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred while fetching boards.',
    ]);
}