<?php
// Start session
require_once 'session_config_emp.php';

// Check if employee is logged in
if (!isset($_SESSION['employee_id']) || !isset($_SESSION['cnic'])) {
    header('Location: login_emp.php');
    exit();
}

include 'connect.php';

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['profile_photo'])) {
    $personal_no = $_POST['personal_no'];
    $employee_id = $_POST['employee_id'];
    
    // Verify ownership
    $check_sql = "SELECT re.emp_numb FROM registrations_emp re 
                  WHERE re.id = ? AND re.cnic = ? AND re.emp_numb = ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("iss", $_SESSION['employee_id'], $_SESSION['cnic'], $personal_no);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows == 0) {
        $_SESSION['profile_update_error'] = "You are not authorized to update this profile.";
        header('Location: employee_profile_view.php');
        exit();
    }
    
    // Upload configuration
    $uploadDir = 'uploads/profile_photos/';
    $maxFileSize = 2 * 1024 * 1024; // 2MB
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
    
    // Create upload directory if it doesn't exist
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    $file = $_FILES['profile_photo'];
    
    // Check for errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $_SESSION['profile_update_error'] = "Upload error: " . $file['error'];
        header('Location: employee_profile_view.php');
        exit();
    }
    
    // Check file size
    if ($file['size'] > $maxFileSize) {
        $_SESSION['profile_update_error'] = "File too large. Maximum size is 2MB.";
        header('Location: employee_profile_view.php');
        exit();
    }
    
    // Check file type
    $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($fileInfo, $file['tmp_name']);
    finfo_close($fileInfo);
    
    if (!in_array($mimeType, $allowedTypes)) {
        $_SESSION['profile_update_error'] = "Invalid file type. Only JPG, PNG, and GIF are allowed.";
        header('Location: employee_profile_view.php');
        exit();
    }
    
    // Generate unique filename
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = $personal_no . '_' . time() . '.' . $extension;
    $targetPath = $uploadDir . $filename;
    
    // Get current photo path
    $current_sql = "SELECT photo_path FROM employees WHERE personal_no = ?";
    $current_stmt = $conn->prepare($current_sql);
    $current_stmt->bind_param("s", $personal_no);
    $current_stmt->execute();
    $current_result = $current_stmt->get_result();
    $oldPhotoPath = null;
    
    if ($current_result->num_rows > 0) {
        $current_row = $current_result->fetch_assoc();
        $oldPhotoPath = $current_row['photo_path'];
    }
    
    // Move uploaded file
    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        // Delete old photo if exists
        if (!empty($oldPhotoPath) && file_exists($oldPhotoPath) && $oldPhotoPath != $targetPath) {
            unlink($oldPhotoPath);
        }
        
        // Update database
        $update_sql = "UPDATE employees SET photo_path = ? WHERE personal_no = ?";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("ss", $targetPath, $personal_no);
        
        if ($update_stmt->execute()) {
            $_SESSION['profile_update_success'] = "Profile picture updated successfully!";
        } else {
            $_SESSION['profile_update_error'] = "Failed to update database: " . $update_stmt->error;
            // Delete uploaded file if database update failed
            unlink($targetPath);
        }
    } else {
        $_SESSION['profile_update_error'] = "Failed to upload file. Check folder permissions.";
    }
    
    header('Location: employee_profile_view.php');
    exit();
} else {
    $_SESSION['profile_update_error'] = "Invalid request.";
    header('Location: employee_profile_view.php');
    exit();
}
?>