<?php
session_start();
include 'config.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';

if (!isset($_SESSION['user_id'], $_SESSION['role']) || $_SESSION['role'] !== 'employee') {
    $_SESSION['error_message'] = 'Please log in to access this page.';
    header("Location: login.php");
    exit();
}

$employee_id = (int)$_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'Unknown User';
$email = $_SESSION['email'] ?? '';

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error_message'] = 'Invalid document ID.';
    header("Location: dashboard_employee.php");
    exit();
}
$document_id = (int)$_GET['id'];

// Fetch document
$sql = "SELECT title, file_path, pdf_file FROM documents WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $document_id);
$stmt->execute();
$result = $stmt->get_result();
$document = $result->fetch_assoc();
$stmt->close();

if (!$document) {
    $_SESSION['error_message'] = 'Document not found.';
    header("Location: dashboard_employee.php");
    exit();
}

$effective_file_path = !empty($document['file_path']) ? $document['file_path'] : ($document['pdf_file'] ?? '');
if (empty($effective_file_path) || !file_exists($effective_file_path)) {
    $_SESSION['error_message'] = 'Document file not found.';
    header("Location: dashboard_employee.php");
    exit();
}

// Get current status
$status_sql = "SELECT status FROM document_status WHERE employee_id = ? AND document_id = ?";
$stmt = $conn->prepare($status_sql);
$stmt->bind_param("ii", $employee_id, $document_id);
$stmt->execute();
$res = $stmt->get_result();
$current = $res->fetch_assoc();
$acknowledgment_status = $current['status'] ?? 'Not Read';
$stmt->close();

// Auto mark as "Read" on view (only if not already Acknowledged)
if ($acknowledgment_status === 'Not Read') {
    $upd = $conn->prepare("INSERT INTO document_status (employee_id, document_id, status) VALUES (?, ?, 'Read') ON DUPLICATE KEY UPDATE status = 'Read'");
    $upd->bind_param("ii", $employee_id, $document_id);
    $upd->execute();
    $upd->close();
    $acknowledgment_status = 'Read';

    // Notify superadmin about "Read"
    $admin = $conn->query("SELECT email FROM users WHERE LOWER(role) = 'superadmin' OR LOWER(role) = 'superadmin' LIMIT 1")->fetch_assoc();
    if ($admin) {
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = 'smtp.gmail.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'prabhakaran.cirs@gmail.com';
            $mail->Password = 'rvlgkmpmyugdswqp';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;
            $mail->setFrom('prabhakaran.cirs@gmail.com', 'HR Division');
            $mail->addAddress($admin['email']);
            $mail->Subject = "Document Viewed";
            $mail->Body = "Employee {$username} (ID: {$employee_id}) has viewed: " . $document['title'];
            $mail->send();
        } catch (Exception $e) { /* silent */ }
    }
}

// Handle Acknowledge
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acknowledge'])) {
    $ack = $conn->prepare("INSERT INTO document_status (employee_id, document_id, status) VALUES (?, ?, 'Acknowledged') ON DUPLICATE KEY UPDATE status = 'Acknowledged'");
    $ack->bind_param("ii", $employee_id, $document_id);
    if ($ack->execute()) {
        $acknowledgment_status = 'Acknowledged';
        $_SESSION['success_message'] = "Document acknowledged successfully!";

        // Email to employee
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = 'smtp.gmail.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'prabhakaran.cirs@gmail.com';
            $mail->Password = 'rvlgkmpmyugdswqp';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;
            $mail->setFrom('prabhakaran.cirs@gmail.com', 'HR Division');
            $mail->addAddress($email, $username);
            $mail->Subject = "Document Acknowledged";
            $mail->Body = "Dear {$username},\n\nYou have successfully acknowledged the document:\n" . $document['title'] . "\n\nThank you.";
            $mail->send();
        } catch (Exception $e) {}

        // Email to admin
        $admin = $conn->query("SELECT email FROM users WHERE LOWER(role) IN ('admin', 'superadmin') LIMIT 1")->fetch_assoc();
        if ($admin) {
            $mail = new PHPMailer(true);
            try {
                $mail->isSMTP();
                // same SMTP settings...
                $mail->setFrom('prabhakaran.cirs@gmail.com', 'HR Division');
                $mail->addAddress($admin['email']);
                $mail->Subject = "Document Acknowledged";
                $mail->Body = "Employee {$username} has acknowledged: " . $document['title'];
                $mail->send();
            } catch (Exception $e) {}
        }

        header("Location: dashboard_employee.php");
        exit();
    }
    $ack->close();
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($document['title']); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background:#f8f9fa; user-select:none; }
        iframe { width:100%; height:700px; border:none; }
        .status-value { font-weight:bold 1.2rem; }
    </style>
</head>
<body>
<div class="container mt-4">
    <h2><?php echo htmlspecialchars($document['title']); ?></h2>

    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?></div>
    <?php endif; ?>

    <div class="card p-4 shadow">
        <p><strong>Status:</strong> 
            <span class="status-value text-<?php echo $acknowledgment_status === 'Acknowledged' ? 'success' : ($acknowledgment_status === 'Read' ? 'warning' : 'danger'); ?>">
                <?php echo htmlspecialchars($acknowledgment_status); ?>
            </span>
        </p>

        <iframe src="<?php echo htmlspecialchars($effective_file_path) . '#toolbar=0&navpanes=0&scrollbar=1'; ?>"></iframe>

        <div class="mt-3">
            <form method="POST" style="display:inline;">
                <button type="submit" name="acknowledge" class="btn btn-success <?php echo $acknowledgment_status === 'Acknowledged' ? 'disabled' : ''; ?>">
                    Acknowledge Document
                </button>
            </form>
            <a href="dashboard_employee.php" class="btn btn-secondary ms-2">Back to Dashboard</a>
        </div>
    </div>
</div>
</body>
</html>