<?php
/**
 * eTIMS Integration Management
 * Configure and manage eTIMS integration
 * Kenyan Pension & Life Insurance Management System
 */

require_once 'layouts/main.php';
require_once 'includes/auth.php';
require_once 'classes/ETIMSService.php';

requireLogin();
requirePermission('manage_etims_integration');

$etimsService = new ETIMSService($conn);
$message = '';
$messageType = '';

// Test connection
if (isset($_GET['test'])) {
    $healthCheck = $etimsService->checkHealth();
    if ($healthCheck['success']) {
        $message = 'eTIMS connection successful!';
        $messageType = 'success';
    } else {
        $message = 'eTIMS connection failed: ' . ($healthCheck['message'] ?? 'Unknown error');
        $messageType = 'danger';
    }
}

// Get recent invoices
$recentInvoices = $conn->query("SELECT * FROM etims_invoices 
                                ORDER BY created_at DESC 
                                LIMIT 20")->fetch_all(MYSQLI_ASSOC);

// Get statistics
$stats = [
    'total_invoices' => $conn->query("SELECT COUNT(*) FROM etims_invoices")->fetch_row()[0],
    'successful' => $conn->query("SELECT COUNT(*) FROM etims_invoices WHERE status = 'SUBMITTED'")->fetch_row()[0],
    'failed' => $conn->query("SELECT COUNT(*) FROM etims_invoices WHERE status = 'FAILED'")->fetch_row()[0],
    'pending' => $conn->query("SELECT COUNT(*) FROM etims_invoices WHERE status = 'PENDING'")->fetch_row()[0]
];

$pageTitle = 'eTIMS Integration';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'eTIMS Integration')); ?>
    <link rel="stylesheet" href="assets/css/pension-dashboard.css">
    <?php include 'layouts/head-css.php'; ?>
</head>

<body data-sidebar="dark">
    <div id="layout-wrapper">
        <?php include 'layouts/sidebar.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="welcome-header" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>eTIMS Integration</h2>
                                <p>Manage Electronic Tax Invoice Management System integration</p>
                            </div>
                        </div>
                    </div>

                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Statistics -->
                    <div class="metrics-row">
                        <div class="metric-card contributions">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Invoices</h6>
                                <span class="metric-icon"><i class="ri-file-list-line"></i></span>
                            </div>
                            <div class="metric-value"><?php echo number_format($stats['total_invoices']); ?></div>
                        </div>

                        <div class="metric-card balances">
                            <div class="metric-header">
                                <h6 class="metric-title">Successful</h6>
                                <span class="metric-icon"><i class="ri-check-line"></i></span>
                            </div>
                            <div class="metric-value"><?php echo number_format($stats['successful']); ?></div>
                        </div>

                        <div class="metric-card withdrawals">
                            <div class="metric-header">
                                <h6 class="metric-title">Failed</h6>
                                <span class="metric-icon"><i class="ri-close-line"></i></span>
                            </div>
                            <div class="metric-value"><?php echo number_format($stats['failed']); ?></div>
                        </div>

                        <div class="metric-card policies">
                            <div class="metric-header">
                                <h6 class="metric-title">Pending</h6>
                                <span class="metric-icon"><i class="ri-time-line"></i></span>
                            </div>
                            <div class="metric-value"><?php echo number_format($stats['pending']); ?></div>
                        </div>
                    </div>

                    <!-- Configuration -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">eTIMS Configuration</h4>
                                </div>
                                <div class="page-card-body">
                                    <p class="text-muted">Configure eTIMS settings in <a href="settings.php">System Settings</a> → Integrations tab.</p>
                                    <a href="settings.php?tab=integrations" class="btn btn-primary me-2">
                                        <i class="ri-settings-3-line me-2"></i>Configure Settings
                                    </a>
                                    <a href="?test=1" class="btn btn-success">
                                        <i class="ri-plug-line me-2"></i>Test Connection
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Invoices -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Recent Invoices</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Invoice Number</th>
                                                    <th>Source Type</th>
                                                    <th>Source ID</th>
                                                    <th>Trader Invoice</th>
                                                    <th>Status</th>
                                                    <th>Created</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($recentInvoices)): ?>
                                                    <tr><td colspan="7" class="text-center">No invoices found</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($recentInvoices as $invoice): ?>
                                                        <tr>
                                                            <td><strong><?php echo htmlspecialchars($invoice['invoice_number']); ?></strong></td>
                                                            <td><span class="badge bg-info"><?php echo htmlspecialchars($invoice['source_type']); ?></span></td>
                                                            <td><?php echo $invoice['source_id']; ?></td>
                                                            <td><?php echo htmlspecialchars($invoice['trader_invoice_no'] ?? 'N/A'); ?></td>
                                                            <td>
                                                                <span class="status-badge status-<?php echo strtolower($invoice['status']); ?>">
                                                                    <?php echo htmlspecialchars($invoice['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo date('d M Y, H:i', strtotime($invoice['created_at'])); ?></td>
                                                            <td>
                                                                <a href="etims_invoice_details.php?id=<?php echo $invoice['invoice_record_id']; ?>" class="btn btn-sm btn-info">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
