<?php

session_start();

$path_to_root = "";
include $path_to_root . 'database.php';

$db = new database();

if (isset($_GET['action']) && $_GET['action']!="" && !empty($_SESSION['user_id'])) {
    $action = $_GET['action'];
} else {
    header("location:login.php");
}

if ($action == 'addtocart') {
    $id_barang = $_GET['id'];
    $id_user = $_SESSION['user_id'];
    $quantity = $_GET['quantity'];

    $sql = "SELECT * FROM keranjang WHERE id_barang=$id_barang AND id_user=$id_user";

    $result = $db->db_query($sql);
    $num_rows = $db->db_num_rows($result);

    if ($num_rows == 0) {
        $sql = "INSERT INTO `keranjang` (`id_user`, `id_barang`, `quantity`, `lama_sewa`) VALUES ('" . $id_user ."', '" . $id_barang . "', '" . $quantity . "', '1')";

        $result = $db->db_query($sql);

        if ($result) {
            header("location:index.php?result=success");
        } else {
            header("location:index.php?result=failure");
        }
    } else {
        header("location:index.php?result=already_available");
    }
}

?>