<?php
require_once '../../config.php';
require_once '../../functions.php';

check_user_auth();

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

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = $_POST['full_name'] ?? '';
    $email = $_POST['email'] ?? '';
    $phone = $_POST['phone'] ?? '';

    // Handle Profile Image Upload
    $profile_image = null;
    if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
        $allowed = ['jpg', 'jpeg', 'png', 'gif'];
        $filename = $_FILES['profile_image']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

        if (in_array($ext, $allowed)) {
            $new_filename = 'user_' . $user_id . '_' . time() . '.' . $ext;
            // Use absolute path for upload
            $upload_dir = __DIR__ . '/../../public/uploads/profiles/';
            $upload_path = $upload_dir . $new_filename;

            // Ensure directory exists
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }

            if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $upload_path)) {
                $profile_image = 'uploads/profiles/' . $new_filename;
            } else {
                $error = "Failed to upload image.";
            }
        } else {
            $error = "Invalid file type. Only JPG, PNG, GIF allowed.";
        }
    }

    if (empty($error)) {
        try {
            // Build Update Query dynamically
            $sql = "UPDATE users SET full_name = ?, email = ?, phone = ?";
            $params = [$full_name, $email, $phone];

            if ($profile_image) {
                $sql .= ", profile_image = ?";
                $params[] = $profile_image;
            }

            $sql .= " WHERE id = ?";
            $params[] = $user_id;

            $stmt = $pdo->prepare($sql);
            if ($stmt->execute($params)) {
                if ($profile_image) {
                    $_SESSION['profile_image'] = $profile_image;
                }
                $message = "Profile updated successfully!";
            } else {
                $error = "Failed to update profile.";
            }
        } catch (PDOException $e) {
            $error = "Database Error: " . $e->getMessage();
        }
    }
}

// Fetch User Data
try {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();
} catch (PDOException $e) {
    $error = "Error fetching data.";
}

$pageTitle = "Edit Profile - User Panel";
include '../includes/header.php';
?>

<?php include '../includes/user_sidebar.php'; ?>

<!--app-content open-->
<div class="main-content app-content mt-0">
    <div class="side-app">

        <!-- CONTAINER -->
        <div class="main-container container-fluid">

            <?php include '../includes/navbar.php'; ?>

            <!-- PAGE-HEADER -->
            <div class="page-header">
                <h1 class="page-title">Edit Profile</h1>
                <div>
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="javascript:void(0)">Home</a></li>
                        <li class="breadcrumb-item active" aria-current="page">Profile</li>
                    </ol>
                </div>
            </div>
            <!-- PAGE-HEADER END -->

            <!-- ROW-1 -->
            <div class="row">
                <div class="col-xl-8 col-lg-12">
                    <?php if (!empty($message)): ?>
                        <div class="alert alert-success" role="alert"><button type="button" class="btn-close"
                                data-bs-dismiss="alert" aria-hidden="true">×</button><i class="fa fa-check-circle-o me-2"
                                aria-hidden="true"></i> <?php echo htmlspecialchars($message); ?></div>
                    <?php endif; ?>
                    <?php if (!empty($error)): ?>
                        <div class="alert alert-danger" role="alert"><button type="button" class="btn-close"
                                data-bs-dismiss="alert" aria-hidden="true">×</button><i class="fa fa-frown-o me-2"
                                aria-hidden="true"></i> <?php echo htmlspecialchars($error); ?></div>
                    <?php endif; ?>

                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Update Profile</h3>
                        </div>
                        <div class="card-body">
                            <form method="POST" enctype="multipart/form-data">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Full Name</label>
                                            <input type="text" name="full_name" class="form-control"
                                                value="<?php echo htmlspecialchars($user['full_name'] ?? ''); ?>"
                                                placeholder="John Doe">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Email</label>
                                            <input type="email" name="email" class="form-control"
                                                value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>"
                                                placeholder="john@example.com">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Phone Number</label>
                                            <input type="text" name="phone" class="form-control"
                                                value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>"
                                                placeholder="+1234567890">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Profile Image</label>
                                            <input type="file" name="profile_image" class="form-control">
                                        </div>
                                    </div>
                                </div>

                                <div class="form-footer mt-4">
                                    <button type="submit" class="btn btn-primary">Update Profile</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="col-xl-4 col-lg-12">
                    <div class="card">
                        <div class="card-body text-center">
                            <span class="avatar avatar-xxl brround cover-image"
                                data-bs-image-src="<?php echo !empty($user['profile_image']) ? asset_url($user['profile_image']) : asset_url('assets/images/users/21.jpg'); ?>"
                                style="background-image: url('<?php echo !empty($user['profile_image']) ? asset_url($user['profile_image']) : asset_url('assets/images/users/21.jpg'); ?>')"></span>
                            <h4 class="h4 mb-0 mt-3">
                                <?php echo htmlspecialchars($user['full_name'] ?? $user['username']); ?>
                            </h4>
                            <p class="card-text text-muted">User</p>
                        </div>
                    </div>
                </div>
            </div>
            <!-- ROW-1 END -->

        </div>
        <!-- CONTAINER END -->
    </div>
</div>
<!--app-content close-->

<?php include '../includes/footer.php'; ?>