<?php
/**
 * My Transfers - View all incoming and outgoing land transfers
 */
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'];
$user_email = $_SESSION['email'] ?? '';

// Ensure land_transfers table exists
$tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'land_transfers'");
if (mysqli_num_rows($tableCheck) == 0) {
    mysqli_query($conn, "
        CREATE TABLE `land_transfers` (
            `id` INT(11) NOT NULL AUTO_INCREMENT,
            `land_id` INT(11) NOT NULL,
            `from_user_id` INT(11) NOT NULL,
            `to_user_id` INT(11) DEFAULT NULL,
            `to_email` VARCHAR(255) NOT NULL,
            `transfer_token` VARCHAR(100) NOT NULL,
            `reason` TEXT,
            `transfer_type` ENUM('sale', 'gift', 'inheritance', 'surveyed', 'other') DEFAULT 'sale',
            `amount` DECIMAL(15,2) DEFAULT NULL,
            `currency` VARCHAR(10) DEFAULT 'TZS',
            `status` ENUM('pending', 'accepted', 'rejected', 'cancelled', 'completed') DEFAULT 'pending',
            `initiated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            `responded_at` TIMESTAMP NULL,
            `completed_at` TIMESTAMP NULL,
            `notes` TEXT,
            PRIMARY KEY (`id`),
            KEY `land_id` (`land_id`),
            KEY `from_user_id` (`from_user_id`),
            KEY `to_user_id` (`to_user_id`),
            KEY `transfer_token` (`transfer_token`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
}

// Get outgoing transfers (transfers I initiated)
$outgoing = [];
$result = mysqli_query($conn, "
    SELECT lt.*, l.land_name, l.total_area, l.area_unit,
           tu.full_name as to_name
    FROM land_transfers lt
    JOIN lands l ON lt.land_id = l.id
    LEFT JOIN users tu ON lt.to_user_id = tu.id
    WHERE lt.from_user_id = $user_id
    ORDER BY lt.initiated_at DESC
");
while ($row = mysqli_fetch_assoc($result)) {
    $outgoing[] = $row;
}

// Get incoming transfers (transfers sent to me)
$incoming = [];
$user_email_escaped = mysqli_real_escape_string($conn, $user_email);
$result = mysqli_query($conn, "
    SELECT lt.*, l.land_name, l.total_area, l.area_unit,
           fu.full_name as from_name, fu.email as from_email
    FROM land_transfers lt
    JOIN lands l ON lt.land_id = l.id
    JOIN users fu ON lt.from_user_id = fu.id
    WHERE (lt.to_user_id = $user_id OR lt.to_email = '$user_email_escaped')
    ORDER BY lt.initiated_at DESC
");
while ($row = mysqli_fetch_assoc($result)) {
    $incoming[] = $row;
}

$pending_incoming = array_filter($incoming, function($t) { return $t['status'] == 'pending'; });
$pending_outgoing = array_filter($outgoing, function($t) { return $t['status'] == 'pending'; });
?>
<!DOCTYPE html>
<html lang="sw">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Uhamishaji Wangu - 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; }
        body { background: #f4f6f9; margin: 0; }

        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            color: white;
        }

        .page-header h1 {
            font-size: 24px;
            margin: 0 0 8px 0;
        }

        .page-header p {
            margin: 0;
            opacity: 0.9;
        }

        .stats-row {
            display: flex;
            gap: 16px;
            margin-bottom: 24px;
            flex-wrap: wrap;
        }

        .stat-card {
            flex: 1;
            min-width: 150px;
            background: white;
            border-radius: 14px;
            padding: 20px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        }

        .stat-card.pending {
            border-left: 4px solid #f59e0b;
        }

        .stat-card.incoming {
            border-left: 4px solid #22c55e;
        }

        .stat-card.outgoing {
            border-left: 4px solid #667eea;
        }

        .stat-value {
            font-size: 28px;
            font-weight: 700;
            color: #1e293b;
        }

        .stat-label {
            font-size: 13px;
            color: #64748b;
            margin-top: 4px;
        }

        .tab-navigation {
            display: flex;
            gap: 12px;
            margin-bottom: 24px;
            flex-wrap: wrap;
        }

        .tab-btn {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 14px 24px;
            background: white;
            border: 2px solid #e2e8f0;
            border-radius: 14px;
            font-weight: 600;
            color: #64748b;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .tab-btn:hover {
            border-color: #667eea;
            color: #667eea;
        }

        .tab-btn.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-color: transparent;
            color: white;
        }

        .tab-count {
            background: rgba(0,0,0,0.1);
            padding: 2px 10px;
            border-radius: 20px;
            font-size: 12px;
        }

        .tab-btn.active .tab-count {
            background: rgba(255,255,255,0.3);
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .transfer-card {
            background: white;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 16px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.05);
            border-left: 4px solid #e2e8f0;
            transition: all 0.3s ease;
        }

        .transfer-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
        }

        .transfer-card.pending { border-left-color: #f59e0b; }
        .transfer-card.completed { border-left-color: #22c55e; }
        .transfer-card.rejected { border-left-color: #ef4444; }
        .transfer-card.cancelled { border-left-color: #94a3b8; }

        .transfer-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 16px;
            flex-wrap: wrap;
            gap: 12px;
        }

        .transfer-land {
            display: flex;
            align-items: center;
            gap: 14px;
        }

        .land-icon {
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
        }

        .land-icon.incoming {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        }

        .land-info h4 {
            margin: 0 0 4px 0;
            font-size: 16px;
            color: #1e293b;
        }

        .land-info p {
            margin: 0;
            font-size: 13px;
            color: #64748b;
        }

        .transfer-status {
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .transfer-status.pending { background: #fef3c7; color: #d97706; }
        .transfer-status.completed { background: #dcfce7; color: #16a34a; }
        .transfer-status.rejected { background: #fef2f2; color: #dc2626; }
        .transfer-status.cancelled { background: #f1f5f9; color: #64748b; }

        .transfer-details {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 16px;
            margin-bottom: 16px;
            padding: 16px;
            background: #f8fafc;
            border-radius: 12px;
        }

        .detail-item {
            display: flex;
            flex-direction: column;
        }

        .detail-item label {
            font-size: 11px;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 4px;
        }

        .detail-item span {
            font-size: 14px;
            font-weight: 600;
            color: #1e293b;
        }

        .transfer-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .btn-action {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 18px;
            border-radius: 10px;
            font-size: 13px;
            font-weight: 600;
            text-decoration: none;
            transition: all 0.3s ease;
            border: none;
            cursor: pointer;
        }

        .btn-action.accept {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            color: white;
        }

        .btn-action.reject {
            background: rgba(239, 68, 68, 0.1);
            color: #dc2626;
        }

        .btn-action.view {
            background: #f1f5f9;
            color: #475569;
        }

        .btn-action:hover {
            transform: translateY(-2px);
            text-decoration: none;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            background: white;
            border-radius: 16px;
        }

        .empty-icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            font-size: 32px;
            color: #667eea;
        }

        .empty-state h3 {
            margin: 0 0 8px 0;
            color: #1e293b;
        }

        .empty-state p {
            margin: 0;
            color: #64748b;
        }

        @media (max-width: 768px) {
            .tab-navigation {
                flex-direction: column;
            }

            .transfer-details {
                grid-template-columns: 1fr 1fr;
            }
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <div class="page-header">
            <h1><i class="fas fa-exchange-alt mr-2"></i>Uhamishaji wa Ardhi / Land Transfers</h1>
            <p>Simamia uhamishaji wa ardhi zinazoingia na zinazotoka</p>
        </div>

        <!-- Stats -->
        <div class="stats-row">
            <div class="stat-card pending">
                <div class="stat-value"><?php echo count($pending_incoming); ?></div>
                <div class="stat-label">Zinasubiri Kukubaliwa</div>
            </div>
            <div class="stat-card incoming">
                <div class="stat-value"><?php echo count($incoming); ?></div>
                <div class="stat-label">Zilizopokewa</div>
            </div>
            <div class="stat-card outgoing">
                <div class="stat-value"><?php echo count($outgoing); ?></div>
                <div class="stat-label">Zilizotumwa</div>
            </div>
        </div>

        <!-- Tab Navigation -->
        <div class="tab-navigation">
            <button class="tab-btn active" onclick="switchTab('incoming')">
                <i class="fas fa-inbox"></i>
                <span>Zinazoingia / Incoming</span>
                <span class="tab-count"><?php echo count($incoming); ?></span>
            </button>
            <button class="tab-btn" onclick="switchTab('outgoing')">
                <i class="fas fa-paper-plane"></i>
                <span>Zinazotoka / Outgoing</span>
                <span class="tab-count"><?php echo count($outgoing); ?></span>
            </button>
        </div>

        <!-- Incoming Transfers -->
        <div id="tab-incoming" class="tab-content active">
            <?php if(empty($incoming)): ?>
            <div class="empty-state">
                <div class="empty-icon">
                    <i class="fas fa-inbox"></i>
                </div>
                <h3>Hakuna Uhamishaji Unaoingia</h3>
                <p>Wakati mtu atakuhamishia ardhi, utaiona hapa.</p>
            </div>
            <?php else: ?>
            <?php foreach($incoming as $transfer): ?>
            <div class="transfer-card <?php echo $transfer['status']; ?>">
                <div class="transfer-header">
                    <div class="transfer-land">
                        <div class="land-icon incoming">
                            <i class="fas fa-map-marked-alt"></i>
                        </div>
                        <div class="land-info">
                            <h4><?php echo htmlspecialchars($transfer['land_name']); ?></h4>
                            <p><?php echo number_format($transfer['total_area'], 2) . ' ' . $transfer['area_unit']; ?></p>
                        </div>
                    </div>
                    <span class="transfer-status <?php echo $transfer['status']; ?>">
                        <?php
                        $statuses = ['pending' => 'Inasubiri', 'completed' => 'Imekamilika', 'rejected' => 'Imekataliwa', 'cancelled' => 'Imefutwa'];
                        echo $statuses[$transfer['status']] ?? $transfer['status'];
                        ?>
                    </span>
                </div>

                <div class="transfer-details">
                    <div class="detail-item">
                        <label>Kutoka / From</label>
                        <span><?php echo htmlspecialchars($transfer['from_name']); ?></span>
                    </div>
                    <div class="detail-item">
                        <label>Aina / Type</label>
                        <span>
                            <?php
                            $types = ['sale' => 'Mauzo', 'gift' => 'Zawadi', 'inheritance' => 'Urithi', 'surveyed' => 'Kupimwa', 'other' => 'Nyingine'];
                            echo $types[$transfer['transfer_type']] ?? $transfer['transfer_type'];
                            ?>
                        </span>
                    </div>
                    <?php if($transfer['amount'] > 0): ?>
                    <div class="detail-item">
                        <label>Kiasi / Amount</label>
                        <span><?php echo number_format($transfer['amount']); ?> <?php echo $transfer['currency']; ?></span>
                    </div>
                    <?php endif; ?>
                    <div class="detail-item">
                        <label>Tarehe / Date</label>
                        <span><?php echo date('M d, Y', strtotime($transfer['initiated_at'])); ?></span>
                    </div>
                </div>

                <?php if($transfer['reason']): ?>
                <p class="mb-3" style="font-size: 14px; color: #64748b;">
                    <i class="fas fa-quote-left mr-1" style="color: #f59e0b;"></i>
                    <?php echo htmlspecialchars($transfer['reason']); ?>
                </p>
                <?php endif; ?>

                <div class="transfer-actions">
                    <?php if($transfer['status'] == 'pending'): ?>
                    <a href="<?php echo url('accept_transfer.php?token=' . $transfer['transfer_token']); ?>" class="btn-action accept">
                        <i class="fas fa-check"></i>Kubali / Accept
                    </a>
                    <a href="<?php echo url('accept_transfer.php?token=' . $transfer['transfer_token']); ?>" class="btn-action reject">
                        <i class="fas fa-times"></i>Kataa / Reject
                    </a>
                    <?php elseif($transfer['status'] == 'completed'): ?>
                    <a href="<?php echo url('land/' . $transfer['land_id']); ?>" class="btn-action view">
                        <i class="fas fa-eye"></i>Tazama Ardhi
                    </a>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- Outgoing Transfers -->
        <div id="tab-outgoing" class="tab-content">
            <?php if(empty($outgoing)): ?>
            <div class="empty-state">
                <div class="empty-icon">
                    <i class="fas fa-paper-plane"></i>
                </div>
                <h3>Hakuna Uhamishaji Uliotuma</h3>
                <p>Utaona hapa uhamishaji wote ulioanzisha kwa ardhi zako.</p>
            </div>
            <?php else: ?>
            <?php foreach($outgoing as $transfer): ?>
            <div class="transfer-card <?php echo $transfer['status']; ?>">
                <div class="transfer-header">
                    <div class="transfer-land">
                        <div class="land-icon">
                            <i class="fas fa-map-marked-alt"></i>
                        </div>
                        <div class="land-info">
                            <h4><?php echo htmlspecialchars($transfer['land_name']); ?></h4>
                            <p><?php echo number_format($transfer['total_area'], 2) . ' ' . $transfer['area_unit']; ?></p>
                        </div>
                    </div>
                    <span class="transfer-status <?php echo $transfer['status']; ?>">
                        <?php
                        $statuses = ['pending' => 'Inasubiri', 'completed' => 'Imekamilika', 'rejected' => 'Imekataliwa', 'cancelled' => 'Imefutwa'];
                        echo $statuses[$transfer['status']] ?? $transfer['status'];
                        ?>
                    </span>
                </div>

                <div class="transfer-details">
                    <div class="detail-item">
                        <label>Kwa / To</label>
                        <span><?php echo htmlspecialchars($transfer['to_name'] ?: $transfer['to_email']); ?></span>
                    </div>
                    <div class="detail-item">
                        <label>Aina / Type</label>
                        <span>
                            <?php
                            $types = ['sale' => 'Mauzo', 'gift' => 'Zawadi', 'inheritance' => 'Urithi', 'surveyed' => 'Kupimwa', 'other' => 'Nyingine'];
                            echo $types[$transfer['transfer_type']] ?? $transfer['transfer_type'];
                            ?>
                        </span>
                    </div>
                    <?php if($transfer['amount'] > 0): ?>
                    <div class="detail-item">
                        <label>Kiasi / Amount</label>
                        <span><?php echo number_format($transfer['amount']); ?> <?php echo $transfer['currency']; ?></span>
                    </div>
                    <?php endif; ?>
                    <div class="detail-item">
                        <label>Tarehe / Date</label>
                        <span><?php echo date('M d, Y', strtotime($transfer['initiated_at'])); ?></span>
                    </div>
                </div>

                <?php if($transfer['reason']): ?>
                <p class="mb-3" style="font-size: 14px; color: #64748b;">
                    <i class="fas fa-quote-left mr-1" style="color: #f59e0b;"></i>
                    <?php echo htmlspecialchars($transfer['reason']); ?>
                </p>
                <?php endif; ?>

                <?php if($transfer['status'] == 'pending'): ?>
                <div class="transfer-actions">
                    <span class="text-muted" style="font-size: 13px;">
                        <i class="fas fa-clock mr-1"></i>Inasubiri majibu kutoka <?php echo htmlspecialchars($transfer['to_email']); ?>
                    </span>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
        </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 switchTab(tabId) {
            document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));

            event.currentTarget.classList.add('active');
            document.getElementById('tab-' + tabId).classList.add('active');
        }
    </script>
</body>
</html>
