<?php
// post/spareparts_action.php
require_once '../config/config.php';
// TAMBAHKAN INI: Include ImageHasher untuk fitur scan gambar
require_once '../assets/php/ImageHasher.php'; 

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

 $action = $_POST['action'] ?? '';
 $uploadDir = '../assets/img/product/';

// --- FUNGSI UPLOAD DENGAN HASH ---
function uploadImages($files, $sparepart_id, $pdo, $dir) {
    $allowed = ['jpg', 'jpeg', 'png', 'gif'];
    foreach ($files['name'] as $key => $name) {
        if ($files['error'][$key] === 0) {
            $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
            if (in_array($ext, $allowed)) {
                $newName = uniqid() . '_' . time() . '.' . $ext;
                $tmpName = $files['tmp_name'][$key];
                $targetPath = $dir . $newName;
                
                if (move_uploaded_file($tmpName, $targetPath)) {
                    // GENERATE IMAGE HASH
                    // Hash ini akan digunakan untuk membandingkan kemiripan gambar
                    $hash = ImageHasher::generateHash($targetPath);
                    
                    // Insert ke DB termasuk hash
                    $stmt = $pdo->prepare("INSERT INTO sparepart_images (sparepart_id, image_path, image_hash) VALUES (?, ?, ?)");
                    $stmt->execute([$sparepart_id, $newName, $hash]);
                }
            }
        }
    }
}

// --- FUNGSI HAPUS GAMBAR LAMA ---
function deleteOldImages($sparepart_id, $pdo, $dir) {
    // 1. Ambil semua nama file dari database
    $stmt = $pdo->prepare("SELECT image_path FROM sparepart_images WHERE sparepart_id = ?");
    $stmt->execute([$sparepart_id]);
    $images = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // 2. Hapus file fisik dari folder
    foreach ($images as $file) {
        $filePath = $dir . $file;
        if (file_exists($filePath)) {
            unlink($filePath); // Hapus file
        }
    }
    
    // 3. Hapus record dari database
    $del = $pdo->prepare("DELETE FROM sparepart_images WHERE sparepart_id = ?");
    $del->execute([$sparepart_id]);
}

try {
    if ($action === 'add') {
        $stmt = $pdo->prepare("INSERT INTO spareparts (part_number, name, category_id, location_id, material_group_id, stock, min_stock, unit, price, status, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $_POST['part_number'], 
            $_POST['name'], 
            $_POST['category_id'] ?: NULL, 
            $_POST['location_id'] ?: NULL, 
            $_POST['material_group_id'] ?: NULL,
            $_POST['stock'], 
            $_POST['min_stock'], 
            $_POST['unit'], 
            $_POST['price'], 
            $_POST['status'], 
            $_POST['description'] ?? ''
        ]);
        $lastId = $pdo->lastInsertId();

        // Upload gambar baru (dengan generate hash)
        if(!empty($_FILES['images']['name'][0])) {
            uploadImages($_FILES['images'], $lastId, $pdo, $uploadDir);
        }
        
        $_SESSION['flash'] = ['type' => 'success', 'msg' => 'Sparepart added'];
    }
    elseif ($action === 'edit') {
        $stmt = $pdo->prepare("UPDATE spareparts SET part_number=?, name=?, category_id=?, location_id=?, material_group_id=?, stock=?, min_stock=?, unit=?, price=?, status=?, description=? WHERE id=?");
        $stmt->execute([
            $_POST['part_number'], 
            $_POST['name'], 
            $_POST['category_id'] ?: NULL, 
            $_POST['location_id'] ?: NULL, 
            $_POST['material_group_id'] ?: NULL,
            $_POST['stock'], 
            $_POST['min_stock'], 
            $_POST['unit'], 
            $_POST['price'], 
            $_POST['status'], 
            $_POST['description'] ?? '',
            $_POST['id']
        ]);

        // LOGIKA UPDATE GAMBAR:
        // Cek apakah user mengunggah file baru
        if(!empty($_FILES['images']['name'][0])) {
            // 1. Hapus gambar lama (file & db)
            deleteOldImages($_POST['id'], $pdo, $uploadDir);
            
            // 2. Upload gambar baru (dengan generate hash baru)
            uploadImages($_FILES['images'], $_POST['id'], $pdo, $uploadDir);
        }
        
        $_SESSION['flash'] = ['type' => 'success', 'msg' => 'Sparepart updated'];
    }
    elseif ($action === 'delete') {
        $id = $_POST['id'];
        
        // Hapus gambar terkait
        deleteOldImages($id, $pdo, $uploadDir);
        
        // Hapus data spareparts
        $stmt = $pdo->prepare("DELETE FROM spareparts WHERE id = ?");
        $stmt->execute([$id]);
        
        $_SESSION['flash'] = ['type' => 'success', 'msg' => 'Sparepart deleted'];
    }
} catch (PDOException $e) {
    $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Error: ' . $e->getMessage()];
}

header('Location: ../view/spareparts.php');
exit;
?>