<?php
include 'connect.php';

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

if (isset($_POST['personal_no'])) {
    $personal_no = $conn->real_escape_string($_POST['personal_no']);
    
    // Fetch current photo path
    $sql = "SELECT photo_path FROM employees WHERE personal_no = '$personal_no'";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        
        // Delete file if exists
        if (!empty($row['photo_path']) && file_exists($row['photo_path'])) {
            if (unlink($row['photo_path'])) {
                // Update database
                $update_sql = "UPDATE employees SET photo_path = NULL WHERE personal_no = '$personal_no'";
                if ($conn->query($update_sql)) {
                    $success = "Photo deleted successfully!";
                } else {
                    $error = "Database error: " . $conn->error;
                }
            } else {
                $error = "Failed to delete file from server.";
            }
        } else {
            // No photo exists, just clear database
            $update_sql = "UPDATE employees SET photo_path = NULL WHERE personal_no = '$personal_no'";
            if ($conn->query($update_sql)) {
                $success = "Photo reference cleared!";
            }
        }
    } else {
        $error = "Employee not found!";
    }
    
    // Store messages in session for display
    session_start();
    if (!empty($success)) {
        $_SESSION['success'] = $success;
    }
    if (!empty($error)) {
        $_SESSION['error'] = $error;
    }
    
    // Redirect back
    header("Location: " . ($_SERVER['HTTP_REFERER'] ?? 'index.php'));
    exit;
}
?>