<?php
include('connection.php');

$con = getdb();

if (isset($_POST["addVendor"])) {
    $vendorName = trim($_POST['vendorName']); // Trim whitespace from the beginning and end

    // Check if the vendor name is not just spaces
    if (!empty($vendorName)) {
        // Check if the vendor already exists
        $checkQuery = "SELECT id FROM vendor WHERE VendorName = '$vendorName'";
        $checkResult = mysqli_query($con, $checkQuery);

        if (mysqli_num_rows($checkResult) > 0) {
            echo "<script type=\"text/javascript\">
                    alert(\"Vendor already exists.\");
                    window.location = \"manage_vendor.php\";
                  </script>";
        } else {
            // Insert the vendor if it doesn't exist
            $insertQuery = "INSERT INTO vendor (VendorName) VALUES ('$vendorName')";
            $insertResult = mysqli_query($con, $insertQuery);

            if ($insertResult) {
                echo "<script type=\"text/javascript\">
                        alert(\"Vendor added successfully.\");
                        window.location = \"manage_vendor.php\";
                      </script>";
            } else {
                echo "<script type=\"text/javascript\">
                        alert(\"Failed to add vendor.\");
                        window.location = \"manage_vendor.php\";
                      </script>";
            }
        }
    } else {
        echo "<script type=\"text/javascript\">
                alert(\"Vendor name cannot be empty \");
                window.location = \"manage_vendor.php\";
              </script>";
    }
}

if (isset($_POST["editVendor"])) {
    $vendorId = mysqli_real_escape_string($con, $_POST['editVendorId']);
    $vendorName = mysqli_real_escape_string($con, $_POST['editVendorName']);

    $updateQuery = "UPDATE vendor SET VendorName = '$vendorName' WHERE id = $vendorId";
    $updateResult = mysqli_query($con, $updateQuery);

    if ($updateResult) {
        echo "<script type=\"text/javascript\">
                alert(\"Vendor updated successfully.\");
                window.location = \"manage_vendor.php\";
              </script>";
    } else {
        echo "<script type=\"text/javascript\">
                alert(\"Failed to update vendor.\");
                window.location = \"manage_vendor.php\";
              </script>";
    }
}

// if (isset($_GET["deleteVendor"])) {
//     $vendorId = mysqli_real_escape_string($con, $_GET['deleteVendor']);

//     $deleteQuery = "DELETE FROM vendor WHERE id = $vendorId";
//     $deleteResult = mysqli_query($con, $deleteQuery);

//     if ($deleteResult) {
//         echo "<script type=\"text/javascript\">
//                 alert(\"Vendor deleted successfully.\");
//                 window.location = \"manage_vendor.php\";
//               </script>";
//     } else {
//         echo "<script type=\"text/javascript\">
//                 alert(\"Failed to delete vendor.\");
//                 window.location = \"manage_vendor.php\";
//               </script>";
//     }
//<a href="manage_vendor.php?deleteVendor=' . $row['id'] . '" onclick="return confirm(\'Are you sure you want to delete this vendor?\')">Delete</a>

// }

function getVendors() {
    $db = mysqli_connect("localhost", "shangrilaperfumes", "shangrilaperfumes", "shangrilaperfumes");

    if (!$db) {
        return array("Error: Unable to connect to the database");
    }

    $query = "SELECT id, VendorName FROM vendor";
    $result = mysqli_query($db, $query);

    if ($result) {
        $vendors = array();
        while ($row = mysqli_fetch_assoc($result)) {
            $vendors[$row['id']] = $row['VendorName'];
        }
        return $vendors;
    } else {
        return array("Error: Unable to fetch vendors");
    }

    mysqli_close($db);
}
function get_all_vendors()
{
    $con = getdb();
    $Sql = "SELECT * FROM `vendor` ORDER BY `VendorName` ASC";
    $result = mysqli_query($con, $Sql);
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            echo '<tr>
                    <td>' . $row['VendorName'] . '</td>
                    <td>
                        <a href="manage_vendor.php?editVendor=' . $row['id'] . '">Edit</a>  
                    </td>
                </tr>';
        }
    } else {
        echo "<tr><td colspan='2'>No vendors found.</td></tr>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Vendors</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
</head>

<body>

    <div class="container">
    <?php include('header.php'); ?>
        <form style="margin: 40px;     margin-left: 100px;     border: 1px solid;" class="form-horizontal" action="manage_vendor.php" method="post">
            <div class="form-group">
                <label class="col-md-4 control-label" for="vendorName">Vendor Name</label>
                <div class="col-md-4">
                    <input type="text" name="vendorName" id="vendorName" class="form-control" required>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-4 col-md-offset-4">
                <button type="submit" name="addVendor" class="btn btn-primary" style="width: 200px; display: block; margin: 0 auto; margin-top: -30px;">Add Vendor</button>

                </div>
            </div>
        </form>

        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Vendor Name</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
                get_all_vendors();
                ?>
            </tbody>
        </table>

        <?php
        if (isset($_GET["editVendor"])) {
            $vendorId = mysqli_real_escape_string($con, $_GET['editVendor']);
            $editQuery = "SELECT * FROM vendor WHERE id = $vendorId";
            $editResult = mysqli_query($con, $editQuery);

            if (mysqli_num_rows($editResult) > 0) {
                $row = mysqli_fetch_assoc($editResult);
                ?>
                <form class="form-horizontal" action="manage_vendor.php" method="post" style="margin-left: 395px;width: 50%;margin: bottom 50px;margin-bottom: 50px;">
                    <input type="hidden" name="editVendorId" value="<?php echo $row['id']; ?>">
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="editVendorName">Edit Vendor Name</label>
                        <div class="col-md-4">
                            <input type="text" name="editVendorName" id="editVendorName" class="form-control" value="<?php echo $row['VendorName']; ?>" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-4 col-md-offset-4" >
                            <button type="submit" name="editVendor" class="btn btn-success" style="    margin-top: -45px;    margin-left: 73px;">Update Vendor</button>
                        </div>
                    </div>
                </form>
        <?php
            } else {
                echo "Vendor not found.";
            }
        }
        ?>
    </div>
</body>
<style>
    /* Add this CSS to style the table */
.table {
    width: 50%;
    margin: auto;
    border-collapse: collapse;
    margin-bottom: 20px;
}

.table th, .table td {
    padding: 10px;
    border: 1px solid black;
    text-align: center;
}

.table th {
    background-color: #000;
    color: white;
}

.table tbody tr:nth-child(even) {
    background-color: #fff;
}

.table tbody tr:nth-child(odd) {
    background-color: #f2f2f2;
}

</style>

</html>