<?php
require_once 'includes/db_connect.php';
if (!isset($_SESSION["user_id"])) { header("location: login.php"); exit; }

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

// Handle Full Profile Update (including optional image upload)
if (isset($_POST['update_profile'])) {
    // Update text-based information
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $address = trim($_POST['address']);
    $nid_number = trim($_POST['nid_number']);
    $date_of_birth = $_POST['date_of_birth'];

    $stmt_update = $conn->prepare("UPDATE users SET full_name=?, email=?, address=?, nid_number=?, date_of_birth=? WHERE id=?");
    $stmt_update->bind_param("sssssi", $full_name, $email, $address, $nid_number, $date_of_birth, $user_id);
    if ($stmt_update->execute()) {
        $message = '<div class="alert alert-success">আপনার তথ্য সফলভাবে আপডেট হয়েছে।</div>';
    } else {
        $message = '<div class="alert alert-danger">তথ্য আপডেট করতে সমস্যা হয়েছে।</div>';
    }
    $stmt_update->close();

    // Handle Profile Picture Upload if a file is selected
    if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] == 0) {
        $target_dir = "uploads/avatars/";
        if (!is_dir($target_dir)) { mkdir($target_dir, 0755, true); } // Create directory if it doesn't exist

        $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
        $file_extension = strtolower(pathinfo($_FILES["profile_image"]["name"], PATHINFO_EXTENSION));
        
        if (in_array($file_extension, $allowed_types) && $_FILES["profile_image"]["size"] <= 2000000) { // Max 2MB
            $new_filename = $target_dir . "user_" . $user_id . "_" . time() . "." . $file_extension;
            
            // Delete old picture if it exists
            $old_pic_stmt = $conn->prepare("SELECT profile_image FROM users WHERE id = ?");
            $old_pic_stmt->bind_param("i", $user_id);
            $old_pic_stmt->execute();
            $old_pic_path = $old_pic_stmt->get_result()->fetch_assoc()['profile_image'];
            if (!empty($old_pic_path) && file_exists($old_pic_path)) { unlink($old_pic_path); }
            $old_pic_stmt->close();

            // Upload new picture
            if (move_uploaded_file($_FILES["profile_image"]["tmp_name"], $new_filename)) {
                $stmt_update_pic = $conn->prepare("UPDATE users SET profile_image = ? WHERE id = ?");
                $stmt_update_pic->bind_param("si", $new_filename, $user_id);
                $stmt_update_pic->execute();
                $stmt_update_pic->close();
                $message = '<div class="alert alert-success">আপনার প্রোফাইল ছবি ও তথ্য সফলভাবে আপডেট হয়েছে।</div>';
            }
        } else {
            $message = '<div class="alert alert-danger">ছবিটি অবশ্যই JPG, PNG, GIF ফরম্যাটের এবং 2MB-এর কম হতে হবে।</div>';
        }
    }
}

// Fetch the latest user data to display
$user_stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$user_stmt->bind_param("i", $user_id);
$user_stmt->execute();
$user = $user_stmt->get_result()->fetch_assoc();
$user_stmt->close();
$conn->close();

$avatar_path = 'assets/images/default_avatar.png';
if (!empty($user['profile_image']) && file_exists($user['profile_image'])) { $avatar_path = $user['profile_image']; }
?>
<!DOCTYPE html><html lang="bn"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>আমার প্রোফাইল</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"><link rel="stylesheet" href="assets/css/style.css"></head>
<body>
<div class="container my-4" style="max-width: 600px;">
    <div class="d-flex align-items-center mb-3"><a href="index.php" class="text-dark fs-4 me-3 text-decoration-none"><i class="fas fa-arrow-left"></i></a><h3 class="mb-0">আমার প্রোফাইল</h3></div>
    <?php if(!empty($message)) echo $message; ?>
    
    <div class="card p-3">
        <div class="text-center mb-3">
            <img src="<?php echo $avatar_path; ?>" alt="Avatar" class="rounded-circle mx-auto" style="width: 120px; height: 120px; object-fit: cover;">
        </div>
        
        <div class="alert alert-info small">
            <i class="fas fa-info-circle"></i> অনুগ্রহ করে আপনার জাতীয় পরিচয়পত্র (NID) অনুযায়ী সঠিক তথ্য দিয়ে প্রোফাইল আপডেট করুন।
        </div>

        <form method="POST" enctype="multipart/form-data">
            <h5 class="mt-4">ব্যবহারকারীর তথ্য পরিবর্তন করুন</h5>
            <hr>
            <div class="mb-3">
                <label class="form-label">নতুন প্রোফাইল ছবি (ঐচ্ছিক)</label>
                <input class="form-control" type="file" name="profile_image">
            </div>
            <div class="mb-3">
                <label class="form-label">সম্পূর্ণ নাম</label>
                <input type="text" name="full_name" class="form-control" value="<?php echo htmlspecialchars($user['full_name'] ?? ''); ?>" required>
            </div>
            <div class="mb-3">
                <label class="form-label">মোবাইল নম্বর (পরিবর্তনযোগ্য নয়)</label>
                <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['mobile'] ?? ''); ?>" disabled>
            </div>
            <div class="mb-3">
                <label class="form-label">ইমেইল</label>
                <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>">
            </div>
            <div class="mb-3">
                <label class="form-label">জন্ম তারিখ</label>
                <input type="date" name="date_of_birth" class="form-control" value="<?php echo htmlspecialchars($user['date_of_birth'] ?? ''); ?>">
            </div>
            <div class="mb-3">
                <label class="form-label">NID নম্বর</label>
                <input type="text" name="nid_number" class="form-control" value="<?php echo htmlspecialchars($user['nid_number'] ?? ''); ?>">
            </div>
            <div class="mb-3">
                <label class="form-label">ঠিকানা</label>
                <textarea name="address" class="form-control"><?php echo htmlspecialchars($user['address'] ?? ''); ?></textarea>
            </div>
            <div class="d-grid">
                <button type="submit" name="update_profile" class="btn btn-primary">তথ্য আপডেট করুন</button>
            </div>
        </form>
    </div>
</div>
<nav class="bottom-nav"></nav>
</body></html>