<?php
include '../includes/auth.php';
include '../config/db.php';

$user_id = $_SESSION['user_id'];
$message = '';
$error = '';

// Get user details
$user_query = $conn->query("SELECT * FROM users WHERE id=$user_id");
$user = $user_query->fetch_assoc();

// Get donation statistics
$donation_stats = $conn->query("
    SELECT 
        COUNT(*) as total_donations,
        SUM(amount) as total_amount,
        MAX(amount) as max_donation,
        MIN(amount) as min_donation,
        MAX(uploaded_at) as last_donation
    FROM donations 
    WHERE user_id=$user_id AND status='verified'
")->fetch_assoc();

// Get recent donations
$recent_donations = $conn->query("
    SELECT * FROM donations 
    WHERE user_id=$user_id AND status='verified' 
    ORDER BY uploaded_at DESC 
    LIMIT 5
");

// Get pending requests
$pending_kyc = ($user['kyc_status'] == 'pending');
$pending_cancellation = $conn->query("SELECT * FROM cancellation_requests WHERE user_id=$user_id AND status='pending'")->num_rows > 0;

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_profile'])) {
    $name = trim($_POST['name']);
    $mobile = trim($_POST['mobile']);
    $address = trim($_POST['address']);
    
    if (empty($name)) {
        $error = "Name is required.";
    } else {
        $stmt = $conn->prepare("UPDATE users SET name=?, mobile=?, address=? WHERE id=?");
        $stmt->bind_param("sssi", $name, $mobile, $address, $user_id);
        if ($stmt->execute()) {
            $message = "Profile updated successfully!";
            // Refresh user data
            $user_query = $conn->query("SELECT * FROM users WHERE id=$user_id");
            $user = $user_query->fetch_assoc();
        } else {
            $error = "Error updating profile.";
        }
        $stmt->close();
    }
}

// Handle password change
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['change_password'])) {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $error = "All password fields are required.";
    } elseif ($new_password !== $confirm_password) {
        $error = "New passwords do not match.";
    } elseif (strlen($new_password) < 6) {
        $error = "Password must be at least 6 characters.";
    } else {
        // Verify current password
        if (password_verify($current_password, $user['password'])) {
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE users SET password=? WHERE id=?");
            $stmt->bind_param("si", $hashed_password, $user_id);
            if ($stmt->execute()) {
                $message = "Password changed successfully!";
            } else {
                $error = "Error changing password.";
            }
            $stmt->close();
        } else {
            $error = "Current password is incorrect.";
        }
    }
}

// Generate member ID
$member_id = "GAU" . str_pad($user['id'], 6, "0", STR_PAD_LEFT);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Profile - Gau Seva Foundation</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 2rem;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        /* Header */
        .profile-header {
            background: white;
            border-radius: 20px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .header-info h1 {
            color: #1a3a1a;
            font-size: 1.8rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .header-info p {
            color: #666;
            margin-top: 5px;
        }

        .header-actions {
            display: flex;
            gap: 1rem;
        }

        .btn-back, .btn-logout {
            padding: 0.7rem 1.5rem;
            border-radius: 10px;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-back {
            background: #6c757d;
            color: white;
        }

        .btn-back:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }

        .btn-logout {
            background: #dc3545;
            color: white;
        }

        .btn-logout:hover {
            background: #c82333;
            transform: translateY(-2px);
        }

        /* Profile Grid */
        .profile-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 1.5rem;
        }

        /* Cards */
        .card {
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            transition: transform 0.3s;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .card-header {
            background: linear-gradient(135deg, #2c5f2d, #1a3a1a);
            color: white;
            padding: 1.2rem 1.5rem;
        }

        .card-header h2 {
            font-size: 1.2rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-body {
            padding: 1.5rem;
        }

        /* Profile Info */
        .profile-avatar {
            text-align: center;
            margin-bottom: 1.5rem;
        }

        .avatar-circle {
            width: 100px;
            height: 100px;
            background: linear-gradient(135deg, #2c5f2d, #1a3a1a);
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 1rem;
            border: 4px solid #ffd700;
        }

        .avatar-circle i {
            font-size: 3rem;
            color: white;
        }

        .member-badge {
            display: inline-block;
            padding: 0.3rem 1rem;
            background: #d4edda;
            color: #155724;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .member-id {
            margin-top: 0.5rem;
            font-size: 0.85rem;
            color: #666;
        }

        /* Info Rows */
        .info-row {
            display: flex;
            justify-content: space-between;
            padding: 0.8rem 0;
            border-bottom: 1px solid #eee;
        }

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

        .info-label {
            font-weight: 600;
            color: #666;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .info-label i {
            color: #2c5f2d;
            width: 20px;
        }

        .info-value {
            color: #333;
            font-weight: 500;
        }

        .status-badge {
            display: inline-block;
            padding: 0.2rem 0.7rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .status-approved {
            background: #d4edda;
            color: #155724;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }

        .status-active {
            background: #d4edda;
            color: #155724;
        }

        .status-inactive {
            background: #f8d7da;
            color: #721c24;
        }

        /* Form Styles */
        .form-group {
            margin-bottom: 1.2rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #333;
        }

        .form-group label i {
            color: #2c5f2d;
            margin-right: 5px;
        }

        .form-group input, .form-group textarea {
            width: 100%;
            padding: 0.75rem;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-family: 'Poppins', sans-serif;
            transition: all 0.3s;
        }

        .form-group input:focus, .form-group textarea:focus {
            outline: none;
            border-color: #2c5f2d;
            box-shadow: 0 0 0 3px rgba(44,95,45,0.1);
        }

        .btn-submit {
            width: 100%;
            padding: 0.75rem;
            background: linear-gradient(135deg, #2c5f2d, #1a3a1a);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(44,95,45,0.3);
        }

        /* Donation Stats */
        .stats-mini {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .stat-mini {
            text-align: center;
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 15px;
        }

        .stat-mini .number {
            font-size: 1.5rem;
            font-weight: 700;
            color: #2c5f2d;
        }

        .stat-mini .label {
            font-size: 0.7rem;
            color: #666;
        }

        /* Donation Table */
        .donation-table {
            width: 100%;
            border-collapse: collapse;
        }

        .donation-table th, .donation-table td {
            padding: 0.8rem;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        .donation-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #1a3a1a;
        }

        .amount-positive {
            color: #28a745;
            font-weight: 600;
        }

        /* Alert Messages */
        .alert {
            padding: 1rem;
            border-radius: 10px;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 10px;
            animation: slideIn 0.3s ease-out;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border-left: 4px solid #28a745;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Tab Buttons */
        .tab-buttons {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 1.5rem;
            border-bottom: 2px solid #e0e0e0;
        }

        .tab-btn {
            padding: 0.7rem 1.2rem;
            background: none;
            border: none;
            cursor: pointer;
            font-weight: 500;
            color: #666;
            transition: all 0.3s;
            border-radius: 10px 10px 0 0;
        }

        .tab-btn.active {
            color: #2c5f2d;
            border-bottom: 3px solid #2c5f2d;
            background: rgba(44,95,45,0.05);
        }

        .tab-btn:hover {
            color: #2c5f2d;
        }

        .tab-pane {
            display: none;
        }

        .tab-pane.active {
            display: block;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        /* Responsive */
        @media (max-width: 768px) {
            body {
                padding: 1rem;
            }

            .profile-header {
                flex-direction: column;
                text-align: center;
            }

            .stats-mini {
                grid-template-columns: 1fr;
            }

            .donation-table th, .donation-table td {
                padding: 0.5rem;
                font-size: 0.8rem;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <!-- Header -->
    <div class="profile-header">
        <div class="header-info">
            <h1><i class="fas fa-user-circle"></i> My Profile</h1>
            <p>Manage your account information and view your contributions</p>
        </div>
        <div class="header-actions">
            <a href="dashboard.php" class="btn-back"><i class="fas fa-arrow-left"></i> Dashboard</a>
            <a href="../logout.php" class="btn-logout"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>

    <!-- Messages -->
    <?php if($message): ?>
    <div class="alert alert-success">
        <i class="fas fa-check-circle"></i>
        <span><?= htmlspecialchars($message) ?></span>
    </div>
    <?php endif; ?>

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

    <!-- Profile Grid -->
    <div class="profile-grid">
        <!-- Profile Info Card -->
        <div class="card">
            <div class="card-header">
                <h2><i class="fas fa-id-card"></i> Profile Information</h2>
            </div>
            <div class="card-body">
                <div class="profile-avatar">
                    <div class="avatar-circle">
                        <i class="fas fa-user-circle"></i>
                    </div>
                    <div>
                        <span class="member-badge">
                            <i class="fas fa-crown"></i> 
                            <?= $user['membership_active'] ? 'Active Member' : 'Inactive' ?>
                        </span>
                    </div>
                    <div class="member-id">
                        <i class="fas fa-barcode"></i> Member ID: <?= $member_id ?>
                    </div>
                </div>

                <div class="info-row">
                    <span class="info-label"><i class="fas fa-user"></i> Full Name</span>
                    <span class="info-value"><?= htmlspecialchars($user['name']) ?></span>
                </div>
                <div class="info-row">
                    <span class="info-label"><i class="fas fa-envelope"></i> Email Address</span>
                    <span class="info-value"><?= htmlspecialchars($user['email']) ?></span>
                </div>
                <div class="info-row">
                    <span class="info-label"><i class="fas fa-phone"></i> Mobile Number</span>
                    <span class="info-value"><?= htmlspecialchars($user['mobile'] ?: 'Not provided') ?></span>
                </div>
                <div class="info-row">
                    <span class="info-label"><i class="fas fa-map-marker-alt"></i> Address</span>
                    <span class="info-value"><?= htmlspecialchars($user['address'] ?: 'Not provided') ?></span>
                </div>
                <div class="info-row">
                    <span class="info-label"><i class="fas fa-calendar-alt"></i> Member Since</span>
                    <span class="info-value"><?= date('F j, Y', strtotime($user['created_at'])) ?></span>
                </div>
                <div class="info-row">
                    <span class="info-label"><i class="fas fa-id-card"></i> KYC Status</span>
                    <span class="info-value">
                        <span class="status-badge status-<?= $user['kyc_status'] ?>">
                            <?= ucfirst($user['kyc_status']) ?>
                        </span>
                    </span>
                </div>
                <div class="info-row">
                    <span class="info-label"><i class="fas fa-toggle-on"></i> Membership</span>
                    <span class="info-value">
                        <span class="status-badge <?= $user['membership_active'] ? 'status-active' : 'status-inactive' ?>">
                            <?= $user['membership_active'] ? 'Active' : 'Inactive' ?>
                        </span>
                    </span>
                </div>
            </div>
        </div>

        <!-- Edit Profile Card with Tabs -->
        <div class="card">
            <div class="card-header">
                <h2><i class="fas fa-edit"></i> Account Settings</h2>
            </div>
            <div class="card-body">
                <div class="tab-buttons">
                    <button class="tab-btn active" onclick="showTab('edit')"><i class="fas fa-user-edit"></i> Edit Profile</button>
                    <button class="tab-btn" onclick="showTab('password')"><i class="fas fa-key"></i> Change Password</button>
                </div>

                <!-- Edit Profile Tab -->
                <div id="editTab" class="tab-pane active">
                    <form method="POST">
                        <div class="form-group">
                            <label><i class="fas fa-user"></i> Full Name</label>
                            <input type="text" name="name" value="<?= htmlspecialchars($user['name']) ?>" required>
                        </div>
                        <div class="form-group">
                            <label><i class="fas fa-phone"></i> Mobile Number</label>
                            <input type="tel" name="mobile" value="<?= htmlspecialchars($user['mobile']) ?>" placeholder="Enter your mobile number">
                        </div>
                        <div class="form-group">
                            <label><i class="fas fa-map-marker-alt"></i> Address</label>
                            <textarea name="address" rows="3" placeholder="Enter your address"><?= htmlspecialchars($user['address']) ?></textarea>
                        </div>
                        <button type="submit" name="update_profile" class="btn-submit">
                            <i class="fas fa-save"></i> Update Profile
                        </button>
                    </form>
                </div>

                <!-- Change Password Tab -->
                <div id="passwordTab" class="tab-pane">
                    <form method="POST">
                        <div class="form-group">
                            <label><i class="fas fa-lock"></i> Current Password</label>
                            <input type="password" name="current_password" required placeholder="Enter current password">
                        </div>
                        <div class="form-group">
                            <label><i class="fas fa-key"></i> New Password</label>
                            <input type="password" name="new_password" required placeholder="Enter new password (min 6 characters)">
                        </div>
                        <div class="form-group">
                            <label><i class="fas fa-check-circle"></i> Confirm New Password</label>
                            <input type="password" name="confirm_password" required placeholder="Confirm new password">
                        </div>
                        <button type="submit" name="change_password" class="btn-submit">
                            <i class="fas fa-sync-alt"></i> Change Password
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Donation Statistics Card -->
    <div class="card" style="margin-top: 1.5rem;">
        <div class="card-header">
            <h2><i class="fas fa-chart-line"></i> Donation Summary</h2>
        </div>
        <div class="card-body">
            <div class="stats-mini">
                <div class="stat-mini">
                    <div class="number"><?= $donation_stats['total_donations'] ?? 0 ?></div>
                    <div class="label">Total Donations</div>
                </div>
                <div class="stat-mini">
                    <div class="number">₹<?= number_format($donation_stats['total_amount'] ?? 0, 2) ?></div>
                    <div class="label">Total Amount</div>
                </div>
                <div class="stat-mini">
                    <div class="number">₹<?= number_format($donation_stats['max_donation'] ?? 0, 2) ?></div>
                    <div class="label">Highest Donation</div>
                </div>
                <div class="stat-mini">
                    <div class="number">₹<?= number_format($donation_stats['min_donation'] ?? 0, 2) ?></div>
                    <div class="label">Lowest Donation</div>
                </div>
            </div>
            <?php if($donation_stats['last_donation']): ?>
            <div class="info-row">
                <span class="info-label"><i class="fas fa-clock"></i> Last Donation</span>
                <span class="info-value"><?= date('F j, Y, g:i A', strtotime($donation_stats['last_donation'])) ?></span>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Recent Donations Card -->
    <?php if($recent_donations && $recent_donations->num_rows > 0): ?>
    <div class="card" style="margin-top: 1.5rem;">
        <div class="card-header">
            <h2><i class="fas fa-history"></i> Recent Donations</h2>
        </div>
        <div class="card-body">
            <div class="table-container" style="overflow-x: auto;">
                <table class="donation-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Amount</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($donation = $recent_donations->fetch_assoc()): ?>
                        <tr>
                            <td><?= date('d M Y, h:i A', strtotime($donation['uploaded_at'])) ?></td>
                            <td class="amount-positive">₹<?= number_format($donation['amount'], 2) ?></td>
                            <td><span class="status-badge status-approved"><i class="fas fa-check-circle"></i> Verified</span></td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Pending Alerts -->
    <?php if($pending_kyc): ?>
    <div class="alert alert-warning" style="background: #fff3cd; border-left-color: #ffc107; margin-top: 1rem;">
        <i class="fas fa-clock"></i>
        <div>
            <strong>KYC Verification Pending!</strong> Please submit your KYC documents to get full membership benefits.
            <a href="submit_kyc.php" style="color: #856404; margin-left: 10px;">Submit Now →</a>
        </div>
    </div>
    <?php endif; ?>

    <?php if($pending_cancellation): ?>
    <div class="alert alert-info" style="background: #d1ecf1; border-left-color: #17a2b8; margin-top: 1rem;">
        <i class="fas fa-info-circle"></i>
        <div>
            <strong>Membership Cancellation Requested!</strong> Your request is under review by the admin.
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
    function showTab(tab) {
        // Hide all tabs
        document.getElementById('editTab').classList.remove('active');
        document.getElementById('passwordTab').classList.remove('active');
        
        // Remove active class from buttons
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        
        // Show selected tab
        if(tab === 'edit') {
            document.getElementById('editTab').classList.add('active');
            document.querySelectorAll('.tab-btn')[0].classList.add('active');
        } else {
            document.getElementById('passwordTab').classList.add('active');
            document.querySelectorAll('.tab-btn')[1].classList.add('active');
        }
    }
</script>
</body>
</html>