<?php
/**
 * Enterprise HRM ERP System - MIS Report Edit
 * Redirects to create.php with edit mode
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

// Check permissions
$roleCode = strtolower($_SESSION['role_code'] ?? '');
if (!in_array($roleCode, ['super_admin', 'hr_admin'])) {
    $_SESSION['error'] = 'You do not have permission to edit MIS reports.';
    header('Location: ' . BASE_URL . '/modules/mis/index.php');
    exit;
}

$misId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$siteId = getCurrentSiteId();

if ($misId <= 0) {
    $_SESSION['error'] = 'Invalid MIS report ID.';
    header('Location: ' . BASE_URL . '/modules/mis/index.php');
    exit;
}

// Verify report exists and is not locked
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM mis_reports WHERE mis_id = ? AND site_id = ?");
    $stmt->execute([$misId, $siteId]);
    $misData = $stmt->fetch();
    
    if (!$misData) {
        $_SESSION['error'] = 'MIS report not found.';
        header('Location: ' . BASE_URL . '/modules/mis/index.php');
        exit;
    }
    
    if ($misData['is_locked']) {
        $_SESSION['error'] = 'This MIS report is locked and cannot be edited.';
        header('Location: ' . BASE_URL . '/modules/mis/view.php?id=' . $misId);
        exit;
    }
    
} catch (Exception $e) {
    error_log("MIS edit check error: " . $e->getMessage());
    $_SESSION['error'] = 'Error loading MIS report.';
    header('Location: ' . BASE_URL . '/modules/mis/index.php');
    exit;
}

// Redirect to create page with edit mode (create.php handles both create and edit)
header('Location: ' . BASE_URL . '/modules/mis/create.php?id=' . $misId);
exit;
