<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();

$db = Database::getInstance();
$userId = getCurrentUserId();
$role = $_SESSION['role'] ?? null;

$enrollmentId = isset($_GET['enrollment_id']) ? (int)$_GET['enrollment_id'] : 0;
if ($enrollmentId <= 0) {
    setFlashMessage('error', 'Invalid enrollment ID.');
    redirect(APP_URL . '/lms/dashboard.php');
}

$agreement = $db->get(
    "SELECT a.*, ce.course_id, ce.student_id, ce.enrollment_date,
            c.title AS course_title,
            u.first_name, u.last_name, u.email AS student_email
     FROM course_enrollment_agreements a
     JOIN course_enrollments ce ON a.enrollment_id = ce.id
     JOIN courses c ON ce.course_id = c.id
     JOIN users u ON ce.student_id = u.id
     WHERE a.enrollment_id = ?",
    [$enrollmentId]
);

if (!$agreement) {
    setFlashMessage('error', 'No signed agreement found for this enrollment.');
    redirect(APP_URL . '/lms/dashboard.php');
}

$course = $db->get('SELECT instructor_id FROM courses WHERE id = ?', [$agreement['course_id']]);
$instructorId = $course['instructor_id'] ?? null;

$paymentPolicy = $db->get(
    "SELECT * FROM course_enrollment_payment_policies WHERE enrollment_id = ?",
    [$enrollmentId]
);

$privacyPolicy = $db->get(
    "SELECT * FROM course_enrollment_privacy_policies WHERE enrollment_id = ?",
    [$enrollmentId]
);

$canView = false;
if ($agreement['student_id'] == $userId) {
    $canView = true;
} elseif ($instructorId && $instructorId == $userId) {
    $canView = true;
} elseif (hasRole('admin') || hasRole('super_admin')) {
    $canView = true;
}

if (!$canView) {
    setFlashMessage('error', 'You do not have permission to view this agreement.');
    redirect(APP_URL . '/lms/dashboard.php');
}

$pageTitle = 'Enrollment Agreement';
include __DIR__ . '/includes/header.php';
?>

<div class="card">
  <div class="card-header d-flex justify-content-between align-items-center">
    <div>
      <h5 class="mb-0">Enrollment Agreements &amp; Policies</h5>
      <small class="text-muted">Course: <?php echo htmlspecialchars($agreement['course_title'] ?? ''); ?></small>
    </div>
    <div>
      <a href="<?php echo APP_URL; ?>/lms/dashboard.php" class="btn btn-outline-secondary btn-sm">Back</a>
    </div>
  </div>
  <div class="card-body">
    <div class="mb-3">
      <strong>Student:</strong>
      <?php echo htmlspecialchars(($agreement['first_name'] ?? '') . ' ' . ($agreement['last_name'] ?? '')); ?>
      &lt;<?php echo htmlspecialchars($agreement['student_email'] ?? ''); ?>&gt;
    </div>
    
    <hr class="my-4">

    <h6 class="mb-2">Training Agreement</h6>
    <div class="mb-3">
      <strong>Status:</strong>
      <span class="badge bg-<?php echo ($agreement['status'] ?? '') === 'signed' ? 'success' : (($agreement['status'] ?? '') === 'revoked' ? 'danger' : 'secondary'); ?>">
        <?php echo htmlspecialchars(ucfirst($agreement['status'] ?? 'pending')); ?>
      </span>
    </div>
    <div class="mb-3">
      <strong>Signed At:</strong>
      <?php echo htmlspecialchars($agreement['signed_at'] ?? ''); ?>
    </div>
    <div class="mb-3">
      <strong>Signer Name:</strong>
      <?php echo htmlspecialchars($agreement['signer_name'] ?? ''); ?>
    </div>
    <div class="mb-3">
      <strong>Signer Email:</strong>
      <?php echo htmlspecialchars($agreement['signer_email'] ?? ''); ?>
    </div>
    <div class="mb-3">
      <strong>Signer IP:</strong>
      <?php echo htmlspecialchars($agreement['signer_ip'] ?? ''); ?>
    </div>
    <div class="mb-3">
      <strong>Signer User Agent:</strong>
      <span class="text-muted" style="font-size: 0.85rem;"><?php echo htmlspecialchars($agreement['signer_user_agent'] ?? ''); ?></span>
    </div>
    <div class="mb-3">
      <strong>Agreement Title:</strong>
      <?php echo htmlspecialchars($agreement['agreement_title'] ?? 'Training Agreement'); ?>
    </div>
    <div class="border rounded p-3" style="white-space: pre-wrap;">
      <?php echo htmlspecialchars($agreement['agreement_body'] ?? ''); ?>
    </div>

    <hr class="my-4">

    <h6 class="mb-2">Non-Refundable Payment Policy</h6>
    <?php if (!empty($paymentPolicy)): ?>
      <div class="mb-3">
        <strong>Status:</strong>
        <span class="badge bg-<?php echo ($paymentPolicy['status'] ?? '') === 'accepted' ? 'success' : (($paymentPolicy['status'] ?? '') === 'revoked' ? 'danger' : 'secondary'); ?>">
          <?php echo htmlspecialchars(ucfirst($paymentPolicy['status'] ?? 'pending')); ?>
        </span>
      </div>
      <div class="mb-3">
        <strong>Accepted At:</strong>
        <?php echo htmlspecialchars($paymentPolicy['accepted_at'] ?? ''); ?>
      </div>
      <div class="mb-3">
        <strong>Signer Name:</strong>
        <?php echo htmlspecialchars($paymentPolicy['signer_name'] ?? ''); ?>
      </div>
      <div class="mb-3">
        <strong>Signer Email:</strong>
        <?php echo htmlspecialchars($paymentPolicy['signer_email'] ?? ''); ?>
      </div>
      <div class="mb-3">
        <strong>Signer IP:</strong>
        <?php echo htmlspecialchars($paymentPolicy['signer_ip'] ?? ''); ?>
      </div>
      <div class="mb-3">
        <strong>Signer User Agent:</strong>
        <span class="text-muted" style="font-size: 0.85rem;"><?php echo htmlspecialchars($paymentPolicy['signer_user_agent'] ?? ''); ?></span>
      </div>
      <div class="mb-3">
        <strong>Policy Title:</strong>
        <?php echo htmlspecialchars($paymentPolicy['policy_title'] ?? 'Non-Refundable Payment Policy'); ?>
      </div>
      <?php if (!empty($paymentPolicy['policy_url'])): ?>
        <div class="mb-3">
          <a href="<?php echo htmlspecialchars($paymentPolicy['policy_url']); ?>" target="_blank" class="btn btn-sm btn-outline-secondary">
            View Policy Content
          </a>
        </div>
      <?php endif; ?>
    <?php else: ?>
      <p class="text-muted mb-0">No payment policy acceptance recorded for this enrollment.</p>
    <?php endif; ?>

    <hr class="my-4">

    <h6 class="mb-2">Data Privacy Policy</h6>
    <?php if (!empty($privacyPolicy)): ?>
      <div class="mb-3">
        <strong>Status:</strong>
        <span class="badge bg-<?php echo ($privacyPolicy['status'] ?? '') === 'accepted' ? 'success' : (($privacyPolicy['status'] ?? '') === 'revoked' ? 'danger' : 'secondary'); ?>">
          <?php echo htmlspecialchars(ucfirst($privacyPolicy['status'] ?? 'pending')); ?>
        </span>
      </div>
      <div class="mb-3">
        <strong>Accepted At:</strong>
        <?php echo htmlspecialchars($privacyPolicy['accepted_at'] ?? ''); ?>
      </div>
      <div class="mb-3">
        <strong>Signer Name:</strong>
        <?php echo htmlspecialchars($privacyPolicy['signer_name'] ?? ''); ?>
      </div>
      <div class="mb-3">
        <strong>Signer Email:</strong>
        <?php echo htmlspecialchars($privacyPolicy['signer_email'] ?? ''); ?>
      </div>
      <div class="mb-3">
        <strong>Signer IP:</strong>
        <?php echo htmlspecialchars($privacyPolicy['signer_ip'] ?? ''); ?>
      </div>
      <div class="mb-3">
        <strong>Signer User Agent:</strong>
        <span class="text-muted" style="font-size: 0.85rem;"><?php echo htmlspecialchars($privacyPolicy['signer_user_agent'] ?? ''); ?></span>
      </div>
      <div class="mb-3">
        <strong>Policy Title:</strong>
        <?php echo htmlspecialchars($privacyPolicy['policy_title'] ?? 'Data Privacy Policy'); ?>
      </div>
      <?php if (!empty($privacyPolicy['policy_url'])): ?>
        <div class="mb-3">
          <a href="<?php echo htmlspecialchars($privacyPolicy['policy_url']); ?>" target="_blank" class="btn btn-sm btn-outline-secondary">
            View Policy Content
          </a>
        </div>
      <?php endif; ?>
    <?php else: ?>
      <p class="text-muted mb-0">No privacy policy acceptance recorded for this enrollment.</p>
    <?php endif; ?>
  </div>
</div>

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