<?php
/**
 * Accept Transfer - Accept or reject incoming land transfers
 */
define('APP_RUNNING', true);
session_start();
require_once 'db_connect.php';
require_once 'includes/auth.php';

$token = $_GET['token'] ?? '';
$user_id = $_SESSION['user_id'] ?? 0;
$user_email = $_SESSION['email'] ?? '';

// Ensure land_transfers table exists
$tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'land_transfers'");
if (mysqli_num_rows($tableCheck) == 0) {
    header('Location: login.php?error=Transfer not found');
    exit;
}

if (empty($token)) {
    header('Location: login.php?error=Invalid transfer link');
    exit;
}

// Get transfer details
$token_escaped = mysqli_real_escape_string($conn, $token);
$transfer = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT lt.*,
           l.land_name, l.total_area, l.area_unit, l.location_address,
           fu.full_name as from_name, fu.email as from_email, fu.phone as from_phone
    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.transfer_token = '$token_escaped'
"));

if (!$transfer) {
    header('Location: login.php?error=Transfer not found');
    exit;
}

// Check if transfer is still pending
if ($transfer['status'] != 'pending') {
    $status_msg = [
        'completed' => 'Uhamishaji huu umekwisha kukamilika',
        'rejected' => 'Uhamishaji huu umekataliwa',
        'cancelled' => 'Uhamishaji huu umefutwa na mmiliki'
    ];
    header('Location: login.php?error=' . urlencode($status_msg[$transfer['status']] ?? 'Transfer not available'));
    exit;
}

// Check if user is the intended recipient
$is_recipient = false;
if ($user_id && $transfer['to_user_id'] == $user_id) {
    $is_recipient = true;
} elseif ($user_email && strtolower($transfer['to_email']) == strtolower($user_email)) {
    $is_recipient = true;
}

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

// Handle accept/reject
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    if (!$user_id) {
        $error = 'Tafadhali ingia kwanza ili kukubali au kukataa uhamishaji';
    } elseif (!$is_recipient) {
        $error = 'Huna ruhusa ya kukubali uhamishaji huu';
    } else {
        $transfer_id = $transfer['id'];
        $land_id = $transfer['land_id'];
        $from_user_id = $transfer['from_user_id'];

        if ($_POST['action'] == 'accept') {
            // Start transaction
            mysqli_begin_transaction($conn);

            try {
                // Update transfer status
                mysqli_query($conn, "UPDATE land_transfers SET status = 'completed', to_user_id = $user_id, responded_at = NOW(), completed_at = NOW() WHERE id = $transfer_id");

                // Transfer land ownership
                mysqli_query($conn, "UPDATE lands SET user_id = $user_id WHERE id = $land_id");

                // Revoke any shares on this land
                mysqli_query($conn, "UPDATE land_shares SET status = 'revoked' WHERE land_id = $land_id");

                // Commit transaction
                mysqli_commit($conn);

                $success = 'Umekubali uhamishaji! Ardhi "' . htmlspecialchars($transfer['land_name']) . '" sasa ni yako.';

            } catch (Exception $e) {
                mysqli_rollback($conn);
                $error = 'Imeshindwa kukamilisha uhamishaji. Tafadhali jaribu tena.';
            }

        } elseif ($_POST['action'] == 'reject') {
            mysqli_query($conn, "UPDATE land_transfers SET status = 'rejected', to_user_id = $user_id, responded_at = NOW() WHERE id = $transfer_id");
            $success = 'Umekataa uhamishaji. Ardhi itabaki kwa mmiliki wa awali.';
        }
    }
}

// Refresh transfer data if action was taken
if ($success) {
    $transfer = mysqli_fetch_assoc(mysqli_query($conn, "
        SELECT lt.*,
               l.land_name, l.total_area, l.area_unit, l.location_address,
               fu.full_name as from_name, fu.email as from_email, fu.phone as from_phone
        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.transfer_token = '$token_escaped'
    "));
}
?>
<!DOCTYPE html>
<html lang="sw">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kubali Uhamishaji - 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: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .transfer-card {
            background: white;
            border-radius: 24px;
            box-shadow: 0 25px 80px rgba(0,0,0,0.3);
            max-width: 500px;
            width: 100%;
            overflow: hidden;
        }

        .transfer-header {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .transfer-header.completed {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        }

        .transfer-header.rejected {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        }

        .transfer-header i {
            font-size: 48px;
            margin-bottom: 16px;
        }

        .transfer-header h2 {
            margin: 0;
            font-size: 22px;
        }

        .transfer-body {
            padding: 30px;
        }

        .land-preview {
            background: linear-gradient(135deg, rgba(34, 197, 94, 0.1) 0%, rgba(16, 185, 129, 0.1) 100%);
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
            text-align: center;
        }

        .land-preview h3 {
            margin: 0 0 8px 0;
            font-size: 20px;
            color: #1e293b;
        }

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

        .land-stats {
            display: flex;
            justify-content: center;
            gap: 24px;
            margin-top: 16px;
        }

        .land-stat {
            text-align: center;
        }

        .land-stat .value {
            font-size: 20px;
            font-weight: 700;
            color: #22c55e;
        }

        .land-stat .label {
            font-size: 12px;
            color: #64748b;
        }

        .from-info {
            background: #f8fafc;
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 20px;
        }

        .from-info h5 {
            margin: 0 0 12px 0;
            font-size: 14px;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .from-user {
            display: flex;
            align-items: center;
            gap: 12px;
        }

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

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

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

        .transfer-details {
            margin-bottom: 20px;
        }

        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #f1f5f9;
        }

        .detail-row:last-child {
            border-bottom: none;
        }

        .detail-label {
            color: #64748b;
            font-size: 14px;
        }

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

        .reason-box {
            background: #fefce8;
            border: 1px solid #fde047;
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 20px;
        }

        .reason-box h5 {
            margin: 0 0 8px 0;
            font-size: 14px;
            color: #854d0e;
        }

        .reason-box p {
            margin: 0;
            color: #a16207;
            font-style: italic;
        }

        .action-buttons {
            display: flex;
            gap: 12px;
        }

        .btn-accept {
            flex: 1;
            padding: 16px 24px;
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            font-size: 15px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .btn-accept:hover {
            box-shadow: 0 8px 25px rgba(34, 197, 94, 0.4);
            transform: translateY(-2px);
        }

        .btn-reject {
            flex: 1;
            padding: 16px 24px;
            background: rgba(239, 68, 68, 0.1);
            color: #dc2626;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            font-size: 15px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .btn-reject:hover {
            background: rgba(239, 68, 68, 0.2);
        }

        .login-prompt {
            text-align: center;
            padding: 20px;
            background: #f8fafc;
            border-radius: 12px;
        }

        .login-prompt p {
            margin: 0 0 16px 0;
            color: #475569;
        }

        .login-prompt a {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 12px 24px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            text-decoration: none;
            font-weight: 600;
        }

        .success-message {
            text-align: center;
            padding: 30px 0;
        }

        .success-icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            color: white;
            font-size: 36px;
        }

        .success-message h3 {
            margin: 0 0 12px 0;
            color: #1e293b;
        }

        .success-message p {
            margin: 0 0 20px 0;
            color: #64748b;
        }

        .success-message a {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 12px 24px;
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            color: white;
            border-radius: 10px;
            text-decoration: none;
            font-weight: 600;
        }
    </style>
</head>
<body>
    <div class="transfer-card">
        <?php if($success): ?>
        <div class="transfer-header <?php echo $transfer['status']; ?>">
            <i class="fas fa-<?php echo $transfer['status'] == 'completed' ? 'check-circle' : 'times-circle'; ?>"></i>
            <h2><?php echo $transfer['status'] == 'completed' ? 'Uhamishaji Umekamilika!' : 'Uhamishaji Umekataliwa'; ?></h2>
        </div>
        <div class="transfer-body">
            <div class="success-message">
                <div class="success-icon">
                    <i class="fas fa-<?php echo $transfer['status'] == 'completed' ? 'check' : 'times'; ?>"></i>
                </div>
                <h3><?php echo $success; ?></h3>
                <?php if($transfer['status'] == 'completed'): ?>
                <p>Ardhi hii sasa ipo kwenye orodha ya ardhi zako.</p>
                <a href="<?php echo url('lands.php'); ?>">
                    <i class="fas fa-map"></i>Tazama Ardhi Zangu
                </a>
                <?php else: ?>
                <p>Mmiliki ataarifiwa kuhusu uamuzi wako.</p>
                <a href="<?php echo url('lands.php'); ?>">
                    <i class="fas fa-home"></i>Rudi Nyumbani
                </a>
                <?php endif; ?>
            </div>
        </div>
        <?php else: ?>
        <div class="transfer-header">
            <i class="fas fa-exchange-alt"></i>
            <h2>Ombi la Uhamishaji wa Ardhi</h2>
        </div>
        <div class="transfer-body">
            <?php if($error): ?>
            <div class="alert alert-danger mb-4">
                <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
            </div>
            <?php endif; ?>

            <!-- Land Preview -->
            <div class="land-preview">
                <h3><i class="fas fa-map-marked-alt mr-2"></i><?php echo htmlspecialchars($transfer['land_name']); ?></h3>
                <?php if($transfer['location_address']): ?>
                <p><i class="fas fa-map-marker-alt mr-1"></i><?php echo htmlspecialchars($transfer['location_address']); ?></p>
                <?php endif; ?>
                <div class="land-stats">
                    <div class="land-stat">
                        <div class="value"><?php echo number_format($transfer['total_area'], 2); ?></div>
                        <div class="label"><?php echo $transfer['area_unit']; ?></div>
                    </div>
                </div>
            </div>

            <!-- From User Info -->
            <div class="from-info">
                <h5>Kutoka kwa / From</h5>
                <div class="from-user">
                    <div class="from-avatar">
                        <i class="fas fa-user"></i>
                    </div>
                    <div class="from-details">
                        <h4><?php echo htmlspecialchars($transfer['from_name']); ?></h4>
                        <p><?php echo htmlspecialchars($transfer['from_email']); ?></p>
                    </div>
                </div>
            </div>

            <!-- Transfer Details -->
            <div class="transfer-details">
                <div class="detail-row">
                    <span class="detail-label">Aina / Type</span>
                    <span class="detail-value">
                        <?php
                        $types = ['sale' => 'Mauzo / Sale', 'gift' => 'Zawadi / Gift', 'inheritance' => 'Urithi / Inheritance', 'surveyed' => 'Kupimwa / Surveyed', 'other' => 'Nyingine / Other'];
                        echo $types[$transfer['transfer_type']] ?? $transfer['transfer_type'];
                        ?>
                    </span>
                </div>
                <?php if($transfer['amount'] > 0): ?>
                <div class="detail-row">
                    <span class="detail-label">Kiasi / Amount</span>
                    <span class="detail-value"><?php echo number_format($transfer['amount']); ?> <?php echo $transfer['currency']; ?></span>
                </div>
                <?php endif; ?>
                <div class="detail-row">
                    <span class="detail-label">Tarehe / Date</span>
                    <span class="detail-value"><?php echo date('M d, Y H:i', strtotime($transfer['initiated_at'])); ?></span>
                </div>
            </div>

            <!-- Reason -->
            <?php if($transfer['reason']): ?>
            <div class="reason-box">
                <h5><i class="fas fa-quote-left mr-1"></i>Sababu / Reason</h5>
                <p><?php echo htmlspecialchars($transfer['reason']); ?></p>
            </div>
            <?php endif; ?>

            <!-- Action Buttons -->
            <?php if(!$user_id): ?>
            <div class="login-prompt">
                <p><i class="fas fa-lock fa-2x mb-2" style="color: #667eea;"></i></p>
                <p>Ingia kwenye akaunti yako ili kukubali au kukataa uhamishaji huu.</p>
                <a href="<?php echo url('login.php?redirect=' . urlencode($_SERVER['REQUEST_URI'])); ?>">
                    <i class="fas fa-sign-in-alt"></i>Ingia / Login
                </a>
            </div>
            <?php elseif(!$is_recipient): ?>
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle mr-2"></i>
                Uhamishaji huu umekusudiwa kwa <?php echo htmlspecialchars($transfer['to_email']); ?>. Tafadhali ingia na akaunti sahihi.
            </div>
            <?php else: ?>
            <form method="POST">
                <div class="action-buttons">
                    <button type="submit" name="action" value="accept" class="btn-accept" onclick="return confirm('Una uhakika unataka kukubali ardhi hii? Utakuwa mmiliki mpya.')">
                        <i class="fas fa-check"></i>Kubali / Accept
                    </button>
                    <button type="submit" name="action" value="reject" class="btn-reject" onclick="return confirm('Una uhakika unataka kukataa uhamishaji huu?')">
                        <i class="fas fa-times"></i>Kataa / Reject
                    </button>
                </div>
            </form>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</body>
</html>
