<?php
session_start();
include_once "../config/database.php";

if(!isset($_SESSION['user_id'])){
    header("Location: /beauty_pos/login.php");
    exit;
}

if(!isset($_GET['id']) || !is_numeric($_GET['id'])){
    header("Location: /beauty_pos/brands/index.php");
    exit;
}

$id = (int)$_GET['id'];

$get = mysqli_query($conn,"
SELECT *
FROM brands
WHERE id='$id'
");

if(mysqli_num_rows($get)==0){
    header("Location: /beauty_pos/brands/index.php");
    exit;
}

$brand = mysqli_fetch_assoc($get);

$error="";

if(isset($_POST['update'])){

    $brand_name = trim(mysqli_real_escape_string($conn,$_POST['brand_name']));

    if($brand_name==""){

        $error="Brand name is required.";

    }else{

        $check=mysqli_query($conn,"
        SELECT id
        FROM brands
        WHERE brand_name='$brand_name'
        AND id!='$id'
        ");

        if(mysqli_num_rows($check)>0){

            $error="Brand already exists.";

        }else{

            $update=mysqli_query($conn,"
            UPDATE brands
            SET brand_name='$brand_name'
            WHERE id='$id'
            ");

            if($update){

                header("Location: /beauty_pos/brands/index.php?success=updated");
                exit;

            }else{

                $error="Update failed.";

            }

        }

    }

}

include_once "../includes/header.php";
include_once "../includes/sidebar.php";
?>

<div class="overlay" id="overlay"></div>

<div class="main-content">

<?php include_once "../includes/topbar.php"; ?>

<div class="container-fluid">

<div class="card-box rounded-4 shadow p-4">

<div class="d-flex justify-content-between align-items-center mb-4">

<h4>Edit Brand</h4>

<a href="/beauty_pos/brands/index.php" class="btn btn-secondary">
Back
</a>

</div>

<?php if($error!=""){ ?>

<div class="alert alert-danger">

<?php echo $error; ?>

</div>

<?php } ?>

<form method="POST">

<div class="row g-3">

<div class="col-md-12">

<label class="form-label">

Brand Name

</label>

<input
type="text"
name="brand_name"
class="form-control"
required
value="<?php echo htmlspecialchars($brand['brand_name']); ?>"
>

</div>

<div class="col-md-12">

<button
type="submit"
name="update"
class="btn btn-success">

Update Brand

</button>

</div>

</div>

</form>

</div>

</div>

<?php include_once "../includes/footer.php"; ?>

</div>