<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $role_id = $user_details['role_id'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
}

// Function to check permissions
function hasPermission($role_id, $module, $permission_type, $category_type = null, $company_id = null) {
    global $conn;
    
    // Managing Director has full access
    if ($role_id == 1) {
        return true;
    }
    
    $query = "SELECT is_allowed FROM role_permissions 
              WHERE role_id = ? AND module = ? AND permission_type = ?";
    $params = [$role_id, $module, $permission_type];
    $types = "iss";
    
    if ($category_type) {
        $query .= " AND (category_type = ? OR category_type IS NULL)";
        $params[] = $category_type;
        $types .= "s";
    }
    
    if ($company_id) {
        $query .= " AND (company_id = ? OR company_id IS NULL)";
        $params[] = $company_id;
        $types .= "i";
    }
    
    $query .= " ORDER BY category_type DESC, company_id DESC LIMIT 1";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    
    return $result ? (bool)$result['is_allowed'] : false;
}

// Get hierarchical categories based on user permissions
function getHierarchicalCategories($role_id, $parent_id = null, $level = 1) {
    global $conn;
    
    $query = "SELECT ec.*, c.company_name 
              FROM expense_categories ec 
              LEFT JOIN companies c ON ec.company_id = c.company_id 
              WHERE ec.is_active = 1 AND ec.category_level = ?";
    
    $params = [$level];
    $types = "i";
    
    if ($parent_id) {
        $query .= " AND ec.parent_category_id = ?";
        $params[] = $parent_id;
        $types .= "i";
    } else {
        $query .= " AND ec.parent_category_id IS NULL";
    }
    
    // Filter based on role permissions
    if ($role_id == 2) { // Fund Manager
        $query .= " AND ec.category_type NOT IN ('FAMILY', 'SALARY')";
    }
    
    $query .= " ORDER BY ec.sort_order, ec.category_name";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    
    $categories = [];
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $categories[] = $row;
    }
    
    return $categories;
}

// Get companies
$companies_query = "SELECT * FROM companies WHERE is_active = 1 ORDER BY company_name";
$companies = $conn->query($companies_query);

// Get expense statistics
$stats_query = "SELECT 
    COUNT(*) as total_expenses,
    SUM(amount) as total_amount,
    COUNT(CASE WHEN status = 'PENDING' THEN 1 END) as pending_count,
    COUNT(CASE WHEN status = 'APPROVED' THEN 1 END) as approved_count
    FROM expenses e";

// Apply role-based filtering for statistics
if ($role_id == 2) { // Fund Manager
    $stats_query .= " JOIN expense_categories ec ON e.category_id = ec.category_id 
                      WHERE ec.category_type NOT IN ('FAMILY', 'SALARY')";
}

$stats = $conn->query($stats_query)->fetch_assoc();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Expense Administration - Personal Fund Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.32/dist/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .page-header {
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .category-tree {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .tree-header {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.5rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .category-item {
            padding: 0.75rem;
            border-radius: 8px;
            margin-bottom: 0.5rem;
            border: 1px solid #e2e8f0;
            transition: all 0.2s ease;
        }
        
        .category-item:hover {
            background: #f8fafc;
            border-color: #6366f1;
        }
        
        .category-level-1 {
            background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
            color: white;
            font-weight: 600;
            font-size: 1.1rem;
            border: none;
        }
        
        .category-level-1:hover {
            background: linear-gradient(135deg, #1d4ed8 0%, #1e40af 100%);
        }
        
        .category-level-2 {
            background: #e0e7ff;
            color: #3730a3;
            font-weight: 600;
            margin-left: 1.5rem;
            border-left: 4px solid #6366f1;
        }
        
        .category-level-3 {
            background: #f1f5f9;
            color: #475569;
            margin-left: 3rem;
            border-left: 4px solid #94a3b8;
            font-size: 0.9rem;
        }
        
        .category-actions {
            display: flex;
            gap: 0.5rem;
            margin-left: auto;
        }
        
        .btn {
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-weight: 600;
            font-size: 0.75rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .btn-primary { background: #3b82f6; color: white; }
        .btn-primary:hover { background: #1d4ed8; color: white; }
        
        .btn-success { background: #059669; color: white; }
        .btn-success:hover { background: #047857; color: white; }
        
        .btn-warning { background: #d97706; color: white; }
        .btn-warning:hover { background: #b45309; color: white; }
        
        .btn-secondary { background: #6b7280; color: white; }
        .btn-secondary:hover { background: #4b5563; color: white; }
        
        .category-name {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .company-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            background: rgba(255, 255, 255, 0.2);
            color: inherit;
        }
        
        .permission-note {
            background: #fef3c7;
            border: 1px solid #f59e0b;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 2rem;
        }
        
        .permission-note.restricted {
            background: #fee2e2;
            border-color: #ef4444;
        }
        
        .restricted-category {
            opacity: 0.5;
            pointer-events: none;
        }
        
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .category-level-2 {
                margin-left: 1rem;
            }
            
            .category-level-3 {
                margin-left: 2rem;
            }
            
            .category-actions {
                flex-direction: column;
                align-items: stretch;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <h1 class="page-title">Expense Administration</h1>
                        <p class="page-subtitle">Hierarchical expense management system with company-based organization</p>
                    </div>

                    <!-- Permission Notice -->
                    <?php if ($role_name === 'Fund Manager'): ?>
                    <div class="permission-note">
                        <strong>Note:</strong> As a Fund Manager, you have restricted access. You cannot view or manage Family Expenses and Salaries Expenses.
                    </div>
                    <?php elseif ($role_name === 'Administrator'): ?>
                    <div class="permission-note">
                        <strong>Full Access:</strong> As Managing Director, you have complete access to all expense categories and functions.
                    </div>
                    <?php endif; ?>

                    <!-- Summary Statistics -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($stats['total_expenses'] ?? 0); ?></div>
                            <div class="stat-label">Total Expenses</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['total_amount'] ?? 0, 2); ?></div>
                            <div class="stat-label">Total Amount</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($stats['pending_count'] ?? 0); ?></div>
                            <div class="stat-label">Pending Approval</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($stats['approved_count'] ?? 0); ?></div>
                            <div class="stat-label">Approved</div>
                        </div>
                    </div>

                    <!-- Expense Category Tree -->
                    <div class="category-tree">
                        <h3 class="tree-header">Expense Category Structure</h3>
                        
                        <?php 
                        // Get level 1 categories
                        $level1_categories = getHierarchicalCategories($role_id, null, 1);
                        
                        foreach ($level1_categories as $level1):
                            $is_restricted = ($role_id == 2 && in_array($level1['category_type'], ['FAMILY', 'SALARY']));
                        ?>
                        
                        <div class="category-item category-level-1 <?php echo $is_restricted ? 'restricted-category' : ''; ?>">
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="category-name">
                                    <i class="ph-buildings"></i>
                                    <?php echo htmlspecialchars($level1['category_name']); ?>
                                    <?php if ($level1['company_name']): ?>
                                        <span class="company-badge"><?php echo htmlspecialchars($level1['company_name']); ?></span>
                                    <?php endif; ?>
                                </div>
                                <?php if (!$is_restricted): ?>
                                <div class="category-actions">
                                    <a href="add_expense.php?category=<?php echo $level1['category_id']; ?>" class="btn btn-success">
                                        <i class="ph-plus"></i> Add Expense
                                    </a>
                                    <a href="expense_reports.php?category_filter=<?php echo $level1['category_id']; ?>" class="btn btn-primary">
                                        <i class="ph-chart-bar"></i> Reports
                                    </a>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <?php 
                        // Get level 2 categories
                        $level2_categories = getHierarchicalCategories($role_id, $level1['category_id'], 2);
                        
                        foreach ($level2_categories as $level2): 
                        ?>
                        
                        <div class="category-item category-level-2">
                           <div class="d-flex justify-content-between align-items-center">
                               <div class="category-name">
                                   <i class="ph-folder"></i>
                                   <?php echo htmlspecialchars($level2['category_name']); ?>
                               </div>
                               <div class="category-actions">
                                   <a href="add_expense.php?category=<?php echo $level2['category_id']; ?>" class="btn btn-success">
                                       <i class="ph-plus"></i> Add
                                   </a>
                                   <a href="list_expenses.php?category_filter=<?php echo $level2['category_id']; ?>" class="btn btn-warning">
                                       <i class="ph-list"></i> List
                                   </a>
                               </div>
                           </div>
                       </div>
                       
                       <?php 
                       // Get level 3 categories
                       $level3_categories = getHierarchicalCategories($role_id, $level2['category_id'], 3);
                       
                       foreach ($level3_categories as $level3): 
                       ?>
                       
                       <div class="category-item category-level-3">
                           <div class="d-flex justify-content-between align-items-center">
                               <div class="category-name">
                                   <i class="ph-file-text"></i>
                                   <?php echo htmlspecialchars($level3['category_name']); ?>
                               </div>
                               <div class="category-actions">
                                   <a href="add_expense.php?category=<?php echo $level3['category_id']; ?>" class="btn btn-success">
                                       <i class="ph-plus"></i> Track Expense
                                   </a>
                                   <a href="list_expenses.php?category_filter=<?php echo $level3['category_id']; ?>" class="btn btn-secondary">
                                       <i class="ph-eye"></i> View
                                   </a>
                               </div>
                           </div>
                       </div>
                       
                       <?php endforeach; ?>
                       
                       <!-- Show placeholder for empty level 3 categories -->
                       <?php if (empty($level3_categories)): ?>
                           <?php if ($level2['category_code'] == 'ONLINE_SSO' || $level2['category_code'] == 'NOTALE_SSO'): ?>
                           <div class="category-item category-level-3" style="opacity: 0.6;">
                               <div class="category-name">
                                   <i class="ph-minus-circle"></i>
                                   None at the moment
                               </div>
                           </div>
                           <div class="category-item category-level-3" style="opacity: 0.6;">
                               <div class="category-name">
                                   <i class="ph-minus-circle"></i>
                                   None at the moment
                               </div>
                           </div>
                           <?php endif; ?>
                       <?php endif; ?>
                       
                       <?php endforeach; ?>
                       
                       <!-- Show placeholder for Family and Salaries if they have no subcategories -->
                       <?php if (($level1['category_type'] == 'FAMILY' || $level1['category_type'] == 'SALARY') && empty($level2_categories)): ?>
                       <div class="category-item category-level-2" style="opacity: 0.6;">
                           <div class="category-name">
                               <i class="ph-minus-circle"></i>
                               None at the moment
                           </div>
                       </div>
                       <div class="category-item category-level-2" style="opacity: 0.6;">
                           <div class="category-name">
                               <i class="ph-minus-circle"></i>
                               None at the moment
                           </div>
                       </div>
                       <?php endif; ?>
                       
                       <?php endforeach; ?>
                       
                   </div>

                   <!-- Quick Actions -->
                   <div class="row">
                       <div class="col-lg-6">
                           <div class="category-tree">
                               <h3 class="tree-header">Quick Actions</h3>
                               <div class="d-grid gap-2">
                                   <a href="add_expense.php" class="btn btn-primary">
                                       <i class="ph-plus-circle"></i> Add New Expense
                                   </a>
                                   <a href="list_expenses.php" class="btn btn-warning">
                                       <i class="ph-list-bullets"></i> View All Expenses
                                   </a>
                                   <a href="expense_reports.php" class="btn btn-success">
                                       <i class="ph-chart-pie"></i> Generate Reports
                                   </a>
                                   <?php if (hasPermission($role_id, 'EXPENSES', 'APPROVE')): ?>
                                   <a href="expense_approvals.php" class="btn btn-secondary">
                                       <i class="ph-check-circle"></i> Pending Approvals
                                   </a>
                                   <?php endif; ?>
                               </div>
                           </div>
                       </div>
                       
                       <div class="col-lg-6">
                           <div class="category-tree">
                               <h3 class="tree-header">Companies Overview</h3>
                               <?php 
                               $companies->data_seek(0);
                               while ($company = $companies->fetch_assoc()): 
                                   // Get company expense stats
                                   $company_stats_query = "SELECT 
                                       COUNT(*) as count,
                                       COALESCE(SUM(amount), 0) as total
                                       FROM expenses e 
                                       JOIN expense_categories ec ON e.category_id = ec.category_id 
                                       WHERE ec.company_id = ?";
                                   
                                   $stmt_company = $conn->prepare($company_stats_query);
                                   $stmt_company->bind_param("i", $company['company_id']);
                                   $stmt_company->execute();
                                   $company_stats = $stmt_company->get_result()->fetch_assoc();
                               ?>
                               <div class="category-item">
                                   <div class="d-flex justify-content-between align-items-center">
                                       <div class="category-name">
                                           <i class="ph-building-office"></i>
                                           <div>
                                               <strong><?php echo htmlspecialchars($company['company_name']); ?></strong>
                                               <br>
                                               <small style="color: #64748b;">
                                                   <?php echo number_format($company_stats['count']); ?> expenses • 
                                                   KES <?php echo number_format($company_stats['total'], 2); ?>
                                               </small>
                                           </div>
                                       </div>
                                       <div class="category-actions">
                                           <a href="expense_reports.php?company_filter=<?php echo $company['company_id']; ?>" class="btn btn-primary">
                                               <i class="ph-chart-bar"></i> Reports
                                           </a>
                                       </div>
                                   </div>
                               </div>
                               <?php endwhile; ?>
                           </div>
                       </div>
                   </div>

                   <!-- Recent Expenses -->
                   <div class="category-tree">
                       <h3 class="tree-header">Recent Expenses</h3>
                       
                       <?php 
                       $recent_query = "SELECT e.*, ec.category_name, ec.category_type, c.company_name, u.full_name as created_by_name
                                       FROM expenses e 
                                       JOIN expense_categories ec ON e.category_id = ec.category_id 
                                       LEFT JOIN companies c ON ec.company_id = c.company_id 
                                       LEFT JOIN users u ON e.created_by = u.user_id 
                                       WHERE 1=1";
                       
                       // Apply role-based filtering
                       if ($role_id == 2) { // Fund Manager
                           $recent_query .= " AND ec.category_type NOT IN ('FAMILY', 'SALARY')";
                       }
                       
                       $recent_query .= " ORDER BY e.created_at DESC LIMIT 10";
                       
                       $recent_expenses = $conn->query($recent_query);
                       ?>
                       
                       <div class="table-responsive">
                           <table class="table table-hover">
                               <thead style="background: #f8fafc;">
                                   <tr>
                                       <th>Date</th>
                                       <th>Expense Title</th>
                                       <th>Category</th>
                                       <th>Company</th>
                                       <th>Amount</th>
                                       <th>Status</th>
                                       <th>Created By</th>
                                       <th>Actions</th>
                                   </tr>
                               </thead>
                               <tbody>
                                   <?php if ($recent_expenses->num_rows > 0): ?>
                                       <?php while ($expense = $recent_expenses->fetch_assoc()): ?>
                                       <tr>
                                           <td><?php echo date('M j, Y', strtotime($expense['expense_date'])); ?></td>
                                           <td>
                                               <strong><?php echo htmlspecialchars($expense['expense_title']); ?></strong>
                                               <?php if ($expense['description']): ?>
                                                   <br><small style="color: #64748b;">
                                                       <?php echo htmlspecialchars(substr($expense['description'], 0, 50)) . (strlen($expense['description']) > 50 ? '...' : ''); ?>
                                                   </small>
                                               <?php endif; ?>
                                           </td>
                                           <td>
                                               <span class="badge" style="background: <?php echo $expense['color_code'] ?? '#6366f1'; ?>; color: white;">
                                                   <?php echo htmlspecialchars($expense['category_name']); ?>
                                               </span>
                                           </td>
                                           <td><?php echo htmlspecialchars($expense['company_name'] ?? 'N/A'); ?></td>
                                           <td style="font-weight: 600; color: #059669;">
                                               KES <?php echo number_format($expense['amount'], 2); ?>
                                           </td>
                                           <td>
                                               <?php 
                                               $status_class = match($expense['status']) {
                                                   'DRAFT' => 'background: #f1f5f9; color: #64748b;',
                                                   'PENDING' => 'background: #fef3c7; color: #92400e;',
                                                   'APPROVED' => 'background: #dcfce7; color: #166534;',
                                                   'PAID' => 'background: #dcfce7; color: #166534;',
                                                   'REJECTED' => 'background: #fee2e2; color: #991b1b;',
                                                   default => 'background: #f1f5f9; color: #64748b;'
                                               };
                                               ?>
                                               <span class="badge" style="<?php echo $status_class; ?>">
                                                   <?php echo ucfirst(str_replace('_', ' ', strtolower($expense['status']))); ?>
                                               </span>
                                           </td>
                                           <td><?php echo htmlspecialchars($expense['created_by_name']); ?></td>
                                           <td>
                                               <div class="d-flex gap-1">
                                                   <a href="view_expense.php?id=<?php echo $expense['expense_id']; ?>" class="btn btn-primary btn-sm">
                                                       <i class="ph-eye"></i>
                                                   </a>
                                                   <?php if (hasPermission($role_id, 'EXPENSES', 'EDIT', $expense['category_type'])): ?>
                                                   <a href="edit_expense.php?id=<?php echo $expense['expense_id']; ?>" class="btn btn-warning btn-sm">
                                                       <i class="ph-pencil"></i>
                                                   </a>
                                                   <?php endif; ?>
                                               </div>
                                           </td>
                                       </tr>
                                       <?php endwhile; ?>
                                   <?php else: ?>
                                       <tr>
                                           <td colspan="8" style="text-align: center; padding: 2rem; color: #64748b;">
                                               No expenses found. <a href="add_expense.php">Create your first expense</a>.
                                           </td>
                                       </tr>
                                   <?php endif; ?>
                               </tbody>
                           </table>
                       </div>
                   </div>

               </div>
           </div>
           <?php include 'layouts/footer.php'; ?>
       </div>
   </div>

   <?php include 'layouts/vendor-scripts.php'; ?>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.32/dist/sweetalert2.all.min.js"></script>
   
   <script>
       $(document).ready(function() {
           // Add hover effects and animations
           $('.category-item').hover(
               function() {
                   $(this).addClass('shadow-sm');
               },
               function() {
                   $(this).removeClass('shadow-sm');
               }
           );
           
           // Show confirmation for expense actions
           $('a[href*="add_expense"]').click(function(e) {
               const categoryName = $(this).closest('.category-item').find('.category-name').text().trim();
               if (categoryName && !categoryName.includes('None at the moment')) {
                   Swal.fire({
                       title: 'Create Expense',
                       text: `Create a new expense for "${categoryName}"?`,
                       icon: 'question',
                       showCancelButton: true,
                       confirmButtonColor: '#059669',
                       cancelButtonColor: '#6b7280',
                       confirmButtonText: 'Yes, Create',
                       cancelButtonText: 'Cancel'
                   }).then((result) => {
                       if (result.isConfirmed) {
                           window.location.href = $(this).attr('href');
                       }
                   });
                   e.preventDefault();
               }
           });
           
           // Auto-refresh stats every 5 minutes
           setTimeout(function() {
               location.reload();
           }, 300000);
       });
   </script>

   <!-- App js -->
   <script src="assets/js/app.js"></script>
</body>
</html>

<?php $conn->close(); ?>