<?php
// delete_product.php - Process product deletion and clean up image files (Admin Only)
session_start();
require_once 'db.php';

// Access Control check
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.php");
    exit();
}

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

if ($id > 0) {
    try {
        // 1. Fetch product image path before deleting the record
        $stmt = $pdo->prepare("SELECT image FROM products WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $image_path = $stmt->fetchColumn();

        // 2. Delete product record from database
        $delete_stmt = $pdo->prepare("DELETE FROM products WHERE id = :id");
        $delete_stmt->execute([':id' => $id]);

        if ($delete_stmt->rowCount() > 0) {
            // 3. Delete physical image file from the server if it exists
            if ($image_path && strpos($image_path, 'images/') === 0) {
                $full_image_path = __DIR__ . '/' . $image_path;
                if (file_exists($full_image_path)) {
                    @unlink($full_image_path);
                }
            }
            header("Location: admin.php?tab=products&success_msg=" . urlencode("ลบสินค้าและรูปภาพเรียบร้อยแล้ว"));
            exit();
        } else {
            header("Location: admin.php?tab=products&error_msg=" . urlencode("ไม่พบสินค้าดังกล่าวหรือถูกลบไปแล้ว"));
            exit();
        }
    } catch (Exception $e) {
        header("Location: admin.php?tab=products&error_msg=" . urlencode("เกิดข้อผิดพลาด: " . $e->getMessage()));
        exit();
    }
} else {
    header("Location: admin.php?tab=products&error_msg=" . urlencode("รหัสสินค้าไม่ถูกต้อง"));
    exit();
}
?>
