<?php
session_start();
header('Content-Type: text/plain; charset=utf-8');

if (!isset($_SESSION['admin_logged_in'])) {
    http_response_code(401);
    echo 'Unauthorized';
    exit;
}

include 'dblive.php';

try {
    $pdo = new PDO("mysql:host=$user_db_servername;dbname=$user_db_name;charset=utf8", $user_db_username, $user_db_password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    http_response_code(500);
    echo 'DB connect error: ' . htmlspecialchars($e->getMessage());
    exit;
}

$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$password = isset($_POST['password']) ? (string)$_POST['password'] : '';

if ($id <= 0 || $password === '' || strlen($password) < 6) {
    http_response_code(400);
    echo 'Bad request';
    exit;
}

try {
    $hash = password_hash($password, PASSWORD_BCRYPT);
    $stmt = $pdo->prepare('UPDATE kullanici2 SET sifre = :pw, updated_at = NOW() WHERE id = :id');
    $stmt->execute([':pw' => $hash, ':id' => $id]);
    http_response_code(200);
    echo 'OK';
} catch (PDOException $e) {
    http_response_code(500);
    echo 'DB error: ' . htmlspecialchars($e->getMessage());
}