<?php
require_once('connectionSC.php');
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Respon default
$response = array('status' => 'error', 'message' => 'Invalid request');

// Pastikan permintaan menggunakan metode POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Ambil data dari body request
    $username = isset($_POST['username']) ? trim($_POST['username']) : '';
    $newPassword = isset($_POST['newPassword']) ? trim($_POST['newPassword']) : '';

    // Validasi input
    if (!empty($username) && !empty($newPassword)) {
        // Hash password dengan MD5
        $hashedPassword = md5($newPassword);

        // Prepared statement untuk update password
        $stmt = $conn->prepare("UPDATE admin SET password = ? WHERE username = ?");
        $stmt->bind_param("ss", $hashedPassword, $username);

        if ($stmt->execute()) {
            $response['status'] = 'success';
            $response['message'] = 'Password updated successfully';
        } else {
            $response['status'] = 'error';
            $response['message'] = 'Failed to update password.';
        }

        $stmt->close();
    } else {
        $response['status'] = 'error';
        $response['message'] = 'Invalid input. Username and Password are required.';
    }
}

// Tutup koneksi
$conn->close();

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
// Kirim respon dalam format JSON
header('Content-Type: application/json');
echo json_encode($response);
?>
