<?php
/**
 * Share Land - Share land with other users by email
 */
define('APP_RUNNING', true);
session_start();
require_once 'db_connect.php';
require_once 'includes/auth.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

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

// Verify land ownership
$land = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM lands WHERE id = $land_id AND user_id = $user_id"));
if (!$land) {
    header('Location: lands.php?error=Land not found');
    exit;
}

// Ensure land_shares table exists
$tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'land_shares'");
if (mysqli_num_rows($tableCheck) == 0) {
    mysqli_query($conn, "
        CREATE TABLE `land_shares` (
            `id` INT(11) NOT NULL AUTO_INCREMENT,
            `land_id` INT(11) NOT NULL,
            `owner_id` INT(11) NOT NULL,
            `shared_with_email` VARCHAR(255) NOT NULL,
            `shared_with_user_id` INT(11) DEFAULT NULL,
            `share_token` VARCHAR(100) NOT NULL,
            `can_edit` TINYINT(1) DEFAULT 0,
            `message` TEXT DEFAULT NULL,
            `shared_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            `viewed_at` TIMESTAMP NULL,
            `status` ENUM('pending', 'accepted', 'declined', 'revoked') DEFAULT 'pending',
            PRIMARY KEY (`id`),
            UNIQUE KEY `unique_share` (`land_id`, `shared_with_email`),
            KEY `land_id` (`land_id`),
            KEY `owner_id` (`owner_id`),
            KEY `shared_with_user_id` (`shared_with_user_id`),
            KEY `share_token` (`share_token`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
}

$success = '';
$error = '';

// Handle share submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] == 'share') {
        $email = mysqli_real_escape_string($conn, trim($_POST['email']));
        $message = mysqli_real_escape_string($conn, trim($_POST['message'] ?? ''));
        $can_edit = isset($_POST['can_edit']) ? 1 : 0;

        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Tafadhali weka barua pepe halali / Please enter a valid email address';
        } else {
            // Check if already shared with this email
            $existing = mysqli_query($conn, "SELECT id FROM land_shares WHERE land_id = $land_id AND shared_with_email = '$email' AND status != 'revoked'");
            if (mysqli_num_rows($existing) > 0) {
                $error = 'Ardhi hii imeshashirikiwa na ' . htmlspecialchars($email);
            } else {
                // Generate share token
                $share_token = bin2hex(random_bytes(32));

                // Check if the email belongs to an existing user
                $shared_user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT id FROM users WHERE email = '$email'"));
                $shared_user_id = $shared_user ? $shared_user['id'] : 'NULL';

                // Insert share record
                $sql = "INSERT INTO land_shares (land_id, owner_id, shared_with_email, shared_with_user_id, share_token, can_edit, message, status)
                        VALUES ($land_id, $user_id, '$email', $shared_user_id, '$share_token', $can_edit, '$message', 'pending')";

                if (mysqli_query($conn, $sql)) {
                    $success = 'Ardhi imeshirikiwa kwa mafanikio na / Land shared successfully with ' . htmlspecialchars($email);
                } else {
                    $error = 'Imeshindwa kushiriki ardhi. Tafadhali jaribu tena.';
                }
            }
        }
    } elseif ($_POST['action'] == 'revoke') {
        $share_id = intval($_POST['share_id']);
        mysqli_query($conn, "UPDATE land_shares SET status = 'revoked' WHERE id = $share_id AND owner_id = $user_id");
        $success = 'Ufikiaji umefutwa / Share access revoked';
    }
}

// Get existing shares for this land
$shares = [];
$shares_result = mysqli_query($conn, "
    SELECT ls.*, u.full_name, u.username
    FROM land_shares ls
    LEFT JOIN users u ON ls.shared_with_user_id = u.id
    WHERE ls.land_id = $land_id AND ls.status != 'revoked'
    ORDER BY ls.shared_at DESC
");
while ($share = mysqli_fetch_assoc($shares_result)) {
    $shares[] = $share;
}
?>
<!DOCTYPE html>
<html lang="sw">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shiriki Ardhi - Land Secure</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo url('assets/font-awesome/css/all.min.css'); ?>">
    <link href="<?php echo url('assets/vendor/bootstrap/css/bootstrap.min.css'); ?>" rel="stylesheet">
    <style>
        * { font-family: 'Inter', sans-serif; }
        :root { --primary: #1a3a6e; --secondary: #2d5a3d; }
        body { background: #f4f6f9; margin: 0; }
        .card { border: none; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.05); margin-bottom: 20px; }
        .card-header { background: white; border-bottom: 1px solid #eee; padding: 20px; font-weight: 600; }
        .btn-primary { background: var(--primary); border: none; }
        .btn-primary:hover { background: var(--secondary); }
        .topbar {
            background: white; padding: 15px 25px; border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 25px;
        }
        .share-form { background: linear-gradient(135deg, rgba(26, 58, 110, 0.05) 0%, rgba(45, 90, 61, 0.05) 100%); border-radius: 12px; padding: 25px; }
        .share-item {
            background: white; border-radius: 12px; padding: 15px; margin-bottom: 15px;
            border-left: 4px solid var(--primary); box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        .share-item.pending { border-left-color: #f59e0b; }
        .share-item.accepted { border-left-color: #22c55e; }
        .share-item .share-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; flex-wrap: wrap; gap: 10px; }
        .share-item .share-email { font-weight: 600; color: #1e293b; }
        .share-item .share-meta { font-size: 12px; color: #64748b; }
        .share-link { background: #f8fafc; padding: 10px; border-radius: 8px; font-size: 11px; word-break: break-all; }
        .copy-btn { cursor: pointer; color: var(--primary); }
        .copy-btn:hover { color: var(--secondary); }
        @media (max-width: 768px) {
            .share-item .share-header { flex-direction: column; align-items: flex-start; }
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <div class="topbar">
            <h5 class="mb-0">
                <i class="fas fa-share-alt mr-2"></i>Shiriki Ardhi: <?php echo htmlspecialchars($land['land_name']); ?>
            </h5>
        </div>

        <?php if($success): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <?php if($error): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-lg-6">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-user-plus mr-2"></i>Shiriki na Mtu / Share with Someone
                    </div>
                    <div class="card-body">
                        <div class="share-form">
                            <form method="POST">
                                <input type="hidden" name="action" value="share">

                                <div class="form-group">
                                    <label><i class="fas fa-envelope mr-1"></i>Barua Pepe / Email <span class="text-danger">*</span></label>
                                    <input type="email" name="email" class="form-control" placeholder="Weka barua pepe" required>
                                    <small class="text-muted">Mtu huyu ataweza kuona ardhi yako</small>
                                </div>

                                <div class="form-group">
                                    <label><i class="fas fa-comment mr-1"></i>Ujumbe (Si lazima)</label>
                                    <textarea name="message" class="form-control" rows="3" placeholder="Andika ujumbe..."></textarea>
                                </div>

                                <div class="form-group">
                                    <div class="custom-control custom-checkbox">
                                        <input type="checkbox" class="custom-control-input" id="canEdit" name="can_edit">
                                        <label class="custom-control-label" for="canEdit">
                                            <i class="fas fa-edit mr-1"></i>Ruhusu kubadilisha
                                        </label>
                                    </div>
                                    <small class="text-muted">Weka tiki ikiwa unataka waweze kubadilisha maelezo ya ardhi</small>
                                </div>

                                <button type="submit" class="btn btn-primary btn-block">
                                    <i class="fas fa-paper-plane mr-2"></i>Shiriki Ardhi
                                </button>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Public Share Link -->
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-link mr-2"></i>Kiungo cha Umma / Public Link
                    </div>
                    <div class="card-body">
                        <p class="text-muted small">
                            Mtu yeyote mwenye kiungo hiki anaweza kuona ardhi yako bila kuingia:
                        </p>
                        <?php if($land['share_token']): ?>
                        <div class="share-link d-flex align-items-center justify-content-between">
                            <span id="publicLink" class="flex-grow-1"><?php echo SITE_URL; ?>/view_land.php?token=<?php echo $land['share_token']; ?></span>
                            <span class="copy-btn ml-2" onclick="copyLink('publicLink')">
                                <i class="fas fa-copy"></i>
                            </span>
                        </div>
                        <?php else: ?>
                        <p class="text-muted">Hakuna kiungo cha umma. Tengeneza kwa kubadilisha ardhi.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="col-lg-6">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-users mr-2"></i>Imeshirikiwa na / Shared With (<?php echo count($shares); ?>)
                    </div>
                    <div class="card-body">
                        <?php if(empty($shares)): ?>
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-user-friends fa-3x mb-3" style="opacity: 0.3;"></i>
                            <p>Ardhi hii haijashirikiwa na mtu yeyote bado.</p>
                        </div>
                        <?php else: ?>
                        <?php foreach($shares as $share): ?>
                        <div class="share-item <?php echo $share['status']; ?>">
                            <div class="share-header">
                                <div>
                                    <div class="share-email">
                                        <i class="fas fa-user-circle mr-1"></i>
                                        <?php echo $share['full_name'] ?: htmlspecialchars($share['shared_with_email']); ?>
                                    </div>
                                    <div class="share-meta">
                                        <?php echo htmlspecialchars($share['shared_with_email']); ?>
                                    </div>
                                </div>
                                <div>
                                    <?php if($share['status'] == 'pending'): ?>
                                    <span class="badge badge-warning">Inasubiri</span>
                                    <?php elseif($share['status'] == 'accepted'): ?>
                                    <span class="badge badge-success">Imekubaliwa</span>
                                    <?php endif; ?>

                                    <?php if($share['can_edit']): ?>
                                    <span class="badge badge-info ml-1">Anaweza kubadilisha</span>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <div class="share-meta mb-2">
                                <i class="fas fa-clock mr-1"></i>
                                Imeshirikiwa <?php echo date('M d, Y H:i', strtotime($share['shared_at'])); ?>
                                <?php if($share['viewed_at']): ?>
                                <br><i class="fas fa-eye mr-1"></i>
                                Imetazamwa <?php echo date('M d, Y H:i', strtotime($share['viewed_at'])); ?>
                                <?php endif; ?>
                            </div>

                            <?php if($share['message']): ?>
                            <div class="small text-muted mb-2">
                                <i class="fas fa-quote-left mr-1"></i>
                                <?php echo htmlspecialchars($share['message']); ?>
                            </div>
                            <?php endif; ?>

                            <div class="d-flex justify-content-between align-items-center flex-wrap" style="gap: 10px;">
                                <div class="share-link flex-grow-1">
                                    <small id="link<?php echo $share['id']; ?>">
                                        <?php echo SITE_URL; ?>/shared_view.php?token=<?php echo $share['share_token']; ?>
                                    </small>
                                </div>
                                <div class="d-flex" style="gap: 5px;">
                                    <button class="btn btn-sm btn-outline-primary" onclick="copyLink('link<?php echo $share['id']; ?>')">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                    <form method="POST" style="display:inline;">
                                        <input type="hidden" name="action" value="revoke">
                                        <input type="hidden" name="share_id" value="<?php echo $share['id']; ?>">
                                        <button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('Futa ufikiaji kwa mtumiaji huyu?')">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="text-center mt-3">
            <a href="<?php echo url('land/' . $land_id); ?>" class="btn btn-secondary">
                <i class="fas fa-arrow-left mr-2"></i>Rudi kwenye Ardhi
            </a>
        </div>
    </main>

    <script src="<?php echo url('assets/vendor/jquery/jquery.min.js'); ?>"></script>
    <script src="<?php echo url('assets/vendor/bootstrap/js/bootstrap.bundle.min.js'); ?>"></script>
    <script>
        function copyLink(elementId) {
            const text = document.getElementById(elementId).innerText.trim();
            navigator.clipboard.writeText(text).then(() => {
                alert('Kiungo kimenakiliwa! / Link copied!');
            }).catch(() => {
                const textArea = document.createElement('textarea');
                textArea.value = text;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                alert('Kiungo kimenakiliwa! / Link copied!');
            });
        }
    </script>
</body>
</html>
