<?php
// Database Configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'inventory_acf');

// Create connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Set charset to UTF-8
$conn->set_charset("utf8mb4");

// Timezone
date_default_timezone_set('Asia/Jakarta');

// Function untuk logging aktivitas
if (!function_exists('logActivity')) {
    function logActivity($user_id, $aktivitas, $tabel = null, $record_id = null, $detail = null) {
        global $conn;
        
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
        
        $sql = "INSERT INTO log_aktivitas (user_id, aktivitas, tabel, record_id, detail, ip_address) 
                VALUES (?, ?, ?, ?, ?, ?)";
        
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $stmt->bind_param('ississ', $user_id, $aktivitas, $tabel, $record_id, $detail, $ip_address);
            $stmt->execute();
            $stmt->close();
        }
    }
}

// Function untuk format rupiah
if (!function_exists('formatRupiah')) {
    function formatRupiah($angka) {
        return 'Rp ' . number_format($angka, 0, ',', '.');
    }
}

// Function untuk format tanggal Indonesia
if (!function_exists('formatTanggalIndo')) {
    function formatTanggalIndo($tanggal) {
        if (!$tanggal || $tanggal == '0000-00-00') return '-';
        
        $bulan = array(
            1 => 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
            'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
        );
        
        $pecahkan = explode('-', $tanggal);
        return $pecahkan[2] . ' ' . $bulan[(int)$pecahkan[1]] . ' ' . $pecahkan[0];
    }
}

// PERBAIKAN: Function untuk cek akses role dengan normalisasi
if (!function_exists('checkRole_old')) {
    function checkRole_old($allowed_roles = []) {
        if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
            header("Location: ../index.html?error=session");
            exit;
        }
        
        // PERBAIKAN: Ambil role dengan fallback dan normalisasi
        $userRole = strtoupper(trim($_SESSION['role'] ?? $_SESSION['user_type'] ?? ''));
        
        if (empty($userRole)) {
            header("Location: ../index.html?error=no_role");
            exit;
        }
        
        // PERBAIKAN: Normalisasi allowed_roles juga
        $normalizedAllowedRoles = array_map('strtoupper', array_map('trim', $allowed_roles));
        
        // Map role variations to single letter
        $roleMap = [
            'ADMIN' => 'A',
            'ADMINISTRATOR' => 'A',
            'MANAGER' => 'M',
            'STAFF' => 'S',
            'A' => 'A',
            'M' => 'M',
            'S' => 'S'
        ];
        
        // Normalize user role
        $userRole = $roleMap[$userRole] ?? $userRole;
        
        // Normalize allowed roles
        $normalizedAllowedRoles = array_map(function($role) use ($roleMap) {
            return $roleMap[$role] ?? $role;
        }, $normalizedAllowedRoles);
        
        // Check if role is allowed
        if (!empty($normalizedAllowedRoles) && !in_array($userRole, $normalizedAllowedRoles, true)) {
            // Log unauthorized access attempt
            if (function_exists('logActivity') && isset($_SESSION['user_id'])) {
                logActivity(
                    $_SESSION['user_id'], 
                    'Akses ditolak - Role: ' . $userRole . ' - Required: ' . implode(',', $normalizedAllowedRoles),
                    'access_denied',
                    null,
                    $_SERVER['REQUEST_URI'] ?? 'Unknown'
                );
            }
            
            http_response_code(403);
            die("
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset='UTF-8'>
                <title>Akses Ditolak</title>
                <style>
                    body {
                        font-family: 'Segoe UI', Tahoma, sans-serif;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        min-height: 100vh;
                        margin: 0;
                        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    }
                    .error-box {
                        background: white;
                        padding: 40px;
                        border-radius: 12px;
                        box-shadow: 0 10px 40px rgba(0,0,0,0.2);
                        text-align: center;
                        max-width: 500px;
                    }
                    .error-icon {
                        font-size: 64px;
                        margin-bottom: 20px;
                    }
                    h1 {
                        color: #dc2626;
                        margin-bottom: 10px;
                        font-size: 24px;
                    }
                    p {
                        color: #64748b;
                        margin-bottom: 20px;
                        line-height: 1.6;
                    }
                    .role-info {
                        background: #f8fafc;
                        padding: 15px;
                        border-radius: 8px;
                        margin: 20px 0;
                        font-size: 14px;
                    }
                    .btn {
                        display: inline-block;
                        padding: 12px 30px;
                        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                        color: white;
                        text-decoration: none;
                        border-radius: 8px;
                        font-weight: 600;
                        transition: transform 0.2s;
                    }
                    .btn:hover {
                        transform: translateY(-2px);
                    }
                </style>
            </head>
            <body>
                <div class='error-box'>
                    <div class='error-icon'>🚫</div>
                    <h1>Akses Ditolak</h1>
                    <p>Maaf, Anda tidak memiliki izin untuk mengakses halaman ini.</p>
                    <div class='role-info'>
                        <strong>Role Anda:</strong> " . htmlspecialchars($userRole) . "<br>
                        <strong>Role yang Dibutuhkan:</strong> " . htmlspecialchars(implode(', ', $normalizedAllowedRoles)) . "
                    </div>
                    <a href='../dashboard.php' class='btn'>Kembali ke Dashboard</a>
                </div>
            </body>
            </html>
            ");
        }
        
        return true;
    }
}

// Function untuk sanitize input
if (!function_exists('sanitize')) {
    function sanitize($data) {
        global $conn;
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $conn->real_escape_string($data);
    }
}

// Function untuk generate kode inventory
if (!function_exists('generateKodeInventory')) {
    function generateKodeInventory($kategori_id) {
        global $conn;
        
        // Get kategori code with prepared statement
        $stmt = $conn->prepare("SELECT kode FROM kategori WHERE id = ?");
        $stmt->bind_param('i', $kategori_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $kategori = $result->fetch_assoc();
        $stmt->close();
        
        $kode_kategori = $kategori['kode'] ?? 'INV';
        
        // Get last number with prepared statement
        $last = $conn->query("SELECT MAX(no_urut) as last_no FROM inventory")->fetch_assoc();
        $no_urut = ($last['last_no'] ?? 0) + 1;
        
        return $kode_kategori . '-' . date('Y') . '-' . str_pad($no_urut, 4, '0', STR_PAD_LEFT);
    }
}

// TAMBAHAN: Function untuk get user role (helper)
if (!function_exists('getUserRole')) {
    function getUserRole() {
        if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
            return null;
        }
        
        $userRole = strtoupper(trim($_SESSION['role'] ?? $_SESSION['user_type'] ?? ''));
        
        // Map variations
        $roleMap = [
            'ADMIN' => 'A',
            'ADMINISTRATOR' => 'A',
            'MANAGER' => 'M',
            'STAFF' => 'S',
            'A' => 'A',
            'M' => 'M',
            'S' => 'S'
        ];
        
        return $roleMap[$userRole] ?? null;
    }
}

// TAMBAHAN: Function untuk check if user is admin
if (!function_exists('isAdmin')) {
    function isAdmin() {
        return getUserRole() === 'A';
    }
}

// TAMBAHAN: Function untuk check if user is manager
if (!function_exists('isManager')) {
    function isManager() {
        return getUserRole() === 'M';
    }
}

// TAMBAHAN: Function untuk check if user is staff
if (!function_exists('isStaff')) {
    function isStaff() {
        return getUserRole() === 'S';
    }
}
?>