<?php
// keranjang.php

header("Content-Type: application/json; charset=UTF-8");

require 'security.php';
require 'logger.php';
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on keranjang.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

// Mendapatkan token dari header Authorization
$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
    $authorizationHeader = $headers['Authorization'];
    $token = str_replace("Bearer ", "", $authorizationHeader);
} else {
    http_response_code(401);
    echo json_encode(['error' => 'Authorization header missing']);
    log_activity("Authorization header missing in keranjang.php");
    exit;
}

try {
    // Validasi token dan dapatkan user_id
    $stmt = $pdo->prepare("SELECT user_id FROM tokens WHERE token = ? AND expires_at >= NOW()");
    $stmt->execute([$token]);
    $tokenData = $stmt->fetch();

    if (!$tokenData) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        log_activity("Invalid or expired token in keranjang.php");
        exit;
    }

    $user_id = $tokenData['user_id'];

    // Mendapatkan body request
    $input_raw = file_get_contents('php://input');
    $input = json_decode($input_raw, true);
    $input = sanitize_input($input);

    if (empty($input['action'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Action is required']);
        exit;
    }

    $action = $input['action'];

    if ($action === 'lihat') {
        // Ambil daftar produk dalam keranjang user
        $stmt = $pdo->prepare("
            SELECT k.id, p.id AS produk_id, p.judul, p.harga, p.diskon, p.path_gambar, k.jumlah
            FROM keranjang k
            JOIN produk p ON k.produk_id = p.id
            WHERE k.user_id = ?
        ");
        $stmt->execute([$user_id]);
        $keranjang = $stmt->fetchAll();

        echo json_encode($keranjang);
        log_activity("User ID '$user_id' retrieved keranjang.");
        exit;
    
    } elseif ($action === 'tambah') {
        if (empty($input['produk_id']) || empty($input['jumlah']) || $input['jumlah'] <= 0) {
            http_response_code(400);
            echo json_encode(['error' => 'Produk ID and valid jumlah are required']);
            exit;
        }

        $produk_id = $input['produk_id'];
        $jumlah = $input['jumlah'];

        // Cek apakah produk sudah ada di keranjang
        $stmt = $pdo->prepare("SELECT id, jumlah FROM keranjang WHERE user_id = ? AND produk_id = ?");
        $stmt->execute([$user_id, $produk_id]);
        $existing = $stmt->fetch();

        if ($existing) {
            // Update jumlah jika sudah ada
            $new_jumlah = $existing['jumlah'] + $jumlah;
            $stmt = $pdo->prepare("UPDATE keranjang SET jumlah = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$new_jumlah, $existing['id']]);
        } else {
            // Tambahkan produk baru ke keranjang
            $stmt = $pdo->prepare("INSERT INTO keranjang (user_id, produk_id, jumlah) VALUES (?, ?, ?)");
            $stmt->execute([$user_id, $produk_id, $jumlah]);
        }

        echo json_encode(['message' => 'Produk added to keranjang']);
        log_activity("User ID '$user_id' added produk ID '$produk_id' to keranjang.");
        exit;

    } elseif ($action === 'hapus') {
        if (empty($input['keranjang_id'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Keranjang ID is required']);
            exit;
        }

        $keranjang_id = $input['keranjang_id'];

        // Hapus produk dari keranjang
        $stmt = $pdo->prepare("DELETE FROM keranjang WHERE id = ? AND user_id = ?");
        $stmt->execute([$keranjang_id, $user_id]);

        echo json_encode(['message' => 'Produk removed from keranjang']);
        log_activity("User ID '$user_id' removed produk ID '$keranjang_id' from keranjang.");
        exit;

    } elseif ($action === 'update') {
        if (empty($input['keranjang_id']) || empty($input['jumlah']) || $input['jumlah'] <= 0) {
            http_response_code(400);
            echo json_encode(['error' => 'Keranjang ID and valid jumlah are required']);
            exit;
        }

        $keranjang_id = $input['keranjang_id'];
        $jumlah = $input['jumlah'];

        // Update jumlah produk dalam keranjang
        $stmt = $pdo->prepare("UPDATE keranjang SET jumlah = ?, updated_at = NOW() WHERE id = ? AND user_id = ?");
        $stmt->execute([$jumlah, $keranjang_id, $user_id]);

        echo json_encode(['message' => 'Jumlah produk updated']);
        log_activity("User ID '$user_id' updated jumlah for keranjang ID '$keranjang_id'.");
        exit;
    
    } else {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
        exit;
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
    log_activity("keranjang.php error: " . $e->getMessage());
    exit;
}
?>
