<?php
session_start();

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

include_once "../config/database.php";

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

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

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

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

$data=mysqli_fetch_assoc($get);

$message="";
$type="";

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

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

    if($category==""){

        $message="Category Name is required.";
        $type="danger";

    }else{

        $check=mysqli_query($conn,"
        SELECT id
        FROM categories
        WHERE category_name='$category'
        AND id<>'$id'
        ");

        if(mysqli_num_rows($check)>0){

            $message="Category already exists.";
            $type="warning";

        }else{

            $update=mysqli_query($conn,"
            UPDATE categories
            SET category_name='$category'
            WHERE id='$id'
            ");

            if($update){

                header("Location:index.php?updated=1");
                exit();

            }else{

                $message="Unable to update category.";
                $type="danger";

            }

        }

    }

}

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="d-flex justify-content-between align-items-center mb-4">

<div>

<h3 class="fw-bold mb-1">

Edit Category

</h3>

<p class="text-muted mb-0">

Update Product Category

</p>

</div>

<a href="index.php" class="btn btn-secondary">

<i class="fa fa-arrow-left me-2"></i>

Back

</a>

</div>

<div class="row justify-content-center">

<div class="col-lg-7 col-md-10 col-12">

<div class="card shadow border-0 rounded-4">

<div class="card-body p-4">

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

<div class="alert alert-<?=$type?>">

<?=$message?>

</div>

<?php } ?>

<form method="POST">

<div class="mb-3">

<label class="form-label fw-semibold">

Category Name

</label>

<input
type="text"
name="category_name"
class="form-control"
maxlength="100"
required
value="<?=htmlspecialchars($data['category_name'])?>">

</div>

<div class="d-flex gap-2">

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

<i class="fa fa-save me-2"></i>

Update Category

</button>

<a
href="index.php"
class="btn btn-outline-secondary">

Cancel

</a>

</div>

</form>

</div>

</div>

</div>

</div>

</div>

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

</div>