<?php
/**
 * View Expense
 * LandSales Pro - Expense details
 */
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();
requireViewPermission('expenses');

$userId = $_SESSION['user_id'];
$expenseId = intval($_GET['id'] ?? 0);

if (!$expenseId) {
    header('Location: index.php');
    exit;
}

// Fetch expense with project and category info
$expense = db_fetch_one("SELECT e.*, p.name as project_name, c.name as category_name, c.color as category_color, c.icon as category_icon
    FROM expenses e
    LEFT JOIN projects p ON e.project_id = p.id
    LEFT JOIN expense_categories c ON e.category_id = c.id
    WHERE e.id = ? AND e.user_id = ?", 'ii', [$expenseId, $userId]);

if (!$expense) {
    $_SESSION['flash_error'] = "Expense not found";
    header('Location: index.php');
    exit;
}

// Legacy category labels (for backwards compatibility)
$legacyCategoryLabels = [
    'survey' => 'Survey', 'marketing' => 'Marketing', 'legal' => 'Legal',
    'infrastructure' => 'Infrastructure', 'utilities' => 'Utilities', 'staff' => 'Staff',
    'commission' => 'Commission', 'tax' => 'Tax', 'office' => 'Office',
    'transport' => 'Transport', 'other' => 'Other'
];

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

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete'])) {
    if (canManage('expenses')) {
        // Delete receipt file if exists
        if ($expense['receipt_image']) {
            $uploadDir = __DIR__ . '/../../uploads/expenses/';
            if (file_exists($uploadDir . $expense['receipt_image'])) {
                unlink($uploadDir . $expense['receipt_image']);
            }
        }

        db_execute("DELETE FROM expenses WHERE id = ? AND user_id = ?", 'ii', [$expenseId, $userId]);
        $_SESSION['flash_success'] = "Expense deleted successfully!";
        header('Location: index.php');
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View 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">Expense Details</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <?php if (canManage('expenses')): ?>
                <a href="edit.php?id=<?php echo $expenseId; ?>" class="btn btn-primary">
                    <i class="fas fa-edit"></i> Edit
                </a>
                <?php endif; ?>
            </div>
        </div>

        <div class="content-wrapper">
            <?php if (isset($_SESSION['flash_success'])): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <?php echo $_SESSION['flash_success']; unset($_SESSION['flash_success']); ?>
            </div>
            <?php endif; ?>

            <div class="expense-detail">
                <!-- Amount Card -->
                <div class="amount-card">
                    <div class="amount-header">
                        <span class="category-badge">
                            <?php if ($expense['category_icon']): ?><i class="fas <?php echo $expense['category_icon']; ?>"></i><?php endif; ?>
                            <?php echo htmlspecialchars($expense['category_name'] ?? $legacyCategoryLabels[$expense['category']] ?? 'Uncategorized'); ?>
                        </span>
                        <span class="expense-date">
                            <i class="fas fa-calendar"></i>
                            <?php echo date('F j, Y', strtotime($expense['expense_date'])); ?>
                        </span>
                    </div>
                    <div class="amount-value">
                        TZS <?php echo number_format($expense['amount']); ?>
                    </div>
                    <div class="amount-description">
                        <?php echo htmlspecialchars($expense['description']); ?>
                    </div>
                </div>

                <div class="details-grid">
                    <!-- Main Details -->
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-info-circle"></i> Details</h3>
                        </div>
                        <div class="card-body">
                            <div class="info-list">
                                <div class="info-row">
                                    <span class="info-label">Project</span>
                                    <span class="info-value">
                                        <?php if ($expense['project_name']): ?>
                                        <a href="../projects/view.php?id=<?php echo $expense['project_id']; ?>">
                                            <?php echo htmlspecialchars($expense['project_name']); ?>
                                        </a>
                                        <?php else: ?>
                                        <span class="text-muted">General Expense</span>
                                        <?php endif; ?>
                                    </span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Payment Method</span>
                                    <span class="info-value">
                                        <?php echo $paymentMethodLabels[$expense['payment_method']] ?? ucfirst($expense['payment_method']); ?>
                                    </span>
                                </div>
                                <?php if ($expense['reference_number']): ?>
                                <div class="info-row">
                                    <span class="info-label">Reference Number</span>
                                    <span class="info-value"><?php echo htmlspecialchars($expense['reference_number']); ?></span>
                                </div>
                                <?php endif; ?>
                                <div class="info-row">
                                    <span class="info-label">Created</span>
                                    <span class="info-value"><?php echo date('M j, Y \a\t g:i A', strtotime($expense['created_at'])); ?></span>
                                </div>
                                <?php if ($expense['updated_at'] && $expense['updated_at'] !== $expense['created_at']): ?>
                                <div class="info-row">
                                    <span class="info-label">Last Updated</span>
                                    <span class="info-value"><?php echo date('M j, Y \a\t g:i A', strtotime($expense['updated_at'])); ?></span>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Vendor Info -->
                    <?php if ($expense['vendor_name'] || $expense['vendor_phone']): ?>
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-store"></i> Vendor</h3>
                        </div>
                        <div class="card-body">
                            <div class="info-list">
                                <?php if ($expense['vendor_name']): ?>
                                <div class="info-row">
                                    <span class="info-label">Name</span>
                                    <span class="info-value"><?php echo htmlspecialchars($expense['vendor_name']); ?></span>
                                </div>
                                <?php endif; ?>
                                <?php if ($expense['vendor_phone']): ?>
                                <div class="info-row">
                                    <span class="info-label">Phone</span>
                                    <span class="info-value">
                                        <a href="tel:<?php echo htmlspecialchars($expense['vendor_phone']); ?>">
                                            <?php echo htmlspecialchars($expense['vendor_phone']); ?>
                                        </a>
                                    </span>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Receipt -->
                    <?php if ($expense['receipt_image']): ?>
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-receipt"></i> Receipt</h3>
                        </div>
                        <div class="card-body">
                            <?php
                            $receiptPath = SITE_URL . '/uploads/expenses/' . $expense['receipt_image'];
                            $extension = strtolower(pathinfo($expense['receipt_image'], PATHINFO_EXTENSION));
                            ?>
                            <?php if (in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp'])): ?>
                            <a href="<?php echo $receiptPath; ?>" target="_blank" class="receipt-image">
                                <img src="<?php echo $receiptPath; ?>" alt="Receipt">
                                <span class="view-full"><i class="fas fa-expand"></i> View Full</span>
                            </a>
                            <?php else: ?>
                            <a href="<?php echo $receiptPath; ?>" target="_blank" class="pdf-download">
                                <i class="fas fa-file-pdf"></i>
                                <span>View PDF Receipt</span>
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Notes -->
                    <?php if ($expense['notes']): ?>
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-sticky-note"></i> Notes</h3>
                        </div>
                        <div class="card-body">
                            <p class="notes-text"><?php echo nl2br(htmlspecialchars($expense['notes'])); ?></p>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Delete Button -->
                <?php if (canManage('expenses')): ?>
                <div class="danger-zone">
                    <h4>Danger Zone</h4>
                    <p>Once you delete this expense, there is no going back. Please be certain.</p>
                    <form method="POST" onsubmit="return confirm('Are you sure you want to delete this expense? This action cannot be undone.');">
                        <input type="hidden" name="delete" value="1">
                        <button type="submit" class="btn btn-danger">
                            <i class="fas fa-trash-alt"></i> Delete Expense
                        </button>
                    </form>
                </div>
                <?php endif; ?>
            </div>
        </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-danger { background: #dc2626; color: white; }
        .btn-danger:hover { background: #b91c1c; }

        .alert { padding: 1rem 1.25rem; border-radius: 8px; margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.75rem; }
        .alert-success { background: #dcfce7; border: 1px solid #bbf7d0; color: #166534; }

        .amount-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 16px; padding: 2rem; color: white; margin-bottom: 1.5rem; }
        .amount-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; }
        .category-badge { padding: 0.375rem 0.75rem; border-radius: 20px; font-size: 0.75rem; font-weight: 600; background: rgba(255,255,255,0.2); }
        .expense-date { display: flex; align-items: center; gap: 0.5rem; font-size: 0.875rem; opacity: 0.9; }
        .amount-value { font-size: 2.5rem; font-weight: 700; margin-bottom: 0.5rem; }
        .amount-description { font-size: 1.125rem; opacity: 0.9; }

        .details-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1.5rem; }

        .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; }
        .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; }

        .info-list { display: flex; flex-direction: column; gap: 1rem; }
        .info-row { display: flex; justify-content: space-between; padding-bottom: 0.75rem; border-bottom: 1px solid #f1f5f9; }
        .info-row:last-child { border-bottom: none; padding-bottom: 0; }
        .info-label { color: #64748b; font-size: 0.875rem; }
        .info-value { color: #1e293b; font-weight: 500; text-align: right; }
        .info-value a { color: #667eea; text-decoration: none; }
        .info-value a:hover { text-decoration: underline; }
        .text-muted { color: #94a3b8; }

        .receipt-image { display: block; position: relative; border-radius: 8px; overflow: hidden; }
        .receipt-image img { width: 100%; max-height: 300px; object-fit: contain; background: #f8fafc; }
        .receipt-image .view-full { position: absolute; bottom: 0; left: 0; right: 0; padding: 0.75rem; background: linear-gradient(transparent, rgba(0,0,0,0.7)); color: white; display: flex; align-items: center; justify-content: center; gap: 0.5rem; font-size: 0.875rem; }

        .pdf-download { display: flex; align-items: center; gap: 1rem; padding: 1.5rem; background: #fef2f2; border-radius: 8px; text-decoration: none; color: #dc2626; }
        .pdf-download i { font-size: 2.5rem; }
        .pdf-download span { font-weight: 500; }

        .notes-text { margin: 0; color: #475569; line-height: 1.6; }

        .danger-zone { background: #fef2f2; border: 1px solid #fecaca; border-radius: 12px; padding: 1.5rem; margin-top: 2rem; }
        .danger-zone h4 { margin: 0 0 0.5rem 0; color: #dc2626; }
        .danger-zone p { margin: 0 0 1rem 0; color: #991b1b; font-size: 0.875rem; }

        @media (max-width: 768px) {
            .amount-header { flex-direction: column; align-items: flex-start; gap: 0.5rem; }
            .amount-value { font-size: 2rem; }
            .details-grid { grid-template-columns: 1fr; }
        }
    </style>
</body>
</html>
