<?php
/**
 * Plot Details AJAX Endpoint
 * LandSales Pro - Get plot details for modal
 */
define('APP_RUNNING', true);
require_once '../db_connect.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

initSecureSession();

if (!isAuthenticated()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

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

if (!$plotId) {
    echo json_encode(['success' => false, 'error' => 'Invalid plot ID']);
    exit;
}

// Get plot details
$plot = db_fetch_one("SELECT p.*, pr.name as project_name, pr.location as project_location
    FROM plots p
    JOIN projects pr ON p.project_id = pr.id
    WHERE p.id = ? AND p.user_id = ?", 'ii', [$plotId, $userId]);

if (!$plot) {
    echo json_encode(['success' => false, 'error' => 'Plot not found']);
    exit;
}

// Get sale info if sold or reserved
$sale = null;
if ($plot['status'] !== 'available') {
    $sale = db_fetch_one("SELECT s.*, b.full_name as buyer_name, b.phone as buyer_phone, b.email as buyer_email,
        (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
        WHERE s.plot_id = ? AND s.status != 'cancelled'
        ORDER BY s.created_at DESC LIMIT 1", 'i', [$plotId]);
}

// Build HTML
ob_start();
?>
<div class="plot-detail-header <?php echo $plot['status']; ?>">
    <div class="plot-status"><?php echo ucfirst($plot['status']); ?></div>
    <h3>Plot <?php echo htmlspecialchars($plot['plot_number']); ?></h3>
</div>

<div class="plot-detail-info">
    <div class="info-row">
        <span class="info-label">Project</span>
        <span class="info-value"><?php echo htmlspecialchars($plot['project_name']); ?></span>
    </div>
    <div class="info-row">
        <span class="info-label">Size</span>
        <span class="info-value"><?php echo number_format($plot['size']); ?> <?php echo $plot['size_unit']; ?></span>
    </div>
    <div class="info-row">
        <span class="info-label">Price</span>
        <span class="info-value">TZS <?php echo number_format($plot['price']); ?></span>
    </div>
    <?php if ($plot['block']): ?>
    <div class="info-row">
        <span class="info-label">Block</span>
        <span class="info-value"><?php echo htmlspecialchars($plot['block']); ?></span>
    </div>
    <?php endif; ?>
</div>

<?php if ($sale): ?>
<div class="sale-info">
    <h4>Sale Information</h4>
    <div class="info-row">
        <span class="info-label">Buyer</span>
        <span class="info-value"><?php echo htmlspecialchars($sale['buyer_name']); ?></span>
    </div>
    <div class="info-row">
        <span class="info-label">Phone</span>
        <span class="info-value"><?php echo htmlspecialchars($sale['buyer_phone']); ?></span>
    </div>
    <div class="info-row">
        <span class="info-label">Sale Date</span>
        <span class="info-value"><?php echo date('M j, Y', strtotime($sale['sale_date'])); ?></span>
    </div>
    <div class="info-row">
        <span class="info-label">Total Price</span>
        <span class="info-value">TZS <?php echo number_format($sale['total_price']); ?></span>
    </div>
    <div class="info-row">
        <span class="info-label">Paid</span>
        <span class="info-value text-success">TZS <?php echo number_format($sale['total_paid']); ?></span>
    </div>
    <div class="info-row">
        <span class="info-label">Balance</span>
        <span class="info-value text-warning">TZS <?php echo number_format($sale['total_price'] - $sale['total_paid']); ?></span>
    </div>
</div>
<?php endif; ?>

<div class="plot-detail-actions">
    <?php if ($plot['status'] === 'available'): ?>
    <a href="<?php echo SITE_URL; ?>/dashboard/sales/create.php?plot_id=<?php echo $plot['id']; ?>" class="btn btn-primary">
        <i class="fas fa-handshake"></i> Record Sale
    </a>
    <?php elseif ($sale): ?>
    <a href="<?php echo SITE_URL; ?>/dashboard/sales/view.php?id=<?php echo $sale['id']; ?>" class="btn btn-outline">
        <i class="fas fa-eye"></i> View Sale
    </a>
    <a href="<?php echo SITE_URL; ?>/dashboard/payments/create.php?sale_id=<?php echo $sale['id']; ?>" class="btn btn-primary">
        <i class="fas fa-money-bill-wave"></i> Record Payment
    </a>
    <?php endif; ?>
    <a href="<?php echo SITE_URL; ?>/dashboard/plots/edit.php?id=<?php echo $plot['id']; ?>" class="btn btn-outline">
        <i class="fas fa-edit"></i> Edit Plot
    </a>
</div>

<style>
    .plot-detail-header {
        padding: 1.5rem;
        text-align: center;
        color: white;
        border-radius: 12px 12px 0 0;
        margin: -2rem -2rem 1.5rem -2rem;
    }
    .plot-detail-header.available { background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); }
    .plot-detail-header.reserved { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); }
    .plot-detail-header.sold { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); }
    .plot-status { font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; opacity: 0.9; margin-bottom: 0.5rem; }
    .plot-detail-header h3 { margin: 0; font-size: 1.5rem; }

    .plot-detail-info, .sale-info { margin-bottom: 1.5rem; }
    .sale-info { padding-top: 1rem; border-top: 1px solid #f1f5f9; }
    .sale-info h4 { font-size: 0.9rem; color: #64748b; margin-bottom: 1rem; }

    .info-row { display: flex; justify-content: space-between; padding: 0.5rem 0; border-bottom: 1px solid #f1f5f9; }
    .info-row:last-child { border-bottom: none; }
    .info-label { color: #64748b; font-size: 0.85rem; }
    .info-value { font-weight: 500; color: #1e293b; }
    .text-success { color: #16a34a; }
    .text-warning { color: #d97706; }

    .plot-detail-actions { display: flex; flex-direction: column; gap: 0.75rem; }
    .btn { padding: 0.75rem 1rem; border-radius: 8px; font-weight: 500; text-decoration: none; display: flex; align-items: center; justify-content: center; gap: 0.5rem; 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; }
</style>
<?php
$html = ob_get_clean();

echo json_encode([
    'success' => true,
    'html' => $html
]);
