<?php
/**
 * Sales List
 * LandSales Pro - Manage sales records
 */
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();

$userId = $_SESSION['user_id'];

// Filters
$statusFilter = $_GET['status'] ?? 'all';
$projectFilter = $_GET['project'] ?? '';

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

// Build query
$whereClause = "WHERE s.user_id = ?";
$params = [$userId];
$types = 'i';

if ($statusFilter !== 'all') {
    $whereClause .= " AND s.status = ?";
    $params[] = $statusFilter;
    $types .= 's';
}

if ($projectFilter) {
    $whereClause .= " AND p.project_id = ?";
    $params[] = intval($projectFilter);
    $types .= 'i';
}

// Pagination
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

$total = db_fetch_one("SELECT COUNT(*) as count FROM sales s JOIN plots p ON s.plot_id = p.id {$whereClause}", $types, $params)['count'];
$totalPages = ceil($total / $perPage);

$sales = db_fetch_all("SELECT s.*, b.full_name as buyer_name, b.phone as buyer_phone,
    p.plot_number, pr.name as project_name,
    (SELECT COALESCE(SUM(amount), 0) FROM payments WHERE sale_id = s.id AND status = 'confirmed') as total_paid
    FROM sales s
    JOIN buyers b ON s.buyer_id = b.id
    JOIN plots p ON s.plot_id = p.id
    JOIN projects pr ON p.project_id = pr.id
    {$whereClause}
    ORDER BY s.sale_date DESC
    LIMIT {$perPage} OFFSET {$offset}", $types, $params);

// Stats
$stats = db_fetch_one("SELECT
    COUNT(*) as total_sales,
    COALESCE(SUM(total_price), 0) as total_value,
    COALESCE(SUM((SELECT COALESCE(SUM(amount), 0) FROM payments WHERE sale_id = sales.id AND status = 'confirmed')), 0) as total_collected
    FROM sales WHERE user_id = ? AND status = 'active'", 'i', [$userId]);

$pendingBalance = $stats['total_value'] - $stats['total_collected'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sales - <?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">
        <?php
        $pageTitle = 'Sales';
        $headerActions = '<a href="create.php" class="btn btn-primary"><i class="fas fa-plus"></i> Record Sale</a>';
        include '../includes/header.php';
        ?>

        <div class="content-wrapper">
            <!-- Stats -->
            <div class="stats-row">
                <div class="stat-mini">
                    <i class="fas fa-handshake"></i>
                    <div>
                        <div class="stat-value"><?php echo number_format($stats['total_sales']); ?></div>
                        <div class="stat-label">Total Sales</div>
                    </div>
                </div>
                <div class="stat-mini success">
                    <i class="fas fa-chart-line"></i>
                    <div>
                        <div class="stat-value">TZS <?php echo formatMoney($stats['total_value']); ?></div>
                        <div class="stat-label">Total Value</div>
                    </div>
                </div>
                <div class="stat-mini info">
                    <i class="fas fa-money-bill-wave"></i>
                    <div>
                        <div class="stat-value">TZS <?php echo formatMoney($stats['total_collected']); ?></div>
                        <div class="stat-label">Collected</div>
                    </div>
                </div>
                <div class="stat-mini warning">
                    <i class="fas fa-clock"></i>
                    <div>
                        <div class="stat-value">TZS <?php echo formatMoney($pendingBalance); ?></div>
                        <div class="stat-label">Pending</div>
                    </div>
                </div>
            </div>

            <!-- Filters -->
            <div class="filters-card">
                <form class="filters-form" method="GET">
                    <div class="filter-group">
                        <label>Status</label>
                        <select name="status" class="form-control" onchange="this.form.submit()">
                            <option value="all">All Status</option>
                            <option value="active" <?php echo $statusFilter === 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="completed" <?php echo $statusFilter === 'completed' ? 'selected' : ''; ?>>Completed</option>
                            <option value="cancelled" <?php echo $statusFilter === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label>Project</label>
                        <select name="project" class="form-control" onchange="this.form.submit()">
                            <option value="">All Projects</option>
                            <?php foreach ($projects as $project): ?>
                            <option value="<?php echo $project['id']; ?>" <?php echo $projectFilter == $project['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($project['name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </form>
            </div>

            <!-- Table -->
            <div class="card">
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Sale #</th>
                                <th>Buyer</th>
                                <th>Plot</th>
                                <th>Total Price</th>
                                <th>Paid</th>
                                <th>Balance</th>
                                <th>Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($sales)): ?>
                            <tr>
                                <td colspan="8" class="empty-row">
                                    <div class="empty-state">
                                        <i class="fas fa-handshake"></i>
                                        <p>No sales recorded yet</p>
                                        <a href="create.php" class="btn btn-primary btn-sm">Record First Sale</a>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($sales as $sale):
                                $balance = $sale['total_price'] - $sale['total_paid'];
                                $paidPercent = $sale['total_price'] > 0 ? ($sale['total_paid'] / $sale['total_price']) * 100 : 0;
                            ?>
                            <tr>
                                <td>
                                    <span class="sale-number"><?php echo $sale['sale_number']; ?></span>
                                </td>
                                <td>
                                    <div class="buyer-info">
                                        <div class="buyer-name"><?php echo htmlspecialchars($sale['buyer_name']); ?></div>
                                        <div class="buyer-phone"><?php echo $sale['buyer_phone']; ?></div>
                                    </div>
                                </td>
                                <td>
                                    <div class="plot-info">
                                        <div class="plot-number">Plot <?php echo $sale['plot_number']; ?></div>
                                        <div class="project-name"><?php echo htmlspecialchars($sale['project_name']); ?></div>
                                    </div>
                                </td>
                                <td>TZS <?php echo number_format($sale['total_price']); ?></td>
                                <td>
                                    <div class="paid-info">
                                        <span class="text-success">TZS <?php echo number_format($sale['total_paid']); ?></span>
                                        <div class="progress-mini">
                                            <div class="progress-fill" style="width: <?php echo $paidPercent; ?>%"></div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <?php if ($balance > 0): ?>
                                    <span class="text-warning">TZS <?php echo number_format($balance); ?></span>
                                    <?php else: ?>
                                    <span class="badge badge-success">Paid</span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo date('M j, Y', strtotime($sale['sale_date'])); ?></td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="view.php?id=<?php echo $sale['id']; ?>" class="btn-icon" title="View">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <?php if ($balance > 0): ?>
                                        <a href="../payments/create.php?sale_id=<?php echo $sale['id']; ?>" class="btn-icon success" title="Record Payment">
                                            <i class="fas fa-money-bill-wave"></i>
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($totalPages > 1): ?>
                <div class="pagination-wrapper">
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                        <a href="?page=<?php echo $page - 1; ?>&status=<?php echo $statusFilter; ?>&project=<?php echo $projectFilter; ?>" class="page-link">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                        <?php endif; ?>

                        <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                        <a href="?page=<?php echo $i; ?>&status=<?php echo $statusFilter; ?>&project=<?php echo $projectFilter; ?>"
                           class="page-link <?php echo $i === $page ? 'active' : ''; ?>">
                            <?php echo $i; ?>
                        </a>
                        <?php endfor; ?>

                        <?php if ($page < $totalPages): ?>
                        <a href="?page=<?php echo $page + 1; ?>&status=<?php echo $statusFilter; ?>&project=<?php echo $projectFilter; ?>" class="page-link">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </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-sm { padding: 0.5rem 0.875rem; font-size: 0.8rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .stats-row { display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap; }
        .stat-mini { flex: 1; min-width: 180px; padding: 1rem; background: white; border-radius: 10px; display: flex; align-items: center; gap: 0.75rem; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .stat-mini i { width: 40px; height: 40px; background: #f1f5f9; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: #64748b; }
        .stat-mini.success { border-left: 3px solid #22c55e; }
        .stat-mini.success i { background: #dcfce7; color: #16a34a; }
        .stat-mini.info { border-left: 3px solid #3b82f6; }
        .stat-mini.info i { background: #dbeafe; color: #2563eb; }
        .stat-mini.warning { border-left: 3px solid #f59e0b; }
        .stat-mini.warning i { background: #fef3c7; color: #d97706; }
        .stat-mini .stat-value { font-size: 1.1rem; font-weight: 700; color: #1e293b; }
        .stat-mini .stat-label { font-size: 0.75rem; color: #64748b; }

        .filters-card { background: white; border-radius: 10px; padding: 1rem; margin-bottom: 1.5rem; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .filters-form { display: flex; gap: 1rem; }
        .filter-group { display: flex; align-items: center; gap: 0.5rem; }
        .filter-group label { font-size: 0.85rem; font-weight: 500; color: #64748b; }
        .form-control { padding: 0.5rem 0.75rem; border: 1px solid #e2e8f0; border-radius: 6px; font-size: 0.85rem; }

        .card { background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .table-responsive { overflow-x: auto; }
        .data-table { width: 100%; border-collapse: collapse; }
        .data-table th, .data-table td { padding: 1rem; text-align: left; border-bottom: 1px solid #f1f5f9; }
        .data-table th { background: #f8fafc; font-weight: 600; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; }
        .data-table tbody tr:hover { background: #f8fafc; }

        .sale-number { font-family: monospace; font-weight: 600; color: #667eea; }
        .buyer-name { font-weight: 500; color: #1e293b; }
        .buyer-phone { font-size: 0.8rem; color: #64748b; }
        .plot-number { font-weight: 500; color: #1e293b; }
        .project-name { font-size: 0.8rem; color: #64748b; }

        .paid-info { display: flex; flex-direction: column; gap: 0.25rem; }
        .progress-mini { width: 60px; height: 4px; background: #e2e8f0; border-radius: 2px; overflow: hidden; }
        .progress-fill { height: 100%; background: #22c55e; }

        .text-success { color: #16a34a; }
        .text-warning { color: #d97706; }
        .badge { padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.7rem; font-weight: 600; }
        .badge-success { background: #dcfce7; color: #16a34a; }

        .action-buttons { 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: #f1f5f9; text-decoration: none; transition: all 0.2s; }
        .btn-icon:hover { background: #667eea; color: white; }
        .btn-icon.success:hover { background: #22c55e; }

        .empty-row td { padding: 3rem; }
        .empty-state { text-align: center; color: #94a3b8; }
        .empty-state i { font-size: 2rem; margin-bottom: 0.5rem; }

        .pagination-wrapper { padding: 1rem; border-top: 1px solid #f1f5f9; display: flex; justify-content: center; }
        .pagination { display: flex; gap: 0.25rem; }
        .page-link { padding: 0.5rem 0.75rem; border-radius: 6px; text-decoration: none; color: #64748b; font-weight: 500; }
        .page-link:hover { background: #f1f5f9; }
        .page-link.active { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }

        @media (max-width: 768px) {
            .stats-row { flex-direction: column; }
            .filters-form { flex-direction: column; }
        }
    </style>
</body>
</html>
