<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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


// Atur header untuk response JSON dan izin CORS
// header("Access-Control-Allow-Origin: http://192.168.101.123");
// header("Content-Type: application/json");
// header("Access-Control-Allow-Methods: POST");
// header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Origin: *");

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Metode request harus POST.']);
    exit();
}

// Database credentials
$servername = "localhost";
$username = "dmoxnpnp_pos";
$password = "jakarta183";
$dbname = "dmoxnpnp_pos_m";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    http_response_code(500);
    echo json_encode(['error' => 'Koneksi database gagal: ' . $conn->connect_error]);
    exit();
}

// ==================================================================
// LOGIKA UTAMA: Cek apakah ini proses REDEEM atau GET DATA
// ==================================================================

if (isset($_POST['reward_kode']) && !empty($_POST['reward_kode'])) {
    
    // --- PROSES 1: REDEEM HADIAH & GET DATA ---

    if (!isset($_POST['member_id'])) {
        http_response_code(400);
        echo json_encode(['error' => "ID Member dibutuhkan untuk redeem."]);
        exit();
    }

    $member_id = $_POST['member_id'];
    $reward_kode = $_POST['reward_kode'];

    // Langkah 1: Ambil data reward dari database
    $stmt_reward = $conn->prepare("SELECT * FROM reward WHERE kode = ?");
    $stmt_reward->bind_param("s", $reward_kode);
    $stmt_reward->execute();
    $result_reward = $stmt_reward->get_result();
    if ($result_reward->num_rows === 0) {
        http_response_code(404);
        echo json_encode(['error' => 'Kode hadiah tidak ditemukan.']);
        exit();
    }
    $reward_data = $result_reward->fetch_assoc();
    $stmt_reward->close();

    // Langkah 2: Validasi member (jika reward bersifat khusus)
    if (!empty($reward_data['member']) && $reward_data['member'] != $member_id) {
        http_response_code(403); // Forbidden
        echo json_encode(['error' => 'Hadiah ini khusus untuk member lain.']);
        exit();
    }

    // Langkah 3: Ambil data poin member saat ini & validasi kecukupan poin
    $stmt_member = $conn->prepare("SELECT point FROM member WHERE id = ?");
    $stmt_member->bind_param("i", $member_id);
    $stmt_member->execute();
    $result_member = $stmt_member->get_result();
    if ($result_member->num_rows === 0) {
        http_response_code(404);
        echo json_encode(['error' => 'Data member tidak ditemukan.']);
        exit();
    }
    $member_current_data = $result_member->fetch_assoc();
    $poin_sebelum = (int)$member_current_data['point'];
    $stmt_member->close();

    if ($poin_sebelum < (int)$reward_data['poin_tukar']) {
        http_response_code(400); // Bad Request
        echo json_encode(['error' => 'Poin tidak mencukupi untuk menukar hadiah ini.']);
        exit();
    }

    // Langkah 4: Lakukan transaksi database
    $conn->begin_transaction();
    try {
        // 4a: Insert ke trx_member
        $poin_untuk_dikurangi = -abs((int)$reward_data['poin_tukar']);
        $jual_string = $reward_data['nama'] . '-' . $reward_data['harga'] . '_' . $reward_data['nama_menu'];
        
        $stmt_insert = $conn->prepare("INSERT INTO trx_member (member, jenis, point, jual, reward, menu, cab, brand, tanggal) VALUES (?, 'REDEEM', ?, ?, ?, ?, '', '', NOW())");
        $stmt_insert->bind_param("isssi", $member_id, $poin_untuk_dikurangi, $jual_string, $reward_kode, $reward_data['kode_menu']);
        $stmt_insert->execute();
        $trx_member_id = $stmt_insert->insert_id; // Ambil ID transaksi yang baru dibuat
        $stmt_insert->close();

        // 4b: Update poin di tabel member
        $stmt_update = $conn->prepare("UPDATE member SET point = point + ? WHERE id = ?");
        $stmt_update->bind_param("ii", $poin_untuk_dikurangi, $member_id);
        $stmt_update->execute();
        $stmt_update->close();

        $conn->commit();
    } catch (mysqli_sql_exception $exception) {
        $conn->rollback();
        http_response_code(500);
        echo json_encode(['error' => 'Transaksi database gagal: ' . $exception->getMessage()]);
        exit();
    }

    // Langkah 5: Ambil data member TERBARU setelah poin dikurangi
    $stmt_final = $conn->prepare("SELECT * FROM member WHERE id = ?");
    $stmt_final->bind_param("i", $member_id);
    $stmt_final->execute();
    $final_member_data = $stmt_final->get_result()->fetch_assoc();
    $stmt_final->close();

    // Langkah 6: Siapkan dan kirim respons JSON yang lengkap
    $final_member_data['redeem_success_message'] = "Redeem '" . $reward_data['nama'] . "' berhasil!";
    $final_member_data['poin_sebelum'] = $poin_sebelum;
    $final_member_data['poin_ditukar'] = (int)$reward_data['poin_tukar'];
    $final_member_data['poin_akhir'] = (int)$final_member_data['point'];
    $final_member_data['trx_member_id'] = $trx_member_id;
    $final_member_data['reward_kode'] = $reward_data['kode'];
    $final_member_data['reward_kode_menu'] = $reward_data['kode_menu'];
    $final_member_data['reward_harga'] = $reward_data['harga'];
    $final_member_data['reward_nama_menu'] = $reward_data['nama_menu'];
    $final_member_data['reward_nama'] = $reward_data['nama'];

    echo json_encode($final_member_data);

} else {

    // --- PROSES 2: AMBIL DATA MEMBER (FUNGSI LAMA) ---
    // (Tidak ada perubahan di blok ini)
    if (!isset($_POST['member_id']) || empty($_POST['member_id'])) {
        http_response_code(400);
        echo json_encode(['error' => 'ID Member tidak boleh kosong.']);
        exit();
    }
    $member_id = $_POST['member_id'];
    $stmt = $conn->prepare("SELECT * FROM member WHERE id = ?");
    if ($stmt === false) {
        http_response_code(500);
        echo json_encode(['error' => 'Gagal menyiapkan statement: ' . $conn->error]);
        exit();
    }
    $stmt->bind_param("i", $member_id);
    if (!$stmt->execute()) {
        http_response_code(500);
        echo json_encode(['error' => 'Eksekusi query gagal: ' . $stmt->error]);
        exit();
    }
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $member_data = $result->fetch_assoc();
        echo json_encode($member_data);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Member dengan ID ' . htmlspecialchars($member_id) . ' tidak ditemukan.']);
    }
    $stmt->close();
}

$conn->close();

?>