<?php
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '/home/kdsmf/earnperday.live/backend/config/db.php';

$data = json_decode(file_get_contents('php://input'), true);
$currentPass = $data['currentPass'] ?? '';
$newUsername  = trim($data['newUsername'] ?? '');
$newPassword  = trim($data['newPassword'] ?? '');

// Validation
if (empty($currentPass) || empty($newUsername) || empty($newPassword)) {
    echo json_encode(["status" => "error", "message" => "Sare fields required hain."]);
    exit;
}

try {
    // Step 1: Admin ka current data fetch karo
    $result = mysqli_query($conn, "SELECT * FROM admin WHERE id = 1");

    if (!$result) {
        echo json_encode(["status" => "error", "message" => "Query failed: " . mysqli_error($conn)]);
        exit;
    }

    $admin = mysqli_fetch_assoc($result);

    if (!$admin) {
        echo json_encode(["status" => "error", "message" => "Admin row id=1 nahi mila. Table check karo."]);
        exit;
    }

    // Step 2: Password verify - plain text
    $passwordCorrect = ($currentPass === $admin['password']);
    // Agar hashed hai toh upar wali line comment karo aur neeche uncomment karo:
    // $passwordCorrect = password_verify($currentPass, $admin['password']);

    if (!$passwordCorrect) {
        echo json_encode(["status" => "error", "message" => "Current password galat hai."]);
        exit;
    }

    // Step 3: Update
    $safeUsername = mysqli_real_escape_string($conn, $newUsername);
    $safePassword = mysqli_real_escape_string($conn, $newPassword);

    $updateResult = mysqli_query($conn, "UPDATE admin SET username = '$safeUsername', password = '$safePassword' WHERE id = 1");

    if (!$updateResult) {
        echo json_encode(["status" => "error", "message" => "Update failed: " . mysqli_error($conn)]);
        exit;
    }

    $affected = mysqli_affected_rows($conn);

    if ($affected > 0) {
        echo json_encode(["status" => "success", "message" => "Credentials successfully update ho gaye!"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Koi change nahi hua. Naya data purane jaisa hai."]);
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Server Error: " . $e->getMessage()]);
}
?>