<?php
/**
 * Account Deletion Request Page
 * Allows users to request deletion of their account and associated data
 * Required for Google Play Store compliance
 */

define('APP_RUNNING', true);
require_once 'db_connect.php';
require_once 'includes/auth.php';

initSecureSession();

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

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $csrf_token = $_POST['csrf_token'] ?? '';
    if (!verifyCSRFToken($csrf_token)) {
        $error = 'Security token expired. Please try again.';
    } else {
        $email = sanitizeInput($_POST['email'] ?? '');
        $phone = sanitizeInput($_POST['phone'] ?? '');
        $reason = sanitizeInput($_POST['reason'] ?? '');

        // Validate input
        if(empty($email) && empty($phone)) {
            $error = 'Please provide your email or phone number to identify your account.';
        } else {
            // Check if user exists
            $user_found = false;
            $user_info = '';

            if(!empty($email)) {
                $email_escaped = mysqli_real_escape_string($conn, $email);
                $check = mysqli_query($conn, "SELECT id, email, full_name FROM users WHERE email = '$email_escaped'");
                if(mysqli_num_rows($check) > 0) {
                    $user = mysqli_fetch_assoc($check);
                    $user_found = true;
                    $user_info = "Email: $email";
                }
            }

            if(!$user_found && !empty($phone)) {
                // Normalize phone
                $phone_clean = preg_replace('/[^0-9]/', '', $phone);
                if(strlen($phone_clean) == 9) {
                    $phone_clean = '0' . $phone_clean;
                } elseif(strlen($phone_clean) == 12 && substr($phone_clean, 0, 3) == '255') {
                    $phone_clean = '0' . substr($phone_clean, 3);
                }
                $phone_escaped = mysqli_real_escape_string($conn, $phone_clean);
                $check = mysqli_query($conn, "SELECT id, email, full_name, phone FROM users WHERE phone = '$phone_escaped'");
                if(mysqli_num_rows($check) > 0) {
                    $user = mysqli_fetch_assoc($check);
                    $user_found = true;
                    $user_info = "Phone: $phone";
                }
            }

            // Log the deletion request
            $ip = getClientIP();
            $ip_escaped = mysqli_real_escape_string($conn, $ip);
            $reason_escaped = mysqli_real_escape_string($conn, $reason);
            $email_escaped = mysqli_real_escape_string($conn, $email);
            $phone_escaped = mysqli_real_escape_string($conn, $phone);

            mysqli_query($conn, "INSERT INTO activity_logs (action, description, ip_address)
                                 VALUES ('deletion_request', 'Account deletion requested - Email: $email_escaped, Phone: $phone_escaped, Reason: $reason_escaped', '$ip_escaped')");

            // Always show success to prevent account enumeration
            $success = 'Your account deletion request has been submitted. If an account exists with the provided information, it will be deleted within 7 days. You will receive a confirmation email once completed.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Delete Account - Land Scanner</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/font-awesome/css/all.min.css">
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <style>
        * { font-family: 'Inter', sans-serif; }
        body {
            background: linear-gradient(135deg, #1a3a6e 0%, #2d5a3d 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .delete-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.3);
            padding: 40px;
            width: 100%;
            max-width: 500px;
        }
        .delete-header {
            text-align: center;
            margin-bottom: 30px;
        }
        .delete-header i { font-size: 50px; color: #dc3545; }
        .delete-header h2 { color: #1a3a6e; margin-top: 15px; }
        .form-control {
            border-radius: 10px;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
        }
        .form-control:focus {
            border-color: #dc3545;
            box-shadow: none;
        }
        .btn-delete {
            background: #dc3545;
            border: none;
            border-radius: 10px;
            padding: 12px;
            font-weight: bold;
            width: 100%;
            color: white;
        }
        .btn-delete:hover {
            background: #c82333;
            color: white;
        }
        .warning-box {
            background: #fff3cd;
            border: 1px solid #ffc107;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .warning-box h6 { color: #856404; margin-bottom: 10px; }
        .warning-box ul { margin: 0; padding-left: 20px; color: #856404; }
        .warning-box li { margin-bottom: 5px; font-size: 14px; }
        .back-link { text-align: center; margin-top: 20px; }
        .back-link a { color: #1a3a6e; font-weight: bold; }
        .alert { border-radius: 10px; }
    </style>
</head>
<body>
    <div class="delete-container">
        <div class="delete-header">
            <i class="fas fa-user-times"></i>
            <h2>Delete Account</h2>
            <p class="text-muted">Request deletion of your account and data</p>
        </div>

        <?php if($error): ?>
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
        </div>
        <?php endif; ?>

        <?php if($success): ?>
        <div class="alert alert-success">
            <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
        </div>
        <div class="back-link">
            <a href="home"><i class="fas fa-home mr-1"></i>Back to Home</a>
        </div>
        <?php else: ?>

        <div class="warning-box">
            <h6><i class="fas fa-exclamation-triangle mr-2"></i>Warning: This action is permanent</h6>
            <ul>
                <li>All your land records will be permanently deleted</li>
                <li>All uploaded documents will be removed</li>
                <li>Your account cannot be recovered after deletion</li>
                <li>Deletion will be processed within 7 days</li>
            </ul>
        </div>

        <form action="" method="POST">
            <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">

            <div class="form-group">
                <label><i class="fas fa-envelope mr-1"></i>Email Address</label>
                <input type="email" name="email" class="form-control" placeholder="Enter your registered email">
            </div>

            <div class="text-center my-2 text-muted">- OR -</div>

            <div class="form-group">
                <label><i class="fas fa-phone mr-1"></i>Phone Number</label>
                <input type="tel" name="phone" class="form-control" placeholder="Enter your registered phone number">
            </div>

            <div class="form-group">
                <label><i class="fas fa-comment mr-1"></i>Reason for leaving (optional)</label>
                <textarea name="reason" class="form-control" rows="3" placeholder="Help us improve by telling us why you're leaving..."></textarea>
            </div>

            <div class="form-check mb-3">
                <input type="checkbox" class="form-check-input" id="confirmDelete" required>
                <label class="form-check-label" for="confirmDelete">
                    I understand that my account and all associated data will be permanently deleted
                </label>
            </div>

            <button type="submit" class="btn btn-delete">
                <i class="fas fa-trash-alt mr-2"></i>Request Account Deletion
            </button>
        </form>

        <div class="back-link">
            <p>Changed your mind? <a href="home">Go back to Home</a></p>
            <p class="mt-2">
                <a href="contact" class="text-muted"><i class="fas fa-envelope mr-1"></i>Contact Support</a>
            </p>
        </div>
        <?php endif; ?>
    </div>

    <script src="assets/vendor/jquery/jquery.min.js"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
