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

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

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if($id == 0){
    header("Location: /beauty_pos/products/index.php");
    exit;
}

/* ---------------- FETCH PRODUCT ---------------- */
$get = mysqli_query($conn, "SELECT * FROM products WHERE id='$id'");
$product = mysqli_fetch_assoc($get);

if(!$product){
    header("Location: /beauty_pos/products/index.php");
    exit;
}

/* ---------------- DELETE IMAGE IF EXISTS ---------------- */
if(!empty($product['image'])){
    $imagePath = "../uploads/".$product['image'];
    if(file_exists($imagePath)){
        unlink($imagePath);
    }
}

/* ---------------- DELETE PRODUCT ---------------- */
$delete = mysqli_query($conn, "DELETE FROM products WHERE id='$id'");

if($delete){
    header("Location: /beauty_pos/products/index.php?msg=deleted");
    exit;
} else {
    header("Location: /beauty_pos/products/index.php?msg=error");
    exit;
}