<?php
/**
 * View Buyer
 * LandSales Pro - Buyer profile and purchase history
 */
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'];
$buyerId = intval($_GET['id'] ?? 0);

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

// Get buyer details
$buyer = db_fetch_one("SELECT * FROM buyers WHERE id = ? AND user_id = ?", 'ii', [$buyerId, $userId]);

if (!$buyer) {
    setFlashMessage('error', 'Buyer not found');
    header('Location: index.php');
    exit;
}

// Get buyer's purchases
$purchases = db_fetch_all("SELECT s.*, p.plot_number, p.size, p.size_unit, 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 plots p ON s.plot_id = p.id
    JOIN projects pr ON p.project_id = pr.id
    WHERE s.buyer_id = ?
    ORDER BY s.sale_date DESC", 'i', [$buyerId]);

// Calculate totals
$totalPurchases = count($purchases);
$totalValue = array_sum(array_column($purchases, 'total_price'));
$totalPaid = array_sum(array_column($purchases, 'total_paid'));
$totalBalance = $totalValue - $totalPaid;

// Get recent payments
$recentPayments = db_fetch_all("SELECT py.*, s.sale_number, p.plot_number
    FROM payments py
    JOIN sales s ON py.sale_id = s.id
    JOIN plots p ON s.plot_id = p.id
    WHERE s.buyer_id = ? AND py.status = 'confirmed'
    ORDER BY py.payment_date DESC LIMIT 10", 'i', [$buyerId]);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($buyer['full_name']); ?> - <?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">Buyer Profile</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <a href="edit.php?id=<?php echo $buyerId; ?>" class="btn btn-outline">
                    <i class="fas fa-edit"></i> Edit
                </a>
                <a href="../sales/create.php?buyer_id=<?php echo $buyerId; ?>" class="btn btn-primary">
                    <i class="fas fa-plus"></i> New Sale
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <div class="profile-grid">
                <!-- Buyer Info Card -->
                <div class="card profile-card">
                    <div class="profile-header">
                        <div class="profile-avatar">
                            <?php echo strtoupper(substr($buyer['full_name'], 0, 2)); ?>
                        </div>
                        <h2><?php echo htmlspecialchars($buyer['full_name']); ?></h2>
                        <p class="profile-subtitle">Customer since <?php echo date('F Y', strtotime($buyer['created_at'])); ?></p>
                    </div>
                    <div class="profile-body">
                        <div class="profile-item">
                            <i class="fas fa-phone"></i>
                            <div>
                                <span class="item-label">Phone</span>
                                <a href="tel:<?php echo $buyer['phone']; ?>"><?php echo $buyer['phone']; ?></a>
                            </div>
                        </div>
                        <?php if ($buyer['email']): ?>
                        <div class="profile-item">
                            <i class="fas fa-envelope"></i>
                            <div>
                                <span class="item-label">Email</span>
                                <a href="mailto:<?php echo $buyer['email']; ?>"><?php echo $buyer['email']; ?></a>
                            </div>
                        </div>
                        <?php endif; ?>
                        <?php if ($buyer['id_type'] && $buyer['id_number']): ?>
                        <div class="profile-item">
                            <i class="fas fa-id-card"></i>
                            <div>
                                <span class="item-label"><?php echo strtoupper($buyer['id_type']); ?></span>
                                <span><?php echo htmlspecialchars($buyer['id_number']); ?></span>
                            </div>
                        </div>
                        <?php endif; ?>
                        <?php if ($buyer['address']): ?>
                        <div class="profile-item">
                            <i class="fas fa-map-marker-alt"></i>
                            <div>
                                <span class="item-label">Address</span>
                                <span><?php echo htmlspecialchars($buyer['address']); ?></span>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="profile-actions">
                        <a href="tel:<?php echo $buyer['phone']; ?>" class="action-btn">
                            <i class="fas fa-phone"></i> Call
                        </a>
                        <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $buyer['phone']); ?>" target="_blank" class="action-btn whatsapp">
                            <i class="fab fa-whatsapp"></i> WhatsApp
                        </a>
                        <?php if ($buyer['email']): ?>
                        <a href="mailto:<?php echo $buyer['email']; ?>" class="action-btn">
                            <i class="fas fa-envelope"></i> Email
                        </a>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Stats Cards -->
                <div class="stats-column">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-shopping-cart"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-value"><?php echo $totalPurchases; ?></div>
                            <div class="stat-label">Total Purchases</div>
                        </div>
                    </div>
                    <div class="stat-card success">
                        <div class="stat-icon">
                            <i class="fas fa-chart-line"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-value">TZS <?php echo formatMoney($totalValue); ?></div>
                            <div class="stat-label">Total Value</div>
                        </div>
                    </div>
                    <div class="stat-card info">
                        <div class="stat-icon">
                            <i class="fas fa-money-bill-wave"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-value">TZS <?php echo formatMoney($totalPaid); ?></div>
                            <div class="stat-label">Total Paid</div>
                        </div>
                    </div>
                    <div class="stat-card <?php echo $totalBalance > 0 ? 'warning' : 'success'; ?>">
                        <div class="stat-icon">
                            <i class="fas fa-balance-scale"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-value">TZS <?php echo formatMoney($totalBalance); ?></div>
                            <div class="stat-label">Outstanding Balance</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Purchases -->
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-th"></i> Purchased Plots</h3>
                </div>
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Sale #</th>
                                <th>Plot</th>
                                <th>Project</th>
                                <th>Sale Date</th>
                                <th>Total Price</th>
                                <th>Paid</th>
                                <th>Balance</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($purchases)): ?>
                            <tr>
                                <td colspan="9" class="empty-row">
                                    <div class="empty-state">
                                        <i class="fas fa-shopping-cart"></i>
                                        <p>No purchases yet</p>
                                        <a href="../sales/create.php?buyer_id=<?php echo $buyerId; ?>" class="btn btn-primary btn-sm">Record Sale</a>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($purchases as $purchase):
                                $balance = $purchase['total_price'] - $purchase['total_paid'];
                                $paidPercent = $purchase['total_price'] > 0 ? ($purchase['total_paid'] / $purchase['total_price']) * 100 : 0;
                            ?>
                            <tr>
                                <td><span class="sale-number"><?php echo $purchase['sale_number']; ?></span></td>
                                <td>
                                    <span class="plot-number">Plot <?php echo $purchase['plot_number']; ?></span>
                                    <br><small><?php echo number_format($purchase['size']); ?> <?php echo $purchase['size_unit']; ?></small>
                                </td>
                                <td><?php echo htmlspecialchars($purchase['project_name']); ?></td>
                                <td><?php echo date('M j, Y', strtotime($purchase['sale_date'])); ?></td>
                                <td>TZS <?php echo number_format($purchase['total_price']); ?></td>
                                <td>
                                    <div class="paid-info">
                                        <span class="text-success">TZS <?php echo number_format($purchase['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>
                                    <span class="status-badge status-<?php echo $purchase['status']; ?>">
                                        <?php echo ucfirst($purchase['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="../sales/view.php?id=<?php echo $purchase['id']; ?>" class="btn-icon" title="View">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <?php if ($balance > 0 && $purchase['status'] === 'active'): ?>
                                        <a href="../payments/create.php?sale_id=<?php echo $purchase['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>
            </div>

            <!-- Recent Payments -->
            <?php if (!empty($recentPayments)): ?>
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-history"></i> Recent Payments</h3>
                </div>
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Payment #</th>
                                <th>Plot</th>
                                <th>Amount</th>
                                <th>Method</th>
                                <th>Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recentPayments as $payment): ?>
                            <tr>
                                <td><span class="payment-number"><?php echo $payment['payment_number']; ?></span></td>
                                <td>Plot <?php echo $payment['plot_number']; ?></td>
                                <td class="text-success">TZS <?php echo number_format($payment['amount']); ?></td>
                                <td><?php echo ucfirst($payment['payment_method']); ?></td>
                                <td><?php echo date('M j, Y', strtotime($payment['payment_date'])); ?></td>
                                <td>
                                    <a href="../payments/receipt.php?id=<?php echo $payment['id']; ?>" class="btn-icon" title="Receipt">
                                        <i class="fas fa-receipt"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>

            <!-- Documents Section -->
            <?php if ($buyer['photo'] || $buyer['id_image'] || $buyer['id_document']): ?>
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-file-image"></i> Documents & Photos</h3>
                </div>
                <div class="card-body">
                    <div class="documents-grid">
                        <?php if ($buyer['photo']): ?>
                        <div class="document-item">
                            <h4><i class="fas fa-user"></i> Buyer Photo</h4>
                            <a href="<?php echo SITE_URL; ?>/uploads/buyers/<?php echo htmlspecialchars($buyer['photo']); ?>" target="_blank" class="document-preview">
                                <img src="<?php echo SITE_URL; ?>/uploads/buyers/<?php echo htmlspecialchars($buyer['photo']); ?>" alt="Buyer Photo">
                            </a>
                        </div>
                        <?php endif; ?>

                        <?php if ($buyer['id_image']): ?>
                        <div class="document-item">
                            <h4><i class="fas fa-id-card"></i> ID Card Image</h4>
                            <a href="<?php echo SITE_URL; ?>/uploads/buyers/<?php echo htmlspecialchars($buyer['id_image']); ?>" target="_blank" class="document-preview">
                                <img src="<?php echo SITE_URL; ?>/uploads/buyers/<?php echo htmlspecialchars($buyer['id_image']); ?>" alt="ID Card">
                            </a>
                        </div>
                        <?php endif; ?>

                        <?php if ($buyer['id_document']): ?>
                        <div class="document-item pdf-item">
                            <h4><i class="fas fa-file-pdf"></i> Scanned ID Document</h4>
                            <a href="<?php echo SITE_URL; ?>/uploads/buyers/<?php echo htmlspecialchars($buyer['id_document']); ?>" target="_blank" class="pdf-preview">
                                <i class="fas fa-file-pdf"></i>
                                <span>View PDF Document</span>
                            </a>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($buyer['notes']): ?>
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-sticky-note"></i> Notes</h3>
                </div>
                <div class="card-body">
                    <p><?php echo nl2br(htmlspecialchars($buyer['notes'])); ?></p>
                </div>
            </div>
            <?php endif; ?>
        </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; }

        .profile-grid { display: grid; grid-template-columns: 350px 1fr; gap: 1.5rem; margin-bottom: 1.5rem; }

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

        .profile-card { }
        .profile-header { text-align: center; padding: 2rem 1.5rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .profile-avatar { width: 80px; height: 80px; background: rgba(255,255,255,0.2); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 1rem; font-size: 1.75rem; font-weight: 700; }
        .profile-header h2 { margin: 0 0 0.25rem; font-size: 1.5rem; }
        .profile-subtitle { margin: 0; opacity: 0.9; font-size: 0.85rem; }

        .profile-body { padding: 1.5rem; }
        .profile-item { display: flex; gap: 1rem; padding: 0.75rem 0; border-bottom: 1px solid #f1f5f9; }
        .profile-item:last-child { border-bottom: none; }
        .profile-item i { width: 20px; color: #667eea; margin-top: 0.25rem; }
        .item-label { display: block; font-size: 0.75rem; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; }
        .profile-item a { color: #667eea; text-decoration: none; }

        .profile-actions { display: flex; gap: 0.5rem; padding: 1rem 1.5rem; border-top: 1px solid #f1f5f9; }
        .action-btn { flex: 1; padding: 0.75rem; border-radius: 8px; text-align: center; text-decoration: none; font-size: 0.85rem; font-weight: 500; background: #f1f5f9; color: #64748b; display: flex; align-items: center; justify-content: center; gap: 0.5rem; transition: all 0.2s; }
        .action-btn:hover { background: #667eea; color: white; }
        .action-btn.whatsapp:hover { background: #25D366; }

        .stats-column { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem; }
        .stat-card { background: white; border-radius: 12px; padding: 1.25rem; display: flex; align-items: center; gap: 1rem; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .stat-card.success { border-left: 3px solid #22c55e; }
        .stat-card.info { border-left: 3px solid #3b82f6; }
        .stat-card.warning { border-left: 3px solid #f59e0b; }
        .stat-icon { width: 48px; height: 48px; background: #f1f5f9; border-radius: 12px; display: flex; align-items: center; justify-content: center; color: #64748b; font-size: 1.25rem; }
        .stat-card.success .stat-icon { background: #dcfce7; color: #16a34a; }
        .stat-card.info .stat-icon { background: #dbeafe; color: #2563eb; }
        .stat-card.warning .stat-icon { background: #fef3c7; color: #d97706; }
        .stat-value { font-size: 1.1rem; font-weight: 700; color: #1e293b; }
        .stat-label { font-size: 0.75rem; color: #64748b; }

        .table-responsive { overflow-x: auto; }
        .data-table { width: 100%; border-collapse: collapse; }
        .data-table th, .data-table td { padding: 0.875rem 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, .payment-number { font-family: monospace; font-weight: 600; color: #667eea; }
        .plot-number { font-weight: 600; color: #1e293b; }
        .text-success { color: #16a34a; }
        .text-warning { color: #d97706; }

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

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

        .status-badge { padding: 0.25rem 0.75rem; border-radius: 20px; font-size: 0.7rem; font-weight: 600; }
        .status-active { background: #dbeafe; color: #2563eb; }
        .status-completed { background: #dcfce7; color: #16a34a; }
        .status-cancelled { background: #fee2e2; color: #dc2626; }

        .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: 2rem; }
        .empty-state { text-align: center; color: #94a3b8; }
        .empty-state i { font-size: 2rem; margin-bottom: 0.5rem; }

        .documents-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 1.5rem; }
        .document-item { text-align: center; }
        .document-item h4 { margin: 0 0 0.75rem 0; font-size: 0.85rem; color: #64748b; display: flex; align-items: center; justify-content: center; gap: 0.5rem; }
        .document-item h4 i { color: #667eea; }
        .document-preview { display: block; border: 2px solid #e2e8f0; border-radius: 12px; overflow: hidden; transition: all 0.2s; }
        .document-preview:hover { border-color: #667eea; box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2); }
        .document-preview img { width: 100%; height: 180px; object-fit: cover; display: block; }
        .pdf-preview { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 2rem; background: #fef3c7; border: 2px solid #fcd34d; border-radius: 12px; text-decoration: none; transition: all 0.2s; }
        .pdf-preview:hover { background: #fde68a; border-color: #f59e0b; }
        .pdf-preview i { font-size: 3rem; color: #dc2626; margin-bottom: 0.75rem; }
        .pdf-preview span { font-weight: 500; color: #92400e; }

        @media (max-width: 992px) {
            .profile-grid { grid-template-columns: 1fr; }
            .stats-column { grid-template-columns: repeat(2, 1fr); }
        }

        @media (max-width: 576px) {
            .stats-column { grid-template-columns: 1fr; }
            .profile-actions { flex-wrap: wrap; }
        }
    </style>
</body>
</html>
