<?php
/**
 * Expense Categories
 * LandSales Pro - Manage expense categories
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();
requireManagePermission('expenses');

$userId = $_SESSION['user_id'];
$errors = [];
$success = '';

// Default categories to seed for new users
$defaultCategories = [
    ['name' => 'Survey', 'slug' => 'survey', 'color' => '#1e40af', 'icon' => 'fa-compass'],
    ['name' => 'Marketing', 'slug' => 'marketing', 'color' => '#9d174d', 'icon' => 'fa-bullhorn'],
    ['name' => 'Legal', 'slug' => 'legal', 'color' => '#4338ca', 'icon' => 'fa-gavel'],
    ['name' => 'Infrastructure', 'slug' => 'infrastructure', 'color' => '#92400e', 'icon' => 'fa-road'],
    ['name' => 'Utilities', 'slug' => 'utilities', 'color' => '#0f766e', 'icon' => 'fa-bolt'],
    ['name' => 'Staff', 'slug' => 'staff', 'color' => '#7c3aed', 'icon' => 'fa-users'],
    ['name' => 'Commission', 'slug' => 'commission', 'color' => '#059669', 'icon' => 'fa-percent'],
    ['name' => 'Tax', 'slug' => 'tax', 'color' => '#991b1b', 'icon' => 'fa-file-invoice-dollar'],
    ['name' => 'Office', 'slug' => 'office', 'color' => '#475569', 'icon' => 'fa-building'],
    ['name' => 'Transport', 'slug' => 'transport', 'color' => '#c2410c', 'icon' => 'fa-car'],
    ['name' => 'Other', 'slug' => 'other', 'color' => '#64748b', 'icon' => 'fa-tag'],
];

// Check if user has any categories, if not, seed defaults
$categoryCount = db_fetch_one("SELECT COUNT(*) as count FROM expense_categories WHERE user_id = ?", 'i', [$userId])['count'];
if ($categoryCount == 0) {
    foreach ($defaultCategories as $index => $cat) {
        db_execute("INSERT INTO expense_categories (user_id, name, slug, color, icon, is_default, sort_order) VALUES (?, ?, ?, ?, ?, 1, ?)",
            'issssi', [$userId, $cat['name'], $cat['slug'], $cat['color'], $cat['icon'], $index]);
    }
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $name = trim($_POST['name'] ?? '');
        $color = $_POST['color'] ?? '#64748b';
        $icon = $_POST['icon'] ?? 'fa-tag';

        if (empty($name)) {
            $errors[] = "Category name is required";
        } else {
            $slug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $name));

            // Check if slug exists
            $exists = db_fetch_one("SELECT id FROM expense_categories WHERE user_id = ? AND slug = ?", 'is', [$userId, $slug]);
            if ($exists) {
                $errors[] = "A category with this name already exists";
            } else {
                $maxOrder = db_fetch_one("SELECT MAX(sort_order) as max_order FROM expense_categories WHERE user_id = ?", 'i', [$userId])['max_order'] ?? 0;

                $result = db_execute("INSERT INTO expense_categories (user_id, name, slug, color, icon, sort_order) VALUES (?, ?, ?, ?, ?, ?)",
                    'issssi', [$userId, $name, $slug, $color, $icon, $maxOrder + 1]);

                if ($result) {
                    $success = "Category added successfully!";
                } else {
                    $errors[] = "Failed to add category";
                }
            }
        }
    }

    if ($action === 'edit') {
        $catId = intval($_POST['category_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $color = $_POST['color'] ?? '#64748b';
        $icon = $_POST['icon'] ?? 'fa-tag';
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        if (empty($name)) {
            $errors[] = "Category name is required";
        } else {
            $slug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $name));

            // Check if slug exists for another category
            $exists = db_fetch_one("SELECT id FROM expense_categories WHERE user_id = ? AND slug = ? AND id != ?", 'isi', [$userId, $slug, $catId]);
            if ($exists) {
                $errors[] = "A category with this name already exists";
            } else {
                $result = db_execute("UPDATE expense_categories SET name = ?, slug = ?, color = ?, icon = ?, is_active = ? WHERE id = ? AND user_id = ?",
                    'ssssiis', [$name, $slug, $color, $icon, $isActive, $catId, $userId]);

                if ($result) {
                    $success = "Category updated successfully!";
                } else {
                    $errors[] = "Failed to update category";
                }
            }
        }
    }

    if ($action === 'delete') {
        $catId = intval($_POST['category_id'] ?? 0);

        // Check if category is in use
        $inUse = db_fetch_one("SELECT COUNT(*) as count FROM expenses WHERE category_id = ? AND user_id = ?", 'ii', [$catId, $userId])['count'];

        if ($inUse > 0) {
            $errors[] = "Cannot delete category - it is used by {$inUse} expense(s). Deactivate it instead.";
        } else {
            $result = db_execute("DELETE FROM expense_categories WHERE id = ? AND user_id = ?", 'ii', [$catId, $userId]);
            if ($result) {
                $success = "Category deleted successfully!";
            } else {
                $errors[] = "Failed to delete category";
            }
        }
    }
}

// Fetch categories
$categories = db_fetch_all("SELECT c.*,
    (SELECT COUNT(*) FROM expenses WHERE category_id = c.id) as expense_count
    FROM expense_categories c
    WHERE c.user_id = ?
    ORDER BY c.sort_order, c.name", 'i', [$userId]);

// Available icons
$availableIcons = [
    'fa-tag' => 'Tag',
    'fa-compass' => 'Compass',
    'fa-bullhorn' => 'Bullhorn',
    'fa-gavel' => 'Legal',
    'fa-road' => 'Road',
    'fa-bolt' => 'Bolt',
    'fa-users' => 'Users',
    'fa-percent' => 'Percent',
    'fa-file-invoice-dollar' => 'Invoice',
    'fa-building' => 'Building',
    'fa-car' => 'Car',
    'fa-truck' => 'Truck',
    'fa-tools' => 'Tools',
    'fa-wrench' => 'Wrench',
    'fa-hard-hat' => 'Hard Hat',
    'fa-seedling' => 'Seedling',
    'fa-water' => 'Water',
    'fa-phone' => 'Phone',
    'fa-wifi' => 'WiFi',
    'fa-print' => 'Print',
    'fa-laptop' => 'Laptop',
    'fa-gas-pump' => 'Fuel',
    'fa-utensils' => 'Food',
    'fa-plane' => 'Travel',
    'fa-hotel' => 'Hotel',
    'fa-handshake' => 'Handshake',
    'fa-shield-alt' => 'Security',
    'fa-first-aid' => 'Medical',
    'fa-graduation-cap' => 'Training',
    'fa-chart-line' => 'Analytics',
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Expense Categories - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Expense Categories</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back to Expenses
                </a>
                <button type="button" class="btn btn-primary" onclick="openAddModal()">
                    <i class="fas fa-plus"></i> Add Category
                </button>
            </div>
        </div>

        <div class="content-wrapper">
            <?php if (!empty($errors)): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i>
                <ul>
                    <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php endif; ?>

            <?php if ($success): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <?php echo htmlspecialchars($success); ?>
            </div>
            <?php endif; ?>

            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-tags"></i> Categories</h3>
                    <span class="category-count"><?php echo count($categories); ?> categories</span>
                </div>
                <div class="categories-grid">
                    <?php foreach ($categories as $cat): ?>
                    <div class="category-card <?php echo !$cat['is_active'] ? 'inactive' : ''; ?>">
                        <div class="category-icon" style="background-color: <?php echo $cat['color']; ?>">
                            <i class="fas <?php echo $cat['icon']; ?>"></i>
                        </div>
                        <div class="category-info">
                            <h4><?php echo htmlspecialchars($cat['name']); ?></h4>
                            <span class="expense-count"><?php echo $cat['expense_count']; ?> expenses</span>
                            <?php if (!$cat['is_active']): ?>
                            <span class="status-inactive">Inactive</span>
                            <?php endif; ?>
                        </div>
                        <div class="category-actions">
                            <button type="button" class="btn-icon" title="Edit"
                                    onclick="openEditModal(<?php echo htmlspecialchars(json_encode($cat)); ?>)">
                                <i class="fas fa-edit"></i>
                            </button>
                            <?php if ($cat['expense_count'] == 0 && !$cat['is_default']): ?>
                            <button type="button" class="btn-icon btn-danger" title="Delete"
                                    onclick="deleteCategory(<?php echo $cat['id']; ?>, '<?php echo htmlspecialchars($cat['name']); ?>')">
                                <i class="fas fa-trash"></i>
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Category Modal -->
    <div class="modal-overlay" id="addModal">
        <div class="modal">
            <div class="modal-header">
                <h3>Add Category</h3>
                <button type="button" class="modal-close" onclick="closeModal('addModal')">&times;</button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="add">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="add_name">Category Name <span class="required">*</span></label>
                        <input type="text" id="add_name" name="name" class="form-control" required placeholder="e.g., Equipment">
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="add_color">Color</label>
                            <input type="color" id="add_color" name="color" class="form-control-color" value="#64748b">
                        </div>
                        <div class="form-group">
                            <label for="add_icon">Icon</label>
                            <select id="add_icon" name="icon" class="form-control">
                                <?php foreach ($availableIcons as $icon => $label): ?>
                                <option value="<?php echo $icon; ?>"><?php echo $label; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="icon-preview">
                        <span>Preview:</span>
                        <div class="preview-icon" id="addPreviewIcon" style="background-color: #64748b">
                            <i class="fas fa-tag"></i>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline" onclick="closeModal('addModal')">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Category</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Category Modal -->
    <div class="modal-overlay" id="editModal">
        <div class="modal">
            <div class="modal-header">
                <h3>Edit Category</h3>
                <button type="button" class="modal-close" onclick="closeModal('editModal')">&times;</button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="edit">
                <input type="hidden" name="category_id" id="edit_category_id">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="edit_name">Category Name <span class="required">*</span></label>
                        <input type="text" id="edit_name" name="name" class="form-control" required>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="edit_color">Color</label>
                            <input type="color" id="edit_color" name="color" class="form-control-color">
                        </div>
                        <div class="form-group">
                            <label for="edit_icon">Icon</label>
                            <select id="edit_icon" name="icon" class="form-control">
                                <?php foreach ($availableIcons as $icon => $label): ?>
                                <option value="<?php echo $icon; ?>"><?php echo $label; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="icon-preview">
                        <span>Preview:</span>
                        <div class="preview-icon" id="editPreviewIcon">
                            <i class="fas fa-tag"></i>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="checkbox-label">
                            <input type="checkbox" name="is_active" id="edit_is_active" value="1">
                            <span>Active (visible when adding expenses)</span>
                        </label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline" onclick="closeModal('editModal')">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Changes</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Form (hidden) -->
    <form id="deleteForm" method="POST" style="display: none;">
        <input type="hidden" name="action" value="delete">
        <input type="hidden" name="category_id" id="delete_category_id">
    </form>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .header-actions { display: flex; gap: 0.75rem; }
        .btn { padding: 0.625rem 1.25rem; border-radius: 8px; font-weight: 500; text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; transition: all 0.2s; border: none; cursor: pointer; font-size: 0.875rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .alert { padding: 1rem 1.25rem; border-radius: 8px; margin-bottom: 1.5rem; display: flex; gap: 0.75rem; }
        .alert-danger { background: #fef2f2; border: 1px solid #fecaca; color: #dc2626; }
        .alert-success { background: #dcfce7; border: 1px solid #bbf7d0; color: #166534; }
        .alert ul { margin: 0; padding-left: 1rem; }

        .card { background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .card-header { padding: 1.25rem 1.5rem; border-bottom: 1px solid #f1f5f9; display: flex; justify-content: space-between; align-items: center; }
        .card-header h3 { margin: 0; font-size: 1rem; font-weight: 600; color: #1e293b; display: flex; align-items: center; gap: 0.5rem; }
        .card-header h3 i { color: #667eea; }
        .category-count { font-size: 0.875rem; color: #64748b; }

        .categories-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 1rem; padding: 1.5rem; }

        .category-card { display: flex; align-items: center; gap: 1rem; padding: 1rem; background: #f8fafc; border-radius: 10px; transition: all 0.2s; }
        .category-card:hover { background: #f1f5f9; }
        .category-card.inactive { opacity: 0.6; }

        .category-icon { width: 48px; height: 48px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-size: 1.25rem; flex-shrink: 0; }

        .category-info { flex: 1; }
        .category-info h4 { margin: 0 0 0.25rem 0; font-size: 0.95rem; color: #1e293b; }
        .expense-count { font-size: 0.8rem; color: #64748b; }
        .status-inactive { display: inline-block; margin-left: 0.5rem; padding: 0.125rem 0.5rem; background: #fee2e2; color: #991b1b; border-radius: 4px; font-size: 0.7rem; }

        .category-actions { display: flex; gap: 0.5rem; }
        .btn-icon { width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; color: #64748b; background: white; border: 1px solid #e2e8f0; cursor: pointer; transition: all 0.2s; }
        .btn-icon:hover { background: #667eea; color: white; border-color: #667eea; }
        .btn-icon.btn-danger:hover { background: #dc2626; border-color: #dc2626; }

        /* Modal Styles */
        .modal-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 2000; align-items: center; justify-content: center; }
        .modal-overlay.active { display: flex; }
        .modal { background: white; border-radius: 12px; width: 100%; max-width: 450px; max-height: 90vh; overflow: auto; }
        .modal-header { padding: 1.25rem 1.5rem; border-bottom: 1px solid #f1f5f9; display: flex; justify-content: space-between; align-items: center; }
        .modal-header h3 { margin: 0; font-size: 1.125rem; }
        .modal-close { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #94a3b8; }
        .modal-body { padding: 1.5rem; }
        .modal-footer { padding: 1rem 1.5rem; border-top: 1px solid #f1f5f9; display: flex; justify-content: flex-end; gap: 0.75rem; }

        .form-group { margin-bottom: 1rem; }
        .form-group label { display: block; margin-bottom: 0.5rem; font-weight: 500; color: #374151; font-size: 0.875rem; }
        .required { color: #ef4444; }
        .form-control { width: 100%; padding: 0.75rem 1rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.875rem; box-sizing: border-box; }
        .form-control:focus { outline: none; border-color: #667eea; }
        .form-control-color { width: 60px; height: 40px; padding: 4px; border: 1px solid #e2e8f0; border-radius: 8px; cursor: pointer; }

        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }

        .icon-preview { display: flex; align-items: center; gap: 1rem; padding: 1rem; background: #f8fafc; border-radius: 8px; margin-bottom: 1rem; }
        .icon-preview span { color: #64748b; font-size: 0.875rem; }
        .preview-icon { width: 48px; height: 48px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-size: 1.25rem; }

        .checkbox-label { display: flex; align-items: center; gap: 0.5rem; cursor: pointer; }
        .checkbox-label input { width: 18px; height: 18px; cursor: pointer; }
        .checkbox-label span { font-size: 0.875rem; color: #475569; }

        @media (max-width: 768px) {
            .categories-grid { grid-template-columns: 1fr; }
            .form-row { grid-template-columns: 1fr; }
        }
    </style>

    <script>
        function openAddModal() {
            document.getElementById('addModal').classList.add('active');
        }

        function openEditModal(category) {
            document.getElementById('edit_category_id').value = category.id;
            document.getElementById('edit_name').value = category.name;
            document.getElementById('edit_color').value = category.color;
            document.getElementById('edit_icon').value = category.icon;
            document.getElementById('edit_is_active').checked = category.is_active == 1;

            updatePreview('edit', category.color, category.icon);
            document.getElementById('editModal').classList.add('active');
        }

        function closeModal(modalId) {
            document.getElementById(modalId).classList.remove('active');
        }

        function deleteCategory(id, name) {
            if (confirm('Are you sure you want to delete the category "' + name + '"?')) {
                document.getElementById('delete_category_id').value = id;
                document.getElementById('deleteForm').submit();
            }
        }

        function updatePreview(prefix, color, icon) {
            const previewEl = document.getElementById(prefix + 'PreviewIcon');
            previewEl.style.backgroundColor = color;
            previewEl.innerHTML = '<i class="fas ' + icon + '"></i>';
        }

        // Add preview updates
        document.getElementById('add_color').addEventListener('input', function() {
            updatePreview('add', this.value, document.getElementById('add_icon').value);
        });
        document.getElementById('add_icon').addEventListener('change', function() {
            updatePreview('add', document.getElementById('add_color').value, this.value);
        });
        document.getElementById('edit_color').addEventListener('input', function() {
            updatePreview('edit', this.value, document.getElementById('edit_icon').value);
        });
        document.getElementById('edit_icon').addEventListener('change', function() {
            updatePreview('edit', document.getElementById('edit_color').value, this.value);
        });

        // Close modal on overlay click
        document.querySelectorAll('.modal-overlay').forEach(overlay => {
            overlay.addEventListener('click', function(e) {
                if (e.target === this) {
                    this.classList.remove('active');
                }
            });
        });
    </script>
</body>
</html>
