<?php 
require dirname(dirname(__FILE__)) . '/inc/config.php';
require dirname(dirname(__FILE__)) . '/inc/FunctionQuery.php';
require dirname(dirname(__FILE__)) . '/inc/keyvaliation.php';

header('Content-type: application/json');
$data = json_decode(file_get_contents('php://input'), true);

if ($data['uid'] == '') {
    $returnArr = array(
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Something Went Wrong!"
    );
    echo json_encode($returnArr);
    exit;
}

$owner_id = intval($data['uid']);

// FETCH OWNER PROFILE
$lprofile = $service->query("SELECT name, pro_pic, rdate 
    FROM tbl_user WHERE id = $owner_id")->fetch_assoc();

$apro = array();
$apro['name'] = $lprofile['name'];
$apro['pro_pic'] = $lprofile['pro_pic'];
$apro['rdate'] = $lprofile['rdate'];

// FETCH AVERAGE REVIEW
$rdata_rest = $service->query("
    SELECT SUM(total_lrate)/COUNT(*) AS rate_rest 
    FROM tbl_load 
    WHERE lorry_owner_id = $owner_id 
      AND load_status='Completed' 
      AND total_lrate != 0
")->fetch_assoc();

$apro['review'] = (empty($rdata_rest['rate_rest'])) 
                    ? "5" 
                    : number_format((float)$rdata_rest['rate_rest'], 2, '.', '');

$apro['total_review'] = $service->query("
    SELECT id FROM tbl_load 
    WHERE lorry_owner_id = $owner_id 
      AND is_lrate = 1
")->num_rows;

$apro['total_load'] = $service->query("
    SELECT id FROM tbl_load 
    WHERE lorry_owner_id = $owner_id
")->num_rows;


// ✅ FETCH INDIVIDUAL REVIEWS WHERE OWNER WAS REVIEWED
$reviewRows = $service->query("
    SELECT uid, total_lrate, rate_ltext 
    FROM tbl_load 
    WHERE lorry_owner_id = $owner_id 
      AND is_lrate = 1
    ORDER BY id DESC
");

$uo = array();

while ($row = $reviewRows->fetch_assoc()) {

    $reviewer_id = intval($row['uid']); // This is the REAL reviewer

    // Fetch reviewer details
    $udata = $service->query("
        SELECT pro_pic, name 
        FROM tbl_user 
        WHERE id = $reviewer_id
        LIMIT 1
    ")->fetch_assoc();

    $po = array();
    $po['user_img'] = $udata['pro_pic'];
    $po['customername'] = $udata['name'];
    $po['rate_number'] = $row['total_lrate'];
    $po['rate_text'] = $row['rate_ltext'];

    $uo[] = $po;
}

$apro['total_review_user_wise'] = $uo;

$returnArr = array(
    "lorrizprofile" => $apro,
    "ResponseCode" => "200",
    "Result" => "true",
    "ResponseMsg" => "Transporter Profile Get successfully!"
);

echo json_encode($returnArr);
?>
