<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../config/database.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true) ?? [];
$enrollmentId = (int)($input['enrollment_id'] ?? 0);
$fullName = trim($input['full_name'] ?? '');
$email = trim($input['email'] ?? '');

if (!$enrollmentId) {
    echo json_encode(['success' => false, 'message' => 'enrollment_id required']);
    exit;
}

try {
    $db = Database::getInstance();

    $enrollment = $db->get('SELECT ce.*, c.title AS course_title, c.id AS course_id, u.first_name, u.last_name, u.email, u.id AS student_id FROM course_enrollments ce JOIN courses c ON ce.course_id = c.id JOIN users u ON ce.student_id = u.id WHERE ce.id = ?', [$enrollmentId]);
    if (!$enrollment) {
        echo json_encode(['success' => false, 'message' => 'Enrollment not found']);
        exit;
    }

    $existing = $db->get('SELECT * FROM course_enrollment_privacy_policies WHERE enrollment_id = ?', [$enrollmentId]);
    if ($existing && $existing['status'] === 'accepted') {
        echo json_encode(['success' => true, 'policy_id' => (int)$existing['id']]);
        exit;
    }

    $studentFirst = trim($enrollment['first_name'] ?? '');
    $studentLast = trim($enrollment['last_name'] ?? '');
    $studentName = trim($studentFirst . ' ' . $studentLast);
    $signerName = $fullName !== '' ? $fullName : ($studentName !== '' ? $studentName : 'Student');
    $signerEmail = $email !== '' ? $email : ($enrollment['email'] ?? '');

    $policyTitle = 'Data Privacy Policy';
    $policyUrl = APP_URL . '/website/privacy-policy.php';

    $data = [
        'enrollment_id' => $enrollmentId,
        'course_id' => (int)$enrollment['course_id'],
        'student_id' => (int)$enrollment['student_id'],
        'policy_title' => $policyTitle,
        'policy_url' => $policyUrl,
        'status' => 'accepted',
        'accepted_at' => date('Y-m-d H:i:s'),
        'signer_name' => $signerName,
        'signer_email' => $signerEmail,
        'signer_ip' => getClientIP(),
        'signer_user_agent' => getUserAgent(),
    ];

    if ($existing) {
        $db->update('course_enrollment_privacy_policies', $data, 'id = ?', [$existing['id']]);
        $policyId = (int)$existing['id'];
    } else {
        $policyId = (int)$db->insert('course_enrollment_privacy_policies', $data);
    }

    echo json_encode(['success' => true, 'policy_id' => $policyId]);
    exit;
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    exit;
}
