<?php
/**
 * Create Expense
 * LandSales Pro - Add new expense record
 */
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 = false;

// Get projects for dropdown
$projects = db_fetch_all("SELECT id, name FROM projects WHERE user_id = ? ORDER BY name", 'i', [$userId]);

// Get dynamic categories from database
$categories = db_fetch_all("SELECT * FROM expense_categories WHERE user_id = ? AND is_active = 1 ORDER BY sort_order, name", 'i', [$userId]);

// If no categories exist, seed defaults
if (empty($categories)) {
    $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'],
    ];
    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]);
    }
    $categories = db_fetch_all("SELECT * FROM expense_categories WHERE user_id = ? AND is_active = 1 ORDER BY sort_order, name", 'i', [$userId]);
}

// Payment method options
$paymentMethods = [
    'cash' => 'Cash',
    'bank_transfer' => 'Bank Transfer',
    'mobile_money' => 'Mobile Money',
    'cheque' => 'Cheque',
    'other' => 'Other'
];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $description = trim($_POST['description'] ?? '');
    $categoryId = !empty($_POST['category_id']) ? intval($_POST['category_id']) : null;
    $projectId = !empty($_POST['project_id']) ? intval($_POST['project_id']) : null;
    $amount = floatval($_POST['amount'] ?? 0);
    $expenseDate = $_POST['expense_date'] ?? date('Y-m-d');
    $paymentMethod = $_POST['payment_method'] ?? 'cash';
    $referenceNumber = trim($_POST['reference_number'] ?? '');
    $vendorName = trim($_POST['vendor_name'] ?? '');
    $vendorPhone = trim($_POST['vendor_phone'] ?? '');
    $notes = trim($_POST['notes'] ?? '');

    // Validation
    if (empty($description)) {
        $errors[] = "Description is required";
    }

    if ($amount <= 0) {
        $errors[] = "Amount must be greater than zero";
    }

    if (empty($expenseDate)) {
        $errors[] = "Expense date is required";
    }

    // Handle receipt image upload
    $receiptImage = null;
    if (isset($_FILES['receipt_image']) && $_FILES['receipt_image']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . '/../../uploads/expenses/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf'];
        $maxSize = 5 * 1024 * 1024; // 5MB

        $fileType = $_FILES['receipt_image']['type'];
        $fileSize = $_FILES['receipt_image']['size'];

        if (!in_array($fileType, $allowedTypes)) {
            $errors[] = "Invalid receipt file type. Allowed: JPEG, PNG, GIF, WebP, PDF";
        } elseif ($fileSize > $maxSize) {
            $errors[] = "Receipt file too large. Maximum size is 5MB";
        } else {
            $extension = pathinfo($_FILES['receipt_image']['name'], PATHINFO_EXTENSION);
            $filename = 'receipt_' . time() . '_' . bin2hex(random_bytes(8)) . '.' . $extension;

            if (move_uploaded_file($_FILES['receipt_image']['tmp_name'], $uploadDir . $filename)) {
                $receiptImage = $filename;
            } else {
                $errors[] = "Failed to upload receipt image";
            }
        }
    }

    if (empty($errors)) {
        $sql = "INSERT INTO expenses (user_id, project_id, category_id, description, amount, expense_date,
                payment_method, reference_number, vendor_name, vendor_phone, receipt_image, notes, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";

        $result = db_execute($sql, 'iiidsssssss', [
            $userId,
            $projectId,
            $categoryId,
            $description,
            $amount,
            $expenseDate,
            $paymentMethod,
            $referenceNumber ?: null,
            $vendorName ?: null,
            $vendorPhone ?: null,
            $receiptImage,
            $notes ?: null
        ]);

        if ($result) {
            $_SESSION['flash_success'] = "Expense added successfully!";
            header('Location: index.php');
            exit;
        } else {
            $errors[] = "Failed to save expense. Please try again.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Expense - <?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">Add Expense</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
            </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; ?>

            <form method="POST" enctype="multipart/form-data" class="form-card">
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-info-circle"></i> Expense Details</h3>
                    </div>
                    <div class="card-body">
                        <div class="form-grid">
                            <div class="form-group full-width">
                                <label for="description">Description <span class="required">*</span></label>
                                <input type="text" id="description" name="description" class="form-control"
                                       value="<?php echo htmlspecialchars($_POST['description'] ?? ''); ?>"
                                       placeholder="e.g., Survey fees for Phase 2" required>
                            </div>

                            <div class="form-group">
                                <label for="category_id">Category <span class="required">*</span></label>
                                <select id="category_id" name="category_id" class="form-control" required>
                                    <option value="">Select Category</option>
                                    <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo $cat['id']; ?>" <?php echo ($_POST['category_id'] ?? '') == $cat['id'] ? 'selected' : ''; ?>
                                            data-color="<?php echo $cat['color']; ?>" data-icon="<?php echo $cat['icon']; ?>">
                                        <?php echo htmlspecialchars($cat['name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                                <a href="categories.php" class="category-link"><i class="fas fa-plus"></i> Manage Categories</a>
                            </div>

                            <div class="form-group">
                                <label for="project_id">Project</label>
                                <select id="project_id" name="project_id" class="form-control">
                                    <option value="">General (No specific project)</option>
                                    <?php foreach ($projects as $project): ?>
                                    <option value="<?php echo $project['id']; ?>" <?php echo ($_POST['project_id'] ?? '') == $project['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($project['name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="form-group">
                                <label for="amount">Amount (TZS) <span class="required">*</span></label>
                                <input type="number" id="amount" name="amount" class="form-control"
                                       value="<?php echo $_POST['amount'] ?? ''; ?>"
                                       min="0" step="1" placeholder="0" required>
                            </div>

                            <div class="form-group">
                                <label for="expense_date">Expense Date <span class="required">*</span></label>
                                <input type="date" id="expense_date" name="expense_date" class="form-control"
                                       value="<?php echo $_POST['expense_date'] ?? date('Y-m-d'); ?>" required>
                            </div>

                            <div class="form-group">
                                <label for="payment_method">Payment Method</label>
                                <select id="payment_method" name="payment_method" class="form-control">
                                    <?php foreach ($paymentMethods as $key => $label): ?>
                                    <option value="<?php echo $key; ?>" <?php echo ($_POST['payment_method'] ?? 'cash') === $key ? 'selected' : ''; ?>>
                                        <?php echo $label; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="form-group">
                                <label for="reference_number">Reference Number</label>
                                <input type="text" id="reference_number" name="reference_number" class="form-control"
                                       value="<?php echo htmlspecialchars($_POST['reference_number'] ?? ''); ?>"
                                       placeholder="Invoice/Receipt number">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-store"></i> Vendor Information</h3>
                    </div>
                    <div class="card-body">
                        <div class="form-grid">
                            <div class="form-group">
                                <label for="vendor_name">Vendor Name</label>
                                <input type="text" id="vendor_name" name="vendor_name" class="form-control"
                                       value="<?php echo htmlspecialchars($_POST['vendor_name'] ?? ''); ?>"
                                       placeholder="Company or person name">
                            </div>

                            <div class="form-group">
                                <label for="vendor_phone">Vendor Phone</label>
                                <input type="tel" id="vendor_phone" name="vendor_phone" class="form-control"
                                       value="<?php echo htmlspecialchars($_POST['vendor_phone'] ?? ''); ?>"
                                       placeholder="+255...">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-file-upload"></i> Receipt & Notes</h3>
                    </div>
                    <div class="card-body">
                        <div class="form-grid">
                            <div class="form-group">
                                <label for="receipt_image">Receipt Image/PDF</label>
                                <div class="file-upload">
                                    <input type="file" id="receipt_image" name="receipt_image"
                                           accept="image/*,application/pdf">
                                    <label for="receipt_image" class="file-upload-label">
                                        <i class="fas fa-cloud-upload-alt"></i>
                                        <span>Choose file or drag & drop</span>
                                        <small>Max 5MB - JPEG, PNG, GIF, WebP, PDF</small>
                                    </label>
                                    <div class="file-preview" id="filePreview"></div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="notes">Notes</label>
                                <textarea id="notes" name="notes" class="form-control" rows="4"
                                          placeholder="Additional notes..."><?php echo htmlspecialchars($_POST['notes'] ?? ''); ?></textarea>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-actions">
                    <a href="index.php" class="btn btn-outline">Cancel</a>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Save Expense
                    </button>
                </div>
            </form>
        </div>
    </div>

    <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; }
        .btn-primary:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4); }

        .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 ul { margin: 0; padding-left: 1rem; }
        .alert li { margin: 0.25rem 0; }

        .card { background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); margin-bottom: 1.5rem; overflow: hidden; }
        .card-header { padding: 1.25rem 1.5rem; border-bottom: 1px solid #f1f5f9; }
        .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; }
        .card-body { padding: 1.5rem; }

        .form-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1.5rem; }
        .form-group { display: flex; flex-direction: column; gap: 0.5rem; }
        .form-group.full-width { grid-column: span 2; }
        .form-group label { font-weight: 500; color: #374151; font-size: 0.875rem; }
        .required { color: #ef4444; }

        .form-control { padding: 0.75rem 1rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.875rem; transition: all 0.2s; }
        .form-control:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }
        .category-link { display: inline-block; margin-top: 0.5rem; font-size: 0.8rem; color: #667eea; text-decoration: none; }
        .category-link:hover { text-decoration: underline; }
        textarea.form-control { resize: vertical; min-height: 100px; }

        .file-upload { position: relative; }
        .file-upload input[type="file"] { position: absolute; opacity: 0; width: 100%; height: 100%; cursor: pointer; z-index: 2; }
        .file-upload-label { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 2rem; border: 2px dashed #e2e8f0; border-radius: 8px; background: #f8fafc; cursor: pointer; transition: all 0.2s; text-align: center; }
        .file-upload-label:hover { border-color: #667eea; background: #f1f5f9; }
        .file-upload-label i { font-size: 2rem; color: #94a3b8; margin-bottom: 0.5rem; }
        .file-upload-label span { color: #64748b; font-weight: 500; }
        .file-upload-label small { color: #94a3b8; margin-top: 0.25rem; }
        .file-preview { margin-top: 0.5rem; }
        .file-preview img { max-width: 150px; max-height: 150px; border-radius: 8px; }

        .form-actions { display: flex; justify-content: flex-end; gap: 1rem; margin-top: 1rem; }

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

    <script>
        document.getElementById('receipt_image').addEventListener('change', function(e) {
            const preview = document.getElementById('filePreview');
            const file = e.target.files[0];

            if (file) {
                const label = document.querySelector('.file-upload-label span');
                label.textContent = file.name;

                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        preview.innerHTML = `<img src="${e.target.result}" alt="Preview">`;
                    };
                    reader.readAsDataURL(file);
                } else if (file.type === 'application/pdf') {
                    preview.innerHTML = '<i class="fas fa-file-pdf" style="font-size: 3rem; color: #dc2626;"></i>';
                }
            }
        });
    </script>
</body>
</html>
