<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

include_once __DIR__ . "/../config.php";

$response = ["success" => false, "message" => "Invalid request"];

// Get JSON input
$data = json_decode(file_get_contents("php://input"), true);

if (isset($data['client_index']) && isset($data['email'])) {
    $id = (int)$data['client_index'];
    $email = $conn->real_escape_string($data['email']);

    // Fields that can be updated
    $updatableFields = [
        "username", "dob", "number", "address", "website", "company_name",
        "company_address", "company_number", "db_prefex", "profile_pic",
        "country", "dial_code", "zipcode", "city", "state"
    ];

    $updates = [];
    foreach ($updatableFields as $field) {
        if (isset($data[$field])) {
            $value = $conn->real_escape_string($data[$field]);
            $updates[] = "$field = '$value'";
        }
    }

    if (!empty($updates)) {
        $sql = "UPDATE adminlogins 
                SET " . implode(", ", $updates) . " 
                WHERE client_index=$id AND email='$email'";

        if ($conn->query($sql)) {
            // ✅ Fetch record even if no rows affected
            $selectSql = "SELECT client_index, username, email, gender, dob, number, address, website, date, uid,
                                 company_name, CONVERT(company_address USING utf8) AS company_address, 
                                 company_number, db_prefex, status, profile_pic, empId, 
                                 userDepartment, userRole, userAccessLevel, emailToken, email_confirmed,
                                 email_token_time, country, dial_code, zipcode, city, state
                          FROM adminlogins
                          WHERE client_index=$id AND email='$email'
                          LIMIT 1";
            $result = $conn->query($selectSql);

            if ($result && $result->num_rows > 0) {
                $updatedData = $result->fetch_assoc();
                $response = [
                    "success" => true,
                    "message" => "Profile updated successfully",
                    "data" => $updatedData
                ];
            } else {
                $response = ["success" => false, "message" => "Record exists but could not fetch updated data"];
            }
        } else {
            $response = ["success" => false, "message" => "Error updating profile: " . $conn->error];
        }
    } else {
        $response = ["success" => false, "message" => "No valid fields to update"];
    }
} else {
    $response = ["success" => false, "message" => "Client ID and Email required"];
}

echo json_encode($response);
?>
