<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "../include/config.php";
include "../../imagekit/vendor/autoload.php";

use ImageKit\ImageKit;



// Initialize ImageKit
$imageKit = new ImageKit(
    "public_EypymL+l9sKGk/JHnWApsJ94ybA=",
    "private_T5LPQkxAMv70EVlUDk+RyUU3h5w=",
    "https://ik.imagekit.io/zamastudents"
);

$error = "";
$success = "";

// Get current staff data
$staff_email = $_SESSION['email'];
$sql = "SELECT * FROM staff WHERE email = '$staff_email'";
$result = $conn->query($sql);
$staff = $result->fetch_assoc();

// Process update if form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['updateprofile'])) {
    $staffname = trim($_POST['staffname'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $qualification = trim($_POST['qualification'] ?? '');
    $department = trim($_POST['department'] ?? '');
    $gender = $_POST['gender'] ?? '';
    
    // Validation
    if (empty($staffname) || empty($phone) || empty($email) || empty($gender)) {
        $error = "All required fields must be filled!";
    } else {
        // Handle image upload to ImageKit
        $image_url = $staff['image']; // Keep existing image
        
        if (!empty($_FILES['image']['name']) && $_FILES['image']['error'] == 0) {
            $upload = $imageKit->upload([
                'file' => fopen($_FILES['image']['tmp_name'], 'r'),
                'fileName' => 'staff_' . time() . '_' . uniqid(),
                'folder' => '/staff/',
                'useUniqueFileName' => true
            ]);
            
            if (isset($upload->error)) {
                $error = "Image upload failed: " . $upload->error->message;
            } else {
                $image_url = $upload->result->url;
            }
        }
        
        if (empty($error)) {
            // Update database
            $update_sql = "UPDATE staff SET 
                          staffname = ?, 
                          phone = ?, 
                          email = ?, 
                          qualification = ?, 
                          department = ?, 
                          gender = ?, 
                          image = ?
                          WHERE id = ?";
            
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("sssssssi", 
                $staffname, 
                $phone, 
                $email, 
                $qualification, 
                $department, 
                $gender, 
                $image_url,
                $staff['id']
            );
            
            if ($stmt->execute()) {
                // Update session
                $_SESSION['staffname'] = $staffname;
                $_SESSION['email'] = $email;
                $_SESSION['image'] = $image_url;
                
                $success = "Profile updated successfully!";
            } else {
                $error = "Update failed: " . $conn->error;
            }
            $stmt->close();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Profile</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            background-color: #f8f9fa;
            padding-top: 20px;
        }
        .profile-container {
            max-width: 800px;
            margin: 0 auto;
        }
        .profile-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .profile-header {
            background: linear-gradient(to right, #4e54c8, #8f94fb);
            color: white;
            padding: 20px;
            text-align: center;
        }
        .profile-body {
            padding: 30px;
        }
        .image-preview {
            width: 150px;
            height: 150px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid #4e54c8;
            margin: 0 auto 20px;
            display: block;
        }
    </style>
</head>
<body>
    <?php include "../include/nav.php"; ?>
<div class="content">
    <div class="profile-container">
        <div class="profile-card">
            <div class="profile-header">
                <h3><i class="fas fa-user-edit"></i> Update Profile</h3>
            </div>
            
            <div class="profile-body">
                <?php if ($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle"></i> <?php echo $success; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <form method="POST" enctype="multipart/form-data">
                    <div class="text-center mb-4">
                        <img src="<?php echo $staff['image'];?>" 
                             class="image-preview" 
                             id="imagePreview"
                             alt="Profile Picture">
                        <div class="mt-2">
                            <label for="image" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-camera"></i> Change Photo
                            </label>
                            <input type="file" class="d-none" id="image" name="image" accept="image/*" onchange="previewImage(this)">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Full Name *</label>
                            <input type="text" class="form-control" name="staffname" 
                                   value="<?php echo htmlspecialchars($staff['staffname']); ?>" required>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Phone *</label>
                            <input type="tel" class="form-control" name="phone" 
                                   value="<?php echo htmlspecialchars($staff['phone']); ?>" required>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Email *</label>
                            <input type="email" class="form-control" name="email" 
                                   value="<?php echo htmlspecialchars($staff['email']); ?>" required>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Gender *</label>
                            <select class="form-select" name="gender" required>
                                <option value="Male" <?php echo $staff['gender'] == 'Male' ? 'selected' : ''; ?>>Male</option>
                                <option value="Female" <?php echo $staff['gender'] == 'Female' ? 'selected' : ''; ?>>Female</option>
                            </select>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Qualification</label>
                            <input type="text" class="form-control" name="qualification" 
                                   value="<?php echo htmlspecialchars($staff['qualification']); ?>">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Department</label>
                            <input type="text" class="form-control" name="department" 
                                   value="<?php echo htmlspecialchars($staff['department']); ?>">
                        </div>
                    </div>
                    
                    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                        <a href="dashboard.php" class="btn btn-secondary me-md-2">
                            <i class="fas fa-arrow-left"></i> Back
                        </a>
                        <button type="submit" name="updateprofile" class="btn btn-primary">
                            <i class="fas fa-save"></i> Update Profile
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        function previewImage(input) {
            const preview = document.getElementById('imagePreview');
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</body>
</html>
<?php
$conn->close();
?>