<?php
// Database connection configuration
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'assets_management_system';

// Set timezone untuk Indonesia
date_default_timezone_set('Asia/Jakarta');

try {
    $pdo = new PDO("mysql:host=$host;dbname=$database;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    
    // Set MySQL timezone to Asia/Jakarta
    $pdo->exec("SET time_zone = '+07:00'");
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Session configuration
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Helper functions
function redirect($url) {
    header("Location: $url");
    exit();
}

function isLoggedIn() {
    return isset($_SESSION['user_id']) && isset($_SESSION['user_type']);
}

function requireLogin() {
    if (!isLoggedIn()) {
        redirect('login.php');
    }
}

function checkUserType($allowed_types) {
    if (!isLoggedIn()) {
        redirect('login.php');
    }
    
    if (!in_array($_SESSION['user_type'], $allowed_types)) {
        redirect('index.php');
    }
}

function sanitize($data) {
    return htmlspecialchars(strip_tags(trim($data)));
}

// Helper function untuk convert image to base64
function imageToBase64($imageData) {
    return base64_encode($imageData);
}

// Helper function untuk convert base64 to image
function base64ToImage($base64Data) {
    return base64_decode($base64Data);
}

// Helper function untuk validasi asset availability
function isAssetAvailableForBorrow($pdo, $asset_id) {
    $stmt = $pdo->prepare("
        SELECT status_borrower, kondisi 
        FROM assets 
        WHERE id = ?
    ");
    $stmt->execute([$asset_id]);
    $asset = $stmt->fetch();
    
    if (!$asset) {
        return false;
    }
    
    // Asset bisa dipinjam jika:
    // - status_borrower = 'available' DAN kondisi = 'baik' ATAU 'rusak'
    // - Tidak bisa dipinjam jika kondisi = 'hilang' atau status_borrower != 'available'
    return ($asset['status_borrower'] === 'available' && 
            ($asset['kondisi'] === 'baik' || $asset['kondisi'] === 'rusak'));
}

// Helper function untuk clear borrow cart
function clearBorrowCart($pdo, $borrower_id, $session_id = null) {
    if ($session_id) {
        $stmt = $pdo->prepare("DELETE FROM borrow_cart WHERE borrower_employee_id = ? AND session_id = ?");
        $stmt->execute([$borrower_id, $session_id]);
    } else {
        $stmt = $pdo->prepare("DELETE FROM borrow_cart WHERE borrower_employee_id = ?");
        $stmt->execute([$borrower_id]);
    }
}

// Helper function untuk get borrower organization
function getBorrowerOrganization($pdo, $borrower_id) {
    $stmt = $pdo->prepare("SELECT organization FROM borrowers WHERE employee_id = ?");
    $stmt->execute([$borrower_id]);
    $result = $stmt->fetch();
    return $result ? $result['organization'] : '';
}
?>