<?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'];
}

$success_message = '';
$error_message = '';

// Handle form submissions
if ($_POST) {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_category':
                $category_name = trim($_POST['category_name']);
                $category_type = $_POST['category_type'];
                $description = trim($_POST['description']);
                $color_code = $_POST['color_code'];
                $budget_limit = !empty($_POST['budget_limit']) ? floatval($_POST['budget_limit']) : NULL;
                $requires_approval = isset($_POST['requires_approval']) ? 1 : 0;

                $insert_query = "INSERT INTO expense_categories (category_name, category_type, description, color_code, budget_limit, requires_approval, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)";
                $insert_stmt = $conn->prepare($insert_query);
                $insert_stmt->bind_param("ssssdii", $category_name, $category_type, $description, $color_code, $budget_limit, $requires_approval, $user_id);
                
                if ($insert_stmt->execute()) {
                    $success_message = "Category added successfully!";
                } else {
                    $error_message = "Failed to add category.";
                }
                break;

            case 'update_category':
                $category_id = $_POST['category_id'];
                $category_name = trim($_POST['category_name']);
                $description = trim($_POST['description']);
                $color_code = $_POST['color_code'];
                $budget_limit = !empty($_POST['budget_limit']) ? floatval($_POST['budget_limit']) : NULL;
                $requires_approval = isset($_POST['requires_approval']) ? 1 : 0;

                $update_query = "UPDATE expense_categories SET category_name = ?, description = ?, color_code = ?, budget_limit = ?, requires_approval = ? WHERE category_id = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("sssdii", $category_name, $description, $color_code, $budget_limit, $requires_approval, $category_id);
                
                if ($update_stmt->execute()) {
                    $success_message = "Category updated successfully!";
                } else {
                    $error_message = "Failed to update category.";
                }
                break;

            case 'toggle_status':
                $category_id = $_POST['category_id'];
                $new_status = $_POST['new_status'];

                $toggle_query = "UPDATE expense_categories SET is_active = ? WHERE category_id = ?";
                $toggle_stmt = $conn->prepare($toggle_query);
                $toggle_stmt->bind_param("ii", $new_status, $category_id);
                
                if ($toggle_stmt->execute()) {
                    $success_message = $new_status ? "Category activated successfully!" : "Category deactivated successfully!";
                } else {
                    $error_message = "Failed to update category status.";
                }
                break;
        }
    }
}

// Get categories with expense counts
$categories_query = "SELECT ec.*, 
                            COUNT(e.expense_id) as total_expenses,
                            SUM(CASE WHEN e.status = 'PAID' THEN e.amount ELSE 0 END) as total_amount,
                            u.full_name as created_by_name
                     FROM expense_categories ec
                     LEFT JOIN expenses e ON ec.category_id = e.category_id
                     LEFT JOIN users u ON ec.created_by = u.user_id
                     GROUP BY ec.category_id
                     ORDER BY ec.category_type, ec.category_name";
$categories_result = $conn->query($categories_query);

// Get category statistics by type
$stats_query = "SELECT 
                    category_type,
                    COUNT(*) as category_count,
                    SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_count
                FROM expense_categories 
                GROUP BY category_type
                ORDER BY category_type";
$stats_result = $conn->query($stats_query);
$category_stats = [];
while ($row = $stats_result->fetch_assoc()) {
    $category_stats[$row['category_type']] = $row;
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Expense Categories - Personal Fund Management System')); ?>
    <?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>
        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, #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 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: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        /* 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 Type Badges */
        .type-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .type-shop { background: #fee2e2; color: #991b1b; }
        .type-company { background: #dbeafe; color: #1e40af; }
        .type-family { background: #dcfce7; color: #166534; }
        
        /* Status Toggle */
        .status-toggle {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }
        
        .status-toggle input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 24px;
        }
        
        .slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        
        input:checked + .slider {
            background-color: #10b981;
        }
        
        input:checked + .slider:before {
            transform: translateX(26px);
        }
        
        /* Color Picker */
        .color-picker {
            width: 40px;
            height: 40px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
        }
        
        /* 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: #6366f1;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 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-primary {
            background: #6366f1;
            color: white;
        }
        
        .btn-primary:hover {
            background: #4f46e5;
        }
        
        .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;
        }
        
        .btn-warning { background: #d97706; color: white; }
        .btn-warning:hover { background: #b45309; color: white; }
        
        /* Alert Messages */
        .alert {
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1.5rem;
            border: none;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
        }
        
        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
        }
        
        /* Modal Enhancements */
        .modal-content {
            border: none;
            border-radius: 12px;
            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;
        }
        
        /* 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;
            }
        }
    </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 Categories</h1>
                        <p class="page-subtitle">Manage expense categories for Shop, Company, and Family expenses</p>
                    </div>

                    <!-- Success/Error Messages -->
                    <?php if ($success_message): ?>
                        <div class="alert alert-success">
                            <i class="ph-check-circle me-2"></i>
                            <?php echo htmlspecialchars($success_message); ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($error_message): ?>
                        <div class="alert alert-danger">
                            <i class="ph-warning-circle me-2"></i>
                            <?php echo htmlspecialchars($error_message); ?>
                        </div>
                    <?php endif; ?>

                    <!-- Stats Row -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo ($category_stats['SHOP']['category_count'] ?? 0) + ($category_stats['COMPANY']['category_count'] ?? 0) + ($category_stats['FAMILY']['category_count'] ?? 0); ?></div>
                            <div class="stat-label">Total Categories</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $category_stats['SHOP']['category_count'] ?? 0; ?></div>
                            <div class="stat-label">Shop Categories</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $category_stats['COMPANY']['category_count'] ?? 0; ?></div>
                            <div class="stat-label">Company Categories</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $category_stats['FAMILY']['category_count'] ?? 0; ?></div>
                            <div class="stat-label">Family Categories</div>
                        </div>
                    </div>

                    <!-- Add Category Form -->
                    <div class="form-card">
                        <h3 style="margin-bottom: 1.5rem; color: #1e293b; font-weight: 600;">Add New Category</h3>
                        <form method="POST">
                            <input type="hidden" name="action" value="add_category">
                            <div class="row">
                                <div class="col-md-4">
                                    <label class="form-label">Category Name</label>
                                    <input type="text" class="form-control" name="category_name" required placeholder="Enter category name">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Category Type</label>
                                    <select class="form-select" name="category_type" required>
                                        <option value="">Select Type</option>
                                        <option value="SHOP">Shop Expenses</option>
                                        <option value="COMPANY">Company Expenses</option>
                                        <option value="FAMILY">Family Expenses</option>
                                    </select>
                                </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-md-3">
                                    <label class="form-label">Budget Limit (Optional)</label>
                                    <input type="number" class="form-control" name="budget_limit" step="0.01" placeholder="Monthly limit">
                                </div>
                            </div>
                            <div class="row mt-3">
                                <div class="col-md-8">
                                    <label class="form-label">Description</label>
                                    <input type="text" class="form-control" name="description" placeholder="Brief description of this category">
                                </div>
                                <div class="col-md-4 d-flex align-items-end">
                                    <div class="form-check me-3">
                                        <input class="form-check-input" type="checkbox" name="requires_approval" id="requiresApproval">
                                        <label class="form-check-label" for="requiresApproval">
                                            Requires Approval
                                        </label>
                                    </div>
                                    <button type="submit" class="btn btn-primary">
                                        <i class="ph-plus me-1"></i> Add Category
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Categories Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Expense Categories</h3>
                        </div>
                        
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Category</th>
                                    <th>Type</th>
                                    <th>Description</th>
                                    <th>Budget Limit</th>
                                    <th>Total Expenses</th>
                                    <th>Total Amount</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($category = $categories_result->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div style="width: 20px; height: 20px; background: <?php echo $category['color_code']; ?>; border-radius: 4px; margin-right: 0.75rem;"></div>
                                            <div>
                                                <div style="font-weight: 600; color: #1e293b;">
                                                    <?php echo htmlspecialchars($category['category_name']); ?>
                                                </div>
                                                <?php if ($category['requires_approval']): ?>
                                                    <div style="color: #d97706; font-size: 0.75rem;">
                                                        <i class="ph-warning"></i> Requires Approval
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <?php 
                                        $type_class = match($category['category_type']) {
                                            'SHOP' => 'type-shop',
                                            'COMPANY' => 'type-company',
                                            'FAMILY' => 'type-family',
                                            default => 'type-shop'
                                        };
                                        ?>
                                        <span class="type-badge <?php echo $type_class; ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', strtolower($category['category_type']))); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span style="color: #64748b;">
                                            <?php echo htmlspecialchars($category['description'] ?: 'No description'); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($category['budget_limit']): ?>
                                            <span style="font-weight: 600; color: #1e293b;">
                                                KES <?php echo number_format($category['budget_limit']); ?>
                                            </span>
                                        <?php else: ?>
                                            <span style="color: #9ca3af;">No limit set</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span style="font-weight: 500; color: #1e293b;">
                                            <?php echo $category['total_expenses']; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span style="font-weight: 600; color: #1e293b;">
                                            KES <?php echo number_format($category['total_amount']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <form method="POST" style="display: inline;">
                                            <input type="hidden" name="action" value="toggle_status">
                                            <input type="hidden" name="category_id" value="<?php echo $category['category_id']; ?>">
                                            <input type="hidden" name="new_status" value="<?php echo $category['is_active'] ? 0 : 1; ?>">
                                            <label class="status-toggle">
                                                <input type="checkbox" <?php echo $category['is_active'] ? 'checked' : ''; ?> onchange="this.form.submit()">
                                                <span class="slider"></span>
                                            </label>
                                        </form>
                                    </td>
                                    <td>
                                        <button class="btn-action btn-warning" onclick="editCategory(<?php echo htmlspecialchars(json_encode($category)); ?>)">
                                            <i class="ph-pencil"></i>
                                        </button>
                                    </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">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="update_category">
                        <input type="hidden" name="category_id" id="edit_category_id">
                        
                        <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="row">
                            <div class="col-md-6">
                                <label class="form-label">Color</label>
                                <input type="color" class="form-control color-picker" name="color_code" id="edit_color_code">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Budget Limit</label>
                                <input type="number" class="form-control" name="budget_limit" id="edit_budget_limit" step="0.01">
                            </div>
                        </div>
                        
                        <div class="mb-3 mt-3">
                            <label class="form-label">Description</label>
                            <input type="text" class="form-control" name="description" id="edit_description">
                        </div>
                        
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="requires_approval" id="edit_requires_approval">
                            <label class="form-check-label" for="edit_requires_approval">
                                Requires Approval
                            </label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update 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) {
            document.getElementById('edit_category_id').value = category.category_id;
            document.getElementById('edit_category_name').value = category.category_name;
            document.getElementById('edit_color_code').value = category.color_code;
            document.getElementById('edit_budget_limit').value = category.budget_limit || '';
            document.getElementById('edit_description').value = category.description || '';
            document.getElementById('edit_requires_approval').checked = category.requires_approval == 1;
            
            new bootstrap.Modal(document.getElementById('editCategoryModal')).show();
        }
    </script>

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

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