<?php
require_once '../includes/config.php';
require_once 'header.php';

$memberId = $_GET['id'] ?? 0;
$error = '';
$success = '';

if (!$memberId) {
    header('Location: members.php');
    exit;
}

// Get member data
$stmt = $pdo->prepare("SELECT * FROM members WHERE id = ?");
$stmt->execute([$memberId]);
$member = $stmt->fetch();

if (!$member) {
    header('Location: members.php');
    exit;
}

// Get membership types
$stmt = $pdo->query("SELECT * FROM membership_types ORDER BY amount");
$membershipTypes = $stmt->fetchAll();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $fullname = trim($_POST['fullname'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $dob = $_POST['dob'] ?? '';
    $gender = $_POST['gender'] ?? '';
    $address = trim($_POST['address'] ?? '');
    $city = trim($_POST['city'] ?? '');
    $state = trim($_POST['state'] ?? '');
    $pincode = trim($_POST['pincode'] ?? '');
    $occupation = trim($_POST['occupation'] ?? '');
    $membership_type_id = $_POST['membership_type_id'] ?? 0;
    $expiry_date = $_POST['expiry_date'] ?? null;
    $status = $_POST['status'] ?? 'active';
    
    if (empty($fullname) || empty($email) || empty($membership_type_id)) {
        $error = 'Please fill all required fields';
    } else {
        // Check if email exists for other members
        $stmt = $pdo->prepare("SELECT id FROM members WHERE email = ? AND id != ?");
        $stmt->execute([$email, $memberId]);
        if ($stmt->rowCount() > 0) {
            $error = 'Email already used by another member';
        } else {
            // Handle photo upload
            $profile_photo = $member['profile_photo'];
            if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] == 0) {
                $uploadResult = uploadFile($_FILES['profile_photo']);
                if (isset($uploadResult['success'])) {
                    // Delete old photo if not default
                    if ($profile_photo != 'default.jpg' && file_exists(UPLOAD_PATH . $profile_photo)) {
                        unlink(UPLOAD_PATH . $profile_photo);
                    }
                    $profile_photo = $uploadResult['filename'];
                }
            }
            
            try {
                $stmt = $pdo->prepare("UPDATE members SET fullname = ?, email = ?, phone = ?, dob = ?, gender = ?, 
                                      address = ?, city = ?, state = ?, pincode = ?, occupation = ?, 
                                      membership_type_id = ?, profile_photo = ?, expiry_date = ?, status = ? 
                                      WHERE id = ?");
                
                $stmt->execute([
                    $fullname, $email, $phone, $dob, $gender, $address, $city, $state, 
                    $pincode, $occupation, $membership_type_id, $profile_photo, $expiry_date, 
                    $status, $memberId
                ]);
                
                $success = 'Member updated successfully!';
                
                // Refresh member data
                $stmt = $pdo->prepare("SELECT * FROM members WHERE id = ?");
                $stmt->execute([$memberId]);
                $member = $stmt->fetch();
                
            } catch (Exception $e) {
                $error = 'Update failed: ' . $e->getMessage();
            }
        }
    }
}
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2"><i class="fas fa-user-edit me-2"></i>Edit Member: <?php echo htmlspecialchars($member['fullname']); ?></h1>
    <a href="members.php" class="btn btn-secondary"><i class="fas fa-arrow-left me-2"></i>Back to Members</a>
</div>

<?php if ($error): ?>
    <div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<div class="card">
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Full Name *</label>
                        <input type="text" class="form-control" name="fullname" value="<?php echo htmlspecialchars($member['fullname']); ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Email *</label>
                        <input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($member['email']); ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Phone Number</label>
                        <input type="tel" class="form-control" name="phone" value="<?php echo htmlspecialchars($member['phone']); ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Date of Birth</label>
                        <input type="date" class="form-control" name="dob" value="<?php echo $member['dob']; ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Gender</label>
                        <select class="form-control" name="gender">
                            <option value="">Select</option>
                            <option value="male" <?php echo $member['gender'] == 'male' ? 'selected' : ''; ?>>Male</option>
                            <option value="female" <?php echo $member['gender'] == 'female' ? 'selected' : ''; ?>>Female</option>
                            <option value="other" <?php echo $member['gender'] == 'other' ? 'selected' : ''; ?>>Other</option>
                        </select>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Membership Type *</label>
                        <select class="form-control" name="membership_type_id" required>
                            <option value="">Select Membership Type</option>
                            <?php foreach ($membershipTypes as $type): ?>
                                <option value="<?php echo $type['id']; ?>" <?php echo $member['membership_type_id'] == $type['id'] ? 'selected' : ''; ?>>
                                    <?php echo $type['type']; ?> - <?php echo formatCurrency($type['amount']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Expiry Date</label>
                        <input type="date" class="form-control" name="expiry_date" value="<?php echo $member['expiry_date']; ?>">
                        <small class="text-muted">Leave empty for lifetime membership</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select class="form-control" name="status">
                            <option value="active" <?php echo $member['status'] == 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="expired" <?php echo $member['status'] == 'expired' ? 'selected' : ''; ?>>Expired</option>
                            <option value="suspended" <?php echo $member['status'] == 'suspended' ? 'selected' : ''; ?>>Suspended</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Profile Photo</label>
                        <div class="row">
                            <div class="col-3">
                                <img src="<?php echo UPLOAD_URL . $member['profile_photo']; ?>" 
                                     style="width: 80px; height: 80px; object-fit: cover; border-radius: 10px;"
                                     onerror="this.src='assets/images/default-avatar.png'">
                            </div>
                            <div class="col-9">
                                <input type="file" class="form-control" name="profile_photo" accept="image/*">
                                <small class="text-muted">Leave empty to keep current photo</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Occupation</label>
                        <input type="text" class="form-control" name="occupation" value="<?php echo htmlspecialchars($member['occupation']); ?>">
                    </div>
                </div>
            </div>
            
            <div class="mb-3">
                <label class="form-label">Address</label>
                <textarea class="form-control" name="address" rows="2"><?php echo htmlspecialchars($member['address']); ?></textarea>
            </div>
            
            <div class="row">
                <div class="col-md-4">
                    <div class="mb-3">
                        <label class="form-label">City</label>
                        <input type="text" class="form-control" name="city" value="<?php echo htmlspecialchars($member['city']); ?>">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="mb-3">
                        <label class="form-label">State</label>
                        <input type="text" class="form-control" name="state" value="<?php echo htmlspecialchars($member['state']); ?>">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="mb-3">
                        <label class="form-label">Pincode</label>
                        <input type="text" class="form-control" name="pincode" value="<?php echo htmlspecialchars($member['pincode']); ?>">
                    </div>
                </div>
            </div>
            
            <div class="alert alert-info">
                <i class="fas fa-info-circle me-2"></i>
                <strong>Membership Number:</strong> <?php echo $member['membership_number']; ?> (Cannot be changed)
            </div>
            
            <button type="submit" class="btn btn-primary">Update Member</button>
            <a href="members.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</div>

<?php require_once 'footer.php'; ?>