<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: /ayula-store/index.php");
    exit();
}

// Get user role
$userRole = $_SESSION['role'];
$username = $_SESSION['username'];
$displayName = ($username === 'root') ? 'Admin' : $username;

// Include database connection
include('../../routes/db_conn.php');

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $kode_barang = $_POST['kode_barang'];
    $nama_barang = $_POST['nama_barang'];
    $id_jenis = $_POST['id_jenis'];
    $stok = $_POST['stok'];
    $harga = $_POST['harga'];

    // Handle image upload if a new file is selected
    $gambar = $_POST['current_image']; // Default to current image

    if (isset($_FILES['product_image']) && $_FILES['product_image']['size'] > 0) {
        $target_dir = "../uploads/img-barang/";
        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0777, true);
        }

        // Use the original filename
        $filename = $_FILES["product_image"]["name"];
        $target_file = $target_dir . $filename;

        // Check if image file is actual image
        $check = getimagesize($_FILES["product_image"]["tmp_name"]);
        if ($check !== false) {
            // Delete old image if it exists
            if (!empty($gambar)) {
                $old_file = $target_dir . $gambar;
                if (file_exists($old_file)) {
                    unlink($old_file); // Delete the old image file
                }
            }

            // Upload file
            if (move_uploaded_file($_FILES["product_image"]["tmp_name"], $target_file)) {
                $gambar = $filename;
            }
        }
    }

    // Update query
    $sql = "UPDATE barang_kasir SET 
            nama_barang = ?,
            id_jenis = ?,
            stok = ?,
            harga = ?,
            gambar = ?
            WHERE kode_barang = ?";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("siiiss", $nama_barang, $id_jenis, $stok, $harga, $gambar, $kode_barang);

    if ($stmt->execute()) {
        header("Location: /ayula-store/views/barang-kasir/?edit_success=1");
        exit();
    } else {
        $error = "Failed to update product";
    }
}

// Get product ID from URL
$kode_barang = isset($_GET['id']) ? $_GET['id'] : 0;

// Fetch product details
$sql = "SELECT * FROM barang_kasir WHERE kode_barang = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $kode_barang);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $product = $result->fetch_assoc();
} else {
    header("Location: /ayula-store/views/barang-kasir/?error=Product not found");
    exit();
}

// Get all categories
$sql_categories = "SELECT * FROM jenis_barang ORDER BY nama_jenis";
$result_categories = $conn->query($sql_categories);
$categories = [];
if ($result_categories->num_rows > 0) {
    while ($row = $result_categories->fetch_assoc()) {
        $categories[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
    <meta name="description" content="POS - Bootstrap Admin Template">
    <meta name="keywords" content="admin, estimates, bootstrap, business, corporate, creative, invoice, html5, responsive, Projects">
    <meta name="author" content="Dreamguys - Bootstrap Admin Template">
    <meta name="robots" content="noindex, nofollow">
    <title>Ayula Store - Edit Produk Kasir</title>

    <link rel="shortcut icon" type="image/x-icon" href="../../src/img/smallest-ayula.png">
    <link rel="stylesheet" href="/ayula-store/bootstrap/assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="/ayula-store/bootstrap/assets/css/animate.css">
    <link rel="stylesheet" href="/ayula-store/bootstrap/assets/plugins/select2/css/select2.min.css">
    <link rel="stylesheet" href="/ayula-store/bootstrap/assets/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" href="/ayula-store/bootstrap/assets/plugins/fontawesome/css/fontawesome.min.css">
    <link rel="stylesheet" href="/ayula-store/bootstrap/assets/plugins/fontawesome/css/all.min.css">
    <link rel="stylesheet" href="/ayula-store/bootstrap/assets/css/style.css">

    <style>
        /* Custom styling for form inputs to ensure consistency */
        .form-control {
            border: 1px solid #e9ecef;
            height: 40px;
            padding: 10px;
            font-size: 15px;
            border-radius: 5px;
        }

        .select2-container--default .select2-selection--single {
            border: 1px solid #e9ecef;
            height: 40px;
            border-radius: 5px;
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 38px;
            padding-left: 12px;
            font-size: 15px;
        }

        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 38px;
        }

        .card-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 20px;
        }

        .form-group label {
            font-weight: 500;
            margin-bottom: 8px;
            display: block;
        }

        /* Disabled field styling to match enabled fields */
        input[disabled] {
            background-color: #f9f9f9;
            cursor: not-allowed;
            opacity: 0.7;
        }
    </style>
</head>

<body>
    <div id="global-loader">
        <div class="whirly-loader"></div>
    </div>

    <div class="main-wrapper">
    <div class="header">
      <div class="header-left active">
        <a href="/ayula-store/views/dashboard/" class="logo">
          <img src="../../src/img/logoayula.png" alt="" />
        </a>
        <a href="/ayula-store/views/dashboard/" class="logo-small">
          <img src="../../src/img/smallest-ayula.png" alt="" />
        </a>
        <a id="toggle_btn" href="javascript:void(0);"> </a>
      </div>

      <a id="mobile_btn" class="mobile_btn" href="#sidebar">
        <span class="bar-icon">
          <span></span>
          <span></span>
          <span></span>
        </span>
      </a>

      <ul class="nav user-menu">
        <li class="nav-item dropdown has-arrow main-drop">
          <a href="javascript:void(0);" class="dropdown-toggle nav-link userset" data-bs-toggle="dropdown">
            <span class="user-img"><img src="../../src/img/userprofile.png" alt="">
              <span class="status online"></span></span>
          </a>
          <div class="dropdown-menu menu-drop-user">
            <div class="profilename">
              <div class="profileset">
                <span class="user-img"><img src="../../src/img/userprofile.png" alt="">
                  <span class="status online"></span></span>
                <div class="profilesets">
                  <h6><?php echo $userRole == 'admin' ? 'Admin' : 'Karyawan'; ?></h6>
                  <h5><?php echo htmlspecialchars($displayName); ?></h5>
                </div>
              </div>
              <hr class="m-0" />
              <a class="dropdown-item" href="/ayula-store/views/report-issue/">
                <img src="../../src/img/warning.png" class="me-2" alt="img" /> Laporkan Masalah
              </a>
              <hr class="m-0" />
              <a class="dropdown-item logout pb-0" href="../../views/logout.php"><img
                  src="../../bootstrap/assets/img/icons/log-out.svg" class="me-2" alt="img" />Keluar</a>
            </div>
          </div>
        </li>
      </ul>

      <div class="dropdown mobile-user-menu">
        <a href="javascript:void(0);" class="nav-link dropdown-toggle" data-bs-toggle="dropdown"
          aria-expanded="false"><i class="fa fa-ellipsis-v"></i></a>
        <div class="dropdown-menu dropdown-menu-right">
          <a class="dropdown-item" href="/ayula-store/views/report-issue/">
            <i class="fa fa-cog me-2"></i> Laporkan Masalah
          </a>
          <hr class="m-0" />
          <a class="dropdown-item logout pb-0" href="../../views/logout.php"><img
              src="../../bootstrap/assets/img/icons/log-out.svg" class="me-2" alt="img" />Keluar</a>
        </div>
      </div>
    </div>

    <div class="sidebar" id="sidebar">
      <div class="sidebar-inner slimscroll">
        <div id="sidebar-menu" class="sidebar-menu">
          <ul>
            <li>
              <a href="/ayula-store/views/dashboard/"><img
                  src="../../bootstrap/assets/img/icons/dashboard.svg" alt="img" /><span>
                  Dashboard</span>
              </a>
            </li>
            <li>
              <a href="/ayula-store/views/transaction/"><img src="../../bootstrap/assets/img/icons/sales1.svg"
                  alt="img" /><span>
                  POS</span></a>
            </li>
            <li class="submenu">
              <a href="javascript:void(0);"><img src="../../bootstrap/assets/img/icons/product.svg" alt="img" /><span>
                  Produk</span>
                <span class="menu-arrow"></span></a>
              <ul>
                <li><a href="/ayula-store/views/barang-kasir/" class="active">Daftar Produk Kasir</a></li>
              </ul>
            </li>

            <li class="submenu">
              <a href="javascript:void(0);"><img src="../../bootstrap/assets/img/icons/time.svg" alt="img" /><span>
                  Laporan</span>
                <span class="menu-arrow"></span></a>
              <ul>
                <li><a href="/ayula-store/views/report/sales-report/">Laporan Penjualan</a></li>
                <?php if ($userRole == 'admin') { ?>
                  <li><a href="/ayula-store/views/report/popular-products/">Produk Terlaris</a></li>
                <?php } ?>
              </ul>
            </li>
            <li class="submenu">
              <a href="javascript:void(0);"><img src="../../bootstrap/assets/img/icons/users1.svg" alt="img" /><span>
                  Pengguna</span>
                <span class="menu-arrow"></span></a>
              <ul>
                <?php if ($userRole == 'admin') { ?>
                  <li><a href="/ayula-store/views/users/add-user.php">Pengguna Baru</a></li>
                <?php } ?>
                <li><a href="/ayula-store/views/users/">Daftar Pengguna</a></li>
              </ul>
            </li>
          </ul>
        </div>
      </div>
    </div>

        <div class="page-wrapper">
            <div class="content">
                <div class="page-header">
                    <div class="page-title">
                        <h4>Edit Produk Kasir</h4>
                        <h6>Update produk kasir Anda</h6>
                    </div>
                </div>

                <div class="card">
                    <div class="card-body">
                        <?php if (isset($error)): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <?php echo $error; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        <?php endif; ?>

                        <form action="editproducts.php" method="POST" enctype="multipart/form-data">
                            <input type="hidden" name="kode_barang" value="<?php echo $product['kode_barang']; ?>">
                            <input type="hidden" name="current_image" value="<?php echo $product['gambar']; ?>">

                            <div class="row">
                                <div class="col-lg-3 col-sm-6 col-12">
                                    <div class="form-group">
                                        <label>Kode Barang</label>
                                        <div class="input-groupicon">
                                            <input type="text" class="form-control" value="<?php echo $product['kode_barang']; ?>" disabled>
                                            <div class="addonset">
                                                <img src="/ayula-store/bootstrap/assets/img/icons/scanners.svg" alt="img">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-3 col-sm-6 col-12">
                                    <div class="form-group">
                                        <label>Nama Barang</label>
                                        <div class="input-groupicon">
                                            <input type="text" class="form-control" name="nama_barang" value="<?php echo $product['nama_barang']; ?>" required>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-3 col-sm-6 col-12">
                                    <div class="form-group">
                                        <label>Jenis Barang</label>
                                        <select class="select form-control" name="id_jenis" required>
                                            <option value="">Pilih Jenis</option>
                                            <?php foreach ($categories as $category): ?>
                                                <option value="<?php echo $category['id_jenis']; ?>"
                                                    <?php if ($category['id_jenis'] == $product['id_jenis']) echo 'selected'; ?>>
                                                    <?php echo $category['nama_jenis']; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-lg-3 col-sm-6 col-12">
                                    <div class="form-group">
                                        <label>Stok</label>
                                        <div class="input-groupicon">
                                            <input type="number" class="form-control" name="stok" value="<?php echo $product['stok']; ?>" required>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-3 col-sm-6 col-12">
                                    <div class="form-group">
                                        <label>Harga</label>
                                        <div class="input-groupicon">
                                            <input type="number" class="form-control" name="harga" value="<?php echo $product['harga']; ?>" required>
                                            <div class="addonset">
                                                <img src="/ayula-store/bootstrap/assets/img/icons/dollar.svg" alt="img">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-12">
                                    <div class="form-group">
                                        <label>Gambar Produk</label>
                                        <div class="image-upload">
                                            <input type="file" name="product_image" accept="image/*">
                                            <div class="image-uploads">
                                                <img src="/ayula-store/bootstrap/assets/img/icons/upload.svg" alt="img">
                                                <h4>Drag and drop file untuk upload</h4>
                                                <p>Atau klik untuk browse</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <?php if (!empty($product['gambar'])): ?>
                                    <div class="col-12">
                                        <div class="form-group">
                                            <label>Gambar Saat Ini</label>
                                            <div class="product-list">
                                                <ul class="row">
                                                    <li class="col-lg-3 col-sm-6">
                                                        <div class="productviews">
                                                            <div class="productviewsimg">
                                                                <img src="../../uploads/products/<?php echo $product['gambar']; ?>" alt="img">
                                                            </div>
                                                            <div class="productviewscontent">
                                                                <div class="productviewsname">
                                                                    <h2><?php echo $product['gambar']; ?></h2>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <div class="col-lg-12 mt-3">
                                    <button type="submit" class="btn btn-submit me-2">Update</button>
                                    <a href="/ayula-store/views/barang-kasir/" class="btn btn-cancel">Batal</a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="/ayula-store/bootstrap/assets/js/jquery-3.6.0.min.js"></script>
    <script src="/ayula-store/bootstrap/assets/js/feather.min.js"></script>
    <script src="/ayula-store/bootstrap/assets/js/jquery.slimscroll.min.js"></script>
    <script src="/ayula-store/bootstrap/assets/js/jquery.dataTables.min.js"></script>
    <script src="/ayula-store/bootstrap/assets/js/dataTables.bootstrap4.min.js"></script>
    <script src="/ayula-store/bootstrap/assets/js/bootstrap.bundle.min.js"></script>
    <script src="/ayula-store/bootstrap/assets/plugins/select2/js/select2.min.js"></script>
    <script src="/ayula-store/bootstrap/assets/plugins/sweetalert/sweetalert2.all.min.js"></script>
    <script src="/ayula-store/bootstrap/assets/plugins/sweetalert/sweetalerts.min.js"></script>
    <script src="/ayula-store/bootstrap/assets/js/script.js"></script>

    <script>
        $(document).ready(function() {
            // Initialize select2
            $('.select').select2({
                minimumResultsForSearch: -1,
                width: '100%'
            });

            // Initialize currency format for price field if needed
            // You could add a currency formatter here if required
        });
    </script>
</body>

</html>