<?php
/**
 * Enterprise HRM ERP System - Data Locking Functions
 * Prevents editing of finalized data
 */

if (!defined('HRM_ACCESS')) {
    die('Direct access not allowed');
}

/**
 * Check if data is locked
 */
function isDataLocked($lockType, $siteId, $month = null, $year = null, $referenceId = null) {
    try {
        $db = getDB();
        
        $where = "lock_type = ? AND site_id = ? AND is_locked = 1";
        $params = [$lockType, $siteId];
        
        if ($month !== null) {
            $where .= " AND month = ?";
            $params[] = $month;
        }
        
        if ($year !== null) {
            $where .= " AND year = ?";
            $params[] = $year;
        }
        
        if ($referenceId !== null) {
            $where .= " AND lock_reference_id = ?";
            $params[] = $referenceId;
        }
        
        $stmt = $db->prepare("SELECT lock_id, locked_at, locked_by, lock_reason FROM data_locks WHERE {$where} LIMIT 1");
        $stmt->execute($params);
        $lock = $stmt->fetch();
        
        return $lock ? $lock : false;
    } catch (Exception $e) {
        error_log("Error checking data lock: " . $e->getMessage());
        return false;
    }
}

/**
 * Lock data
 */
function lockData($lockType, $siteId, $month, $year, $referenceId = null, $lockReason = null) {
    try {
        $db = getDB();
        $db->beginTransaction();
        
        // Check if already locked
        $existingLock = isDataLocked($lockType, $siteId, $month, $year, $referenceId);
        if ($existingLock) {
            $db->rollBack();
            return ['success' => false, 'message' => 'Data is already locked.'];
        }
        
        $stmt = $db->prepare("
            INSERT INTO data_locks (
                site_id, lock_type, lock_reference_id, month, year, 
                lock_date, is_locked, locked_by, lock_reason
            ) VALUES (?, ?, ?, ?, ?, CURDATE(), 1, ?, ?)
        ");
        
        $userId = getCurrentUserId();
        if (!$userId) {
            $db->rollBack();
            return ['success' => false, 'message' => 'User not logged in.'];
        }
        
        $stmt->execute([
            $siteId,
            $lockType,
            $referenceId,
            $month,
            $year,
            $userId,
            $lockReason
        ]);
        
        $db->commit();
        
        // Log audit
        logAudit('LOCK', 'data_locks', $db->lastInsertId());
        
        return ['success' => true, 'message' => 'Data locked successfully.'];
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        error_log("Error locking data: " . $e->getMessage());
        return ['success' => false, 'message' => 'Error locking data. Please try again.'];
    }
}

/**
 * Unlock data (only for admins)
 */
function unlockData($lockType, $siteId, $month, $year, $referenceId = null) {
    if (!hasAdminAccess()) {
        return ['success' => false, 'message' => 'Only administrators can unlock data.'];
    }
    
    try {
        $db = getDB();
        
        $where = "lock_type = ? AND site_id = ? AND is_locked = 1";
        $params = [$lockType, $siteId];
        
        if ($month !== null) {
            $where .= " AND month = ?";
            $params[] = $month;
        }
        
        if ($year !== null) {
            $where .= " AND year = ?";
            $params[] = $year;
        }
        
        if ($referenceId !== null) {
            $where .= " AND lock_reference_id = ?";
            $params[] = $referenceId;
        }
        
        $stmt = $db->prepare("UPDATE data_locks SET is_locked = 0 WHERE {$where}");
        $stmt->execute($params);
        
        if ($stmt->rowCount() > 0) {
            logAudit('UNLOCK', 'data_locks', null);
            return ['success' => true, 'message' => 'Data unlocked successfully.'];
        } else {
            return ['success' => false, 'message' => 'No locked data found to unlock.'];
        }
    } catch (Exception $e) {
        error_log("Error unlocking data: " . $e->getMessage());
        return ['success' => false, 'message' => 'Error unlocking data. Please try again.'];
    }
}

/**
 * Require data to be unlocked (redirects if locked)
 */
function requireUnlocked($lockType, $siteId, $month = null, $year = null, $referenceId = null) {
    $lock = isDataLocked($lockType, $siteId, $month, $year, $referenceId);
    if ($lock) {
        $lockInfo = "Locked by user ID {$lock['locked_by']} on " . formatDateTime($lock['locked_at']);
        if ($lock['lock_reason']) {
            $lockInfo .= ". Reason: " . htmlspecialchars($lock['lock_reason']);
        }
        $_SESSION['error'] = "This data is locked and cannot be modified. {$lockInfo}";
        header('Location: ' . BASE_URL . '/dashboard.php');
        exit;
    }
}

