<?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'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
}

// Handle form submissions
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add_category') {
            $category_name = trim($_POST['category_name']);
            $description = trim($_POST['description']);
            $color_code = $_POST['color_code'];
            
            if (!empty($category_name)) {
                $stmt = $conn->prepare("INSERT INTO fund_categories (category_name, description, color_code) VALUES (?, ?, ?)");
                $stmt->bind_param("sss", $category_name, $description, $color_code);
                
                if ($stmt->execute()) {
                    $message = "Category added successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error adding category: " . $conn->error;
                    $message_type = "error";
                }
            } else {
                $message = "Category name is required!";
                $message_type = "error";
            }
        } elseif ($_POST['action'] === 'update_category') {
            $category_id = $_POST['category_id'];
            $category_name = trim($_POST['category_name']);
            $description = trim($_POST['description']);
            $color_code = $_POST['color_code'];
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            
            if (!empty($category_name)) {
                $stmt = $conn->prepare("UPDATE fund_categories SET category_name = ?, description = ?, color_code = ?, is_active = ? WHERE category_id = ?");
                $stmt->bind_param("sssii", $category_name, $description, $color_code, $is_active, $category_id);
                
                if ($stmt->execute()) {
                    $message = "Category updated successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error updating category: " . $conn->error;
                    $message_type = "error";
                }
            } else {
                $message = "Category name is required!";
                $message_type = "error";
            }
        } elseif ($_POST['action'] === 'delete_category') {
            $category_id = $_POST['category_id'];
            
            // Check if category is in use
            $check_stmt = $conn->prepare("SELECT COUNT(*) as fund_count FROM funds WHERE category_id = ?");
            $check_stmt->bind_param("i", $category_id);
            $check_stmt->execute();
            $fund_count = $check_stmt->get_result()->fetch_assoc()['fund_count'];
            
            if ($fund_count > 0) {
                $message = "Cannot delete category: It is currently being used by $fund_count fund(s).";
                $message_type = "error";
            } else {
                $stmt = $conn->prepare("DELETE FROM fund_categories WHERE category_id = ?");
                $stmt->bind_param("i", $category_id);
                
                if ($stmt->execute()) {
                    $message = "Category deleted successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error deleting category: " . $conn->error;
                    $message_type = "error";
                }
            }
        }
    }
}

// Get categories with fund counts
$query = "SELECT fc.*, 
                 COUNT(f.fund_id) as fund_count,
                 SUM(f.current_balance) as total_balance
          FROM fund_categories fc 
          LEFT JOIN funds f ON fc.category_id = f.category_id AND f.is_active = 1
          GROUP BY fc.category_id 
          ORDER BY fc.category_name";
$categories = $conn->query($query);

// Get category statistics
$stats_query = "SELECT 
    COUNT(*) as total_categories,
    SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_categories,
    (SELECT COUNT(*) FROM funds WHERE is_active = 1) as total_funds,
    (SELECT SUM(current_balance) FROM funds WHERE is_active = 1) as total_fund_balance
    FROM fund_categories";
$stats = $conn->query($stats_query)->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Fund Categories - Personal Fund Tracker')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        /* Use the same styling from list_consultations.php */
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 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;
        }
        
        /* Alert Messages */
        .alert {
            border-radius: 8px;
            border: none;
            margin-bottom: 1.5rem;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
        }
        
        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
        }
        
        /* Stats Cards */
        .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;
        }
        
        /* Form Card */
        .form-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;
            margin-bottom: 2rem;
        }
        
        .form-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
        }
        
        /* Table Card */
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        /* Category Color Badge */
        .category-color {
            width: 20px;
            height: 20px;
            border-radius: 4px;
            border: 2px solid white;
            box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
        }
        
        /* Status Badges */
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #fee2e2; color: #991b1b; }
        
        /* Action Buttons */
        .btn-action {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            margin: 0 0.25rem;
            transition: all 0.2s ease;
            border: none;
            cursor: pointer;
        }
        
        .btn-primary { background: #3b82f6; color: white; }
        .btn-primary:hover { background: #1d4ed8; color: white; }
        
        .btn-warning { background: #d97706; color: white; }
        .btn-warning:hover { background: #b45309; color: white; }
        
        .btn-danger { background: #dc2626; color: white; }
        .btn-danger:hover { background: #b91c1c; color: white; }
        
        /* Form Controls */
        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-success {
            background: #059669;
            color: white;
        }
        
        .btn-success:hover {
            background: #047857;
        }
        
        /* Color Picker */
        .color-picker {
            width: 50px;
            height: 40px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            cursor: pointer;
        }
        
        /* Modal Styles */
        .modal-content {
            border-radius: 12px;
            border: none;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }
        
        .modal-header {
            border-bottom: 1px solid #e2e8f0;
            padding: 1.5rem;
        }
        
        .modal-body {
            padding: 1.5rem;
        }
        
        .modal-footer {
            border-top: 1px solid #e2e8f0;
            padding: 1.5rem;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .table-header {
                flex-direction: column;
                gap: 1rem;
                align-items: stretch;
            }
            
            .data-table {
                font-size: 0.75rem;
            }
            
            .data-table th,
            .data-table td {
                padding: 0.5rem;
            }
        }
        
        /* Footer spacing fix */
        .main-content {
            padding-bottom: 2rem;
        }
        
        .page-content {
            margin-bottom: 3rem;
        }
    </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">Fund Categories Management</h1>
                        <p class="page-subtitle">Manage fund categories and their settings</p>
                    </div>

                    <!-- Alert Messages -->
                    <?php if ($message): ?>
                        <div class="alert alert-<?php echo $message_type === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show" role="alert">
                            <?php echo htmlspecialchars($message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Stats Row -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['total_categories'] ?? 0; ?></div>
                            <div class="stat-label">Total Categories</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['active_categories'] ?? 0; ?></div>
                            <div class="stat-label">Active Categories</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['total_funds'] ?? 0; ?></div>
                            <div class="stat-label">Total Funds</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['total_fund_balance'] ?? 0); ?></div>
                            <div class="stat-label">Total Fund Balance</div>
                        </div>
                    </div>

                    <!-- Add Category Form -->
                    <div class="form-card">
                        <h3 class="form-title">Add New Category</h3>
                        <form method="POST" class="row g-3">
                            <input type="hidden" name="action" value="add_category">
                            <div class="col-md-4">
                                <label class="form-label">Category Name *</label>
                                <input type="text" class="form-control" name="category_name" required placeholder="e.g., Business Investment">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Description</label>
                                <input type="text" class="form-control" name="description" placeholder="Brief description of the category">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Color</label>
                                <input type="color" class="form-control color-picker" name="color_code" value="#3498db">
                            </div>
                            <div class="col-12">
                                <button type="submit" class="btn btn-success">
                                    <i class="ph-plus me-1"></i> Add Category
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Categories Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Fund Categories</h3>
                        </div>
                        
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Category</th>
                                    <th>Description</th>
                                    <th>Color</th>
                                    <th>Funds Count</th>
                                    <th>Total Balance</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($category = $categories->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div style="font-weight: 600; color: #1e293b;">
                                            <?php echo htmlspecialchars($category['category_name']); ?>
                                        </div>
                                        <div style="color: #64748b; font-size: 0.75rem;">
                                            Created: <?php echo date('M j, Y', strtotime($category['created_at'])); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <div style="color: #64748b;">
                                            <?php echo htmlspecialchars($category['description'] ?: 'No description'); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center gap-2">
                                            <div class="category-color" style="background-color: <?php echo $category['color_code']; ?>;"></div>
                                            <span style="font-size: 0.75rem; color: #64748b;"><?php echo $category['color_code']; ?></span>
                                        </div>
                                    </td>
                                    <td>
                                        <div style="font-weight: 600; color: #1e293b;">
                                            <?php echo $category['fund_count']; ?> Funds
                                        </div>
                                    </td>
                                    <td>
                                        <div style="font-weight: 600; color: #1e293b;">
                                            KES <?php echo number_format($category['total_balance'] ?? 0); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="status-badge <?php echo $category['is_active'] ? 'status-active' : 'status-inactive'; ?>">
                                            <?php echo $category['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="d-flex gap-1">
                                            <button type="button" class="btn-action btn-warning" 
                                                    onclick="editCategory(<?php echo htmlspecialchars(json_encode($category)); ?>)" 
                                                    title="Edit Category">
                                                <i class="ph-pencil"></i>
                                            </button>
                                            <?php if ($category['fund_count'] == 0): ?>
                                                <button type="button" class="btn-action btn-danger" 
                                                        onclick="deleteCategory(<?php echo $category['category_id']; ?>, '<?php echo htmlspecialchars($category['category_name']); ?>')" 
                                                        title="Delete Category">
                                                    <i class="ph-trash"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Edit Category Modal -->
    <div class="modal fade" id="editCategoryModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Category</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" id="editCategoryForm">
                    <input type="hidden" name="action" value="update_category">
                    <input type="hidden" name="category_id" id="edit_category_id">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Category Name *</label>
                            <input type="text" class="form-control" name="category_name" id="edit_category_name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <textarea class="form-control" name="description" id="edit_description" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Color</label>
                            <input type="color" class="form-control color-picker" name="color_code" id="edit_color_code">
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_active" id="edit_is_active">
                                <label class="form-check-label" for="edit_is_active">
                                    Active
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Category</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Delete Category Modal -->
    <div class="modal fade" id="deleteCategoryModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Delete Category</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" id="deleteCategoryForm">
                    <input type="hidden" name="action" value="delete_category">
                    <input type="hidden" name="category_id" id="delete_category_id">
                    <div class="modal-body">
                        <p>Are you sure you want to delete the category "<strong id="delete_category_name"></strong>"?</p>
                        <p class="text-danger">This action cannot be undone.</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger">Delete Category</button>
                    </div>
                </form>
            </div>
        </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/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        function editCategory(category) {
            $('#edit_category_id').val(category.category_id);
            $('#edit_category_name').val(category.category_name);
            $('#edit_description').val(category.description || '');
            $('#edit_color_code').val(category.color_code);
            $('#edit_is_active').prop('checked', category.is_active == 1);
            
            $('#editCategoryModal').modal('show');
        }
        
        function deleteCategory(categoryId, categoryName) {
            $('#delete_category_id').val(categoryId);
            $('#delete_category_name').text(categoryName);
            
            $('#deleteCategoryModal').modal('show');
        }
    </script>

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

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