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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once __DIR__ . "/../config.php";

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

if (!$data || !isset($data['ac_index'])) {
    echo json_encode([
        "success" => false,
        "error"   => "Invalid input. 'ac_index' is required."
    ]);
    exit;
}

$ac_index = (int)$data['ac_index'];
unset($data['ac_index']); // remove key, rest are update fields

if (empty($data)) {
    echo json_encode([
        "success" => false,
        "error"   => "No fields provided to update."
    ]);
    exit;
}

try {
    // DB connection
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $dbh = new PDO($dsn, DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);

    // Build dynamic query
    $fields = [];
    $params = [":ac_index" => $ac_index];
    foreach ($data as $key => $value) {
        $fields[] = "`$key` = :$key";
        $params[":$key"] = $value;
    }

    $sql = "UPDATE account_types SET " . implode(", ", $fields) . " WHERE ac_index = :ac_index LIMIT 1";
    $stmt = $dbh->prepare($sql);
    $stmt->execute($params);

    if ($stmt->rowCount() > 0) {
        echo json_encode([
            "success" => true,
            "message" => "Account type updated successfully."
        ]);
    } else {
        echo json_encode([
            "success" => false,
            "message" => "No changes made (record may not exist or same values provided)."
        ]);
    }
} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "error"   => "Database update failed",
        "details" => $e->getMessage()
    ]);
    exit;
}
