<?php
// post/material_location_action.php
require_once '../config/config.php';
if (!isset($_SESSION['user_id'])) { header('Location: ../index.php'); exit; }

 $action = $_POST['action'] ?? '';
 $current_lang = $_SESSION['lang'] ?? 'id';

// Pesan fallback
 $msg_success_add = ($current_lang == 'id') ? 'Lokasi berhasil ditambahkan' : 'Location added successfully';
 $msg_success_edit = ($current_lang == 'id') ? 'Lokasi berhasil diperbarui' : 'Location updated successfully';
 $msg_cannot_delete = ($current_lang == 'id') ? 'Tidak dapat menghapus: Lokasi memiliki stok' : 'Cannot delete: Location has stock';

try {
    if ($action === 'add') {
        $stmt = $pdo->prepare("INSERT INTO locations (code, name, building, floor, area, max_capacity, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$_POST['code'], $_POST['name'], $_POST['building'], $_POST['floor'], $_POST['area'], $_POST['max_capacity'], $_POST['status']]);
        
        $log = $pdo->prepare("INSERT INTO activity_log (user_id, action, description, icon) VALUES (?, ?, ?, ?)");
        $log->execute([$_SESSION['user_id'], 'Add Location', "Added location: ".$_POST['name'], 'mdi-map-marker']);
        
        $_SESSION['flash'] = ['type' => 'success', 'msg' => $msg_success_add];
    }
    elseif ($action === 'edit') {
        $stmt = $pdo->prepare("UPDATE locations SET code=?, name=?, building=?, floor=?, area=?, max_capacity=?, status=? WHERE id=?");
        $stmt->execute([$_POST['code'], $_POST['name'], $_POST['building'], $_POST['floor'], $_POST['area'], $_POST['max_capacity'], $_POST['status'], $_POST['id']]);
        
        $log = $pdo->prepare("INSERT INTO activity_log (user_id, action, description, icon) VALUES (?, ?, ?, ?)");
        $log->execute([$_SESSION['user_id'], 'Edit Location', "Updated location: ".$_POST['name'], 'mdi-pencil']);
        
        $_SESSION['flash'] = ['type' => 'success', 'msg' => $msg_success_edit];
    }
    elseif ($action === 'delete') {
        // Cek apakah ada spareparts di lokasi ini
        $check = $pdo->prepare("SELECT COUNT(*) FROM spareparts WHERE location_id = ?");
        $check->execute([$_POST['id']]);
        if ($check->fetchColumn() > 0) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => $msg_cannot_delete];
        } else {
            $stmt = $pdo->prepare("DELETE FROM locations WHERE id = ?");
            $stmt->execute([$_POST['id']]);
            
            $log = $pdo->prepare("INSERT INTO activity_log (user_id, action, description, icon) VALUES (?, ?, ?, ?)");
            $log->execute([$_SESSION['user_id'], 'Delete Location', "Deleted location ID: ".$_POST['id'], 'mdi-delete']);
            
            $_SESSION['flash'] = ['type' => 'success', 'msg' => 'Location deleted'];
        }
    }
} catch (PDOException $e) {
    $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Error: ' . $e->getMessage()];
}

header('Location: ../view/locations.php');
exit;