<?php
/**
 * Enterprise HRM ERP System - MIS Reports
 * Excel-like Management Information System
 */

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

$pageTitle = 'MIS Reports';
$currentModule = 'mis';

$siteId = getCurrentSiteId();

if (!$siteId) {
    $_SESSION['error'] = 'Site ID not found. Please ensure you are assigned to a site.';
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

// Check permissions
$roleCode = strtolower($_SESSION['role_code'] ?? '');
$canCreate = hasPermission('MIS_CREATE') || in_array($roleCode, ['super_admin', 'hr_admin']);
$canDelete = hasPermission('MIS_DELETE') || in_array($roleCode, ['super_admin', 'hr_admin']);

$misReports = [];
$errors = [];

// Handle delete request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    if (!$canDelete) {
        $_SESSION['error'] = 'You do not have permission to delete MIS reports.';
        header('Location: ' . BASE_URL . '/modules/mis/index.php');
        exit;
    }
    
    $deleteId = isset($_POST['mis_id']) ? (int)$_POST['mis_id'] : 0;
    
    if ($deleteId > 0) {
        try {
            $db = getDB();
            
            // Check if MIS report exists and belongs to current site
            $stmt = $db->prepare("SELECT mis_id, is_locked FROM mis_reports WHERE mis_id = ? AND site_id = ?");
            $stmt->execute([$deleteId, $siteId]);
            $report = $stmt->fetch();
            
            if (!$report) {
                $_SESSION['error'] = 'MIS report not found or you do not have permission to delete it.';
                header('Location: ' . BASE_URL . '/modules/mis/index.php');
                exit;
            }
            
            // Check if report is locked
            if ($report['is_locked']) {
                $_SESSION['error'] = 'Cannot delete locked MIS report.';
                header('Location: ' . BASE_URL . '/modules/mis/index.php');
                exit;
            }
            
            // Start transaction
            $db->beginTransaction();
            
            // Delete related data from all MIS tables
            $relatedTables = [
                'mis_sales',
                'mis_segment_purchases',
                'mis_purchases',
                'mis_odc_breakup',
                'mis_labour',
                'mis_budget_vs_actual',
                'mis_fuel_consumption',
                'mis_summary'
            ];
            
            foreach ($relatedTables as $table) {
                try {
                    $stmt = $db->prepare("DELETE FROM {$table} WHERE mis_id = ?");
                    $stmt->execute([$deleteId]);
                } catch (Exception $e) {
                    // Table might not exist, continue
                    error_log("MIS delete from {$table}: " . $e->getMessage());
                }
            }
            
            // Delete the main MIS report
            $stmt = $db->prepare("DELETE FROM mis_reports WHERE mis_id = ? AND site_id = ?");
            $stmt->execute([$deleteId, $siteId]);
            
            if ($stmt->rowCount() > 0) {
                $db->commit();
                logAudit('DELETE', 'mis_reports', $deleteId);
                $_SESSION['success'] = 'MIS report deleted successfully.';
            } else {
                $db->rollBack();
                $_SESSION['error'] = 'Failed to delete MIS report.';
            }
            
        } catch (Exception $e) {
            if (isset($db) && $db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error deleting MIS report: " . $e->getMessage());
            $_SESSION['error'] = 'An error occurred while deleting the MIS report.';
        }
    } else {
        $_SESSION['error'] = 'Invalid MIS report ID.';
    }
    
    header('Location: ' . BASE_URL . '/modules/mis/index.php');
    exit;
}

// Get all MIS reports for this site
try {
    $db = getDB();

    // Ensure permissions exist
    ensureMisPermissions();
    
    // Create tables if they don't exist (without foreign keys to avoid issues)
    try {
        $db->exec("
            CREATE TABLE IF NOT EXISTS `mis_reports` (
              `mis_id` int(11) NOT NULL AUTO_INCREMENT,
              `site_id` int(11) NOT NULL,
              `report_month` int(11) NOT NULL,
              `report_year` int(11) NOT NULL,
              `entity` varchar(255) DEFAULT 'Divine Food Cravers',
              `segment` varchar(100) DEFAULT 'Industry',
              `location` varchar(100),
              `hm_manager_name` varchar(255),
              `site_accountant_name` varchar(255),
              `operation_head` varchar(255),
              `report_status` enum('draft','final','locked') DEFAULT 'draft',
              `is_locked` tinyint(1) DEFAULT 0,
              `locked_at` datetime,
              `locked_by` int(11),
              `created_by` int(11),
              `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
              `updated_by` int(11),
              `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
              PRIMARY KEY (`mis_id`),
              UNIQUE KEY `unique_site_month_year` (`site_id`, `report_month`, `report_year`),
              KEY `fk_mis_site` (`site_id`),
              KEY `fk_mis_created_by` (`created_by`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    } catch (Exception $e) {
        // Table might already exist with different structure, continue
        error_log("MIS table creation note: " . $e->getMessage());
    }
    
    // Get MIS reports list
    $stmt = $db->prepare("
        SELECT m.*, s.site_name,
               u.full_name as created_by_name
        FROM mis_reports m
        LEFT JOIN sites s ON m.site_id = s.site_id
        LEFT JOIN users u ON m.created_by = u.user_id
        WHERE m.site_id = ?
        ORDER BY m.report_year DESC, m.report_month DESC
        LIMIT 50
    ");
    $stmt->execute([$siteId]);
    $misReports = $stmt->fetchAll();
    
} catch (PDOException $e) {
    error_log("MIS list PDO error: " . $e->getMessage());
    $errors[] = 'Database error: ' . htmlspecialchars($e->getMessage());
} catch (Exception $e) {
    error_log("MIS list error: " . $e->getMessage());
    $errors[] = 'Error loading MIS reports: ' . htmlspecialchars($e->getMessage());
}

include __DIR__ . '/../../includes/header.php';
?>

<style>
/* Action Buttons Styling */
.action-buttons {
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
}

.btn-danger {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: white;
    border: none;
}

.btn-danger:hover {
    background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
    transform: translateY(-1px);
}

.btn-danger:disabled {
    background: #9ca3af;
    cursor: not-allowed;
    transform: none;
}

/* Status badge for locked */
.status-locked {
    background: #fbbf24;
    color: #78350f;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 10px;
    font-weight: bold;
    margin-left: 5px;
}
</style>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">MIS Reports - Management Information System</h2>
        <?php if ($canCreate): ?>
        <a href="<?php echo BASE_URL; ?>/modules/mis/create.php" class="btn btn-primary">Create New MIS Report</a>
        <?php endif; ?>
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error" style="margin-top: 20px;">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <?php if (empty($misReports)): ?>
    <div class="table-empty" style="margin-top: 30px;">
        <div class="table-empty-icon">📈</div>
        <div class="table-empty-message">No MIS reports found</div>
        <?php if ($canCreate): ?>
        <div class="table-empty-submessage">
            <a href="<?php echo BASE_URL; ?>/modules/mis/create.php" class="btn btn-primary">Create First MIS Report</a>
        </div>
        <?php endif; ?>
    </div>
    <?php else: ?>
    <div style="margin-top: 20px;">
        <table class="data-table">
            <thead>
                <tr>
                    <th>Period</th>
                    <th>Entity</th>
                    <th>Segment</th>
                    <th>Location</th>
                    <th>Created By</th>
                    <th>Created At</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($misReports as $report): ?>
                <tr>
                    <td>
                        <?php 
                        $monthName = date('F', mktime(0, 0, 0, $report['report_month'], 1));
                        echo $monthName . ' ' . $report['report_year'];
                        if ($report['is_locked']) {
                            echo '<span class="status-locked">🔒 Locked</span>';
                        }
                        ?>
                    </td>
                    <td><?php echo htmlspecialchars($report['entity'] ?? 'N/A'); ?></td>
                    <td><?php echo htmlspecialchars($report['segment'] ?? 'N/A'); ?></td>
                    <td><?php echo htmlspecialchars($report['location'] ?? 'N/A'); ?></td>
                    <td><?php echo htmlspecialchars($report['created_by_name'] ?? 'N/A'); ?></td>
                    <td><?php echo date('d M Y', strtotime($report['created_at'])); ?></td>
                    <td>
                        <div class="action-buttons">
                            <a href="<?php echo BASE_URL; ?>/modules/mis/view.php?id=<?php echo $report['mis_id']; ?>" 
                               class="btn btn-sm btn-primary">View</a>
                            <?php if ($canCreate && !$report['is_locked']): ?>
                            <a href="<?php echo BASE_URL; ?>/modules/mis/edit.php?id=<?php echo $report['mis_id']; ?>" 
                               class="btn btn-sm btn-secondary">Edit</a>
                            <?php endif; ?>
                            <a href="<?php echo BASE_URL; ?>/modules/mis/export.php?id=<?php echo $report['mis_id']; ?>&format=excel" 
                               class="btn btn-sm btn-success">Export Excel</a>
                            <?php if ($canDelete): ?>
                            <form method="POST" style="display: inline;" 
                                  onsubmit="return confirm('Are you sure you want to delete this MIS report for <?php echo $monthName . ' ' . $report['report_year']; ?>?\n\nThis will permanently delete all related data including:\n- Sales data\n- Purchase data\n- Labour data\n- ODC breakup\n- Fuel consumption\n- Budget data\n\nThis action cannot be undone!');">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="mis_id" value="<?php echo $report['mis_id']; ?>">
                                <button type="submit" class="btn btn-sm btn-danger" 
                                        <?php echo $report['is_locked'] ? 'disabled title="Cannot delete locked report"' : ''; ?>>
                                    🗑️ Delete
                                </button>
                            </form>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<?php include __DIR__ . '/../../includes/footer.php'; ?>
