<?php

// Start output buffering to prevent header issues
ob_start();
include("configa.php");

// Set the header to ensure the response is treated as JSON
header('Content-Type: application/json; charset=UTF-8');

// Check if the request method is POST
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Check for a valid database connection
    if ($conn->connect_error) {
        // Return a JSON error message if the connection fails
        echo json_encode(['status' => 'error', 'message' => 'Connection failed: ' . $conn->connect_error]);
        exit;
    }

    // Sanitize and get data from the POST request
    $mobile     = $conn->real_escape_string($_POST['mobile'] ?? '');
    $otp        = $_POST['otp'] ?? '';
    $first_name = $conn->real_escape_string($_POST['first_name'] ?? '');
    $last_name  = $conn->real_escape_string($_POST['last_name'] ?? '');
    $division   = $conn->real_escape_string($_POST['division'] ?? '');
    $district   = $conn->real_escape_string($_POST['district'] ?? '');
    $upazila    = $conn->real_escape_string($_POST['upazila'] ?? '');
    $up         = $conn->real_escape_string($_POST['up'] ?? '');
    $address    = $conn->real_escape_string($_POST['address'] ?? '');
    $username   = $conn->real_escape_string($_POST['username'] ?? '');


    // Check if the mobile number is provided
    if (empty($mobile)) {
        echo json_encode(['status' => 'error', 'message' => 'Mobile number is required.']);
        $conn->close();
        exit;
    }

    // Check if the user exists in the database
    $sql_check = "SELECT mobile FROM login_gest WHERE mobile = ?";
    $stmt_check = $conn->prepare($sql_check);
    $stmt_check->bind_param("s", $mobile);
    $stmt_check->execute();
    $result_check = $stmt_check->get_result();

    if ($result_check->num_rows === 0) {
        echo json_encode(['status' => 'error', 'message' => 'User not found.']);
        $stmt_check->close();
        $conn->close();
        exit;
    }
    $stmt_check->close();

    // Dynamically build the UPDATE query
    $sql_update = "UPDATE login_gest SET ";
    $params = [];
    $types = "";

    // Check for each field and add it to the query if not empty
    if (!empty($username)) {
        $sql_update .= "username = ?, ";
        $params[] = $username;
        $types .= "s";
    }
    if (!empty($first_name)) {
        $sql_update .= "first_name = ?, ";
        $params[] = $first_name;
        $types .= "s";
    }
    if (!empty($last_name)) {
        $sql_update .= "last_name = ?, ";
        $params[] = $last_name;
        $types .= "s";
    }
    if (!empty($division)) {
        $sql_update .= "division = ?, ";
        $params[] = $division;
        $types .= "s";
    }
    if (!empty($district)) {
        $sql_update .= "district = ?, ";
        $params[] = $district;
        $types .= "s";
    }
    if (!empty($upazila)) {
        $sql_update .= "upazila = ?, ";
        $params[] = $upazila;
        $types .= "s";
    }
    if (!empty($up)) {
        $sql_update .= "up = ?, ";
        $params[] = $up;
        $types .= "s";
    }
    if (!empty($address)) {
        $sql_update .= "address = ?, ";
        $params[] = $address;
        $types .= "s";
    }
    if (!empty($otp)) {
        $hashed_password = password_hash($otp, PASSWORD_DEFAULT);
        $sql_update .= "password = ?, ";
        $params[] = $hashed_password;
        $types .= "s";
    }
    
    // Remove the trailing comma and space from the query string
    $sql_update = rtrim($sql_update, ", ");
    $sql_update .= " WHERE mobile = ?";
    $params[] = $mobile;
    $types .= "s";

    // If no fields are to be updated, exit with a message
    if (count($params) <= 1) {
        echo json_encode(['status' => 'error', 'message' => 'No information to update.']);
        $conn->close();
        exit;
    }

    // Prepare and execute the update statement
    $stmt_update = $conn->prepare($sql_update);
    if (!$stmt_update) {
        echo json_encode(['status' => 'error', 'message' => 'SQL prepare failed: ' . $conn->error]);
        $conn->close();
        exit;
    }

    // Bind parameters and execute the query
    $stmt_update->bind_param($types, ...$params);

    if ($stmt_update->execute()) {
        if ($stmt_update->affected_rows > 0) {
          $hide = 1;
            echo json_encode(['status' => 'success', 'message' => 'প্রোপ্রাইল আপডেট সফল হয়েছে।' ]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'No changes were made.']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Error updating record: ' . $stmt_update->error]);
    }

    $stmt_update->close();
    $conn->close();
    exit;
}

// Handle GET requests, returning a JSON error
echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
