<?php
// File: admin/metode/simpan_metode.php
header('Content-Type: application/json');
include '../../config/koneksi.php';
include '../../config/id_generator.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $metode_id = isset($_POST['metode_id']) ? $_POST['metode_id'] : '';
    $tipe_metode = $_POST['tipe_metode'] ?? '';
    $nama_metode = $_POST['nama_metode'] ?? '';
    $rekening_no = $_POST['rekening_no'] ?? '';
    $atas_nama = $_POST['atas_nama'] ?? '';
    $active_st = isset($_POST['active_st']) ? intval($_POST['active_st']) : 1;
    $admin_name = $_POST['admin_name'] ?? 'Admin';

    if (empty($tipe_metode) || empty($nama_metode) || empty($atas_nama)) {
        echo json_encode(["status" => "gagal", "pesan" => "Tipe, Nama, dan Atas Nama harus diisi", "data" => []]);
        exit;
    }

    $qris_gambar = null;
    $upload_dir = '../../uploads/qris/';

    // Proses upload gambar base64 jika ada
    if (isset($_POST['qris_gambar_base64']) && !empty($_POST['qris_gambar_base64'])) {
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        $file_name = time() . '_qris.png';
        $target_path = $upload_dir . $file_name;

        $base64_string = $_POST['qris_gambar_base64'];
        $data = explode(',', $base64_string);
        $image_data = count($data) > 1 ? $data[1] : $data[0];
        
        if (file_put_contents($target_path, base64_decode($image_data))) {
            $qris_gambar = $file_name;
        } else {
            echo json_encode(["status" => "gagal", "pesan" => "Gagal menyimpan gambar QRIS", "data" => []]);
            exit;
        }
    }

    if (!empty($metode_id)) {
        // Mode UPDATE
        // Cek gambar lama jika upload baru
        if ($qris_gambar !== null) {
            $stmt_old = $conn->prepare("SELECT qris_gambar FROM mst_metode_bayar WHERE metode_id = ?");
            $stmt_old->bind_param("s", $metode_id);
            $stmt_old->execute();
            $res_old = $stmt_old->get_result();
            if ($row_old = $res_old->fetch_assoc()) {
                if (!empty($row_old['qris_gambar']) && file_exists($upload_dir . $row_old['qris_gambar'])) {
                    unlink($upload_dir . $row_old['qris_gambar']);
                }
            }
            $stmt_old->close();

            $query = "UPDATE mst_metode_bayar SET tipe_metode=?, nama_metode=?, rekening_no=?, atas_nama=?, qris_gambar=?, active_st=?, updated_by=?, updated_at=CURRENT_TIMESTAMP WHERE metode_id=?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("sssssiss", $tipe_metode, $nama_metode, $rekening_no, $atas_nama, $qris_gambar, $active_st, $admin_name, $metode_id);
        } else {
            $query = "UPDATE mst_metode_bayar SET tipe_metode=?, nama_metode=?, rekening_no=?, atas_nama=?, active_st=?, updated_by=?, updated_at=CURRENT_TIMESTAMP WHERE metode_id=?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("ssssiss", $tipe_metode, $nama_metode, $rekening_no, $atas_nama, $active_st, $admin_name, $metode_id);
        }

        if ($stmt->execute()) {
            echo json_encode(["status" => "sukses", "pesan" => "Metode pembayaran berhasil diperbarui", "data" => []]);
        } else {
            echo json_encode(["status" => "gagal", "pesan" => "Gagal memperbarui metode: " . $stmt->error, "data" => []]);
        }
        $stmt->close();
    } else {
        // Mode INSERT
        $metode_id = generateMetodeId($conn);
        $query = "INSERT INTO mst_metode_bayar (metode_id, tipe_metode, nama_metode, rekening_no, atas_nama, qris_gambar, active_st, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ssssssis", $metode_id, $tipe_metode, $nama_metode, $rekening_no, $atas_nama, $qris_gambar, $active_st, $admin_name);

        if ($stmt->execute()) {
            echo json_encode(["status" => "sukses", "pesan" => "Metode pembayaran berhasil ditambahkan", "data" => []]);
        } else {
            echo json_encode(["status" => "gagal", "pesan" => "Gagal menambah metode: " . $stmt->error, "data" => []]);
        }
        $stmt->close();
    }
} else {
    echo json_encode(["status" => "gagal", "pesan" => "Metode tidak diizinkan", "data" => []]);
}

$conn->close();
?>
