<?php
header('Content-Type: application/json; charset=utf-8');
// From /website/api to /config is two levels up (../../config/database.php)
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();
    // Note: some installations may not have a cohort_type column on cohorts; omit it from the SELECT for compatibility.
    $enrollment = $db->get('SELECT ce.*, c.title AS course_title, c.id AS course_id, c.region AS course_region, u.first_name, u.last_name, u.email, u.id AS student_id, coh.title AS cohort_title, coh.start_date AS cohort_start, coh.end_date AS cohort_end FROM course_enrollments ce JOIN courses c ON ce.course_id = c.id JOIN users u ON ce.student_id = u.id LEFT JOIN cohorts coh ON ce.cohort_id = coh.id WHERE ce.id = ?', [$enrollmentId]);
    if (!$enrollment) {
        echo json_encode(['success' => false, 'message' => 'Enrollment not found']);
        exit;
    }

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

    $courseTitle = $enrollment['course_title'] ?? '';
    $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'] ?? '');

    $cohortTitle = $enrollment['cohort_title'] ?? '';
    $cohortLabel = $cohortTitle !== '' ? $cohortTitle : null;
    $cohortStart = $enrollment['cohort_start'] ?? null;
    $cohortEnd = $enrollment['cohort_end'] ?? null;
    // Older databases may not have cohort_type on cohorts or agreement_templates; treat as null.
    $cohortType = $enrollment['cohort_type'] ?? null;

    $agreementTitle = 'Training Agreement for ' . $courseTitle;
    $agreementBody = '';
    $agreementTemplateId = null;

    $region = $enrollment['course_region'] ?? 'global';
    // Use a simplified template selection that does not depend on cohort_type,
    // so it works even if that column is missing from agreement_templates.
    $template = $db->get(
        "SELECT * FROM agreement_templates
         WHERE is_active = 1
           AND (course_id IS NULL OR course_id = ?)
           AND (region = 'global' OR region = ?)
         ORDER BY (course_id IS NOT NULL AND course_id = ?) DESC,
                  (region = ?) DESC,
                  sort_order ASC,
                  id DESC
         LIMIT 1",
        [$enrollment['course_id'], $region, $enrollment['course_id'], $region]
    );

    if ($template) {
        $agreementTitle = $template['title'] ?: $agreementTitle;
        $body = $template['body'];
        $agreementTemplateId = (int)$template['id'];

        $replacements = [
            '{{APP_NAME}}' => APP_NAME,
            '{{STUDENT_NAME}}' => $signerName,
            '{{COURSE_TITLE}}' => $courseTitle,
            '{{COHORT_TITLE}}' => $cohortLabel ?: '',
            '{{COHORT_START}}' => $cohortStart ?: '',
            '{{COHORT_END}}' => $cohortEnd ?: '',
            '{{COHORT_TYPE}}' => $cohortType ?: '',
        ];

        $agreementBody = strtr($body, $replacements);
    } else {
        $bodyParts = [];
        $bodyParts[] = 'This Training Agreement ("Agreement") is between ' . APP_NAME . ' and ' . $signerName . ' ("Student").';
        $bodyParts[] = 'Course: ' . $courseTitle . '.';
        if ($cohortLabel) {
            $bodyParts[] = 'Cohort: ' . $cohortLabel . '.';
        }
        if ($cohortStart || $cohortEnd) {
            $range = [];
            if ($cohortStart) {
                $range[] = 'start date ' . $cohortStart;
            }
            if ($cohortEnd) {
                $range[] = 'end date ' . $cohortEnd;
            }
            $bodyParts[] = 'Schedule: ' . implode(' to ', $range) . '.';
        }
        $bodyParts[] = 'By proceeding with enrollment and payment, Student confirms that they have reviewed the course description, understands the training scope, and agrees to the code of conduct, attendance expectations, and refund policy published on the site.';
        $bodyParts[] = 'Student acknowledges that access to course materials and any associated live sessions is provided for personal training purposes only and may not be shared, resold, or redistributed.';
        $bodyParts[] = 'By accepting electronically, Student agrees that this constitutes their electronic signature to this Agreement.';

        $agreementBody = implode("\n\n", $bodyParts);
    }

    $data = [
        'enrollment_id' => $enrollmentId,
        'course_id' => (int)$enrollment['course_id'],
        'student_id' => (int)$enrollment['student_id'],
        // Omit agreement_template_id for compatibility with schemas that don't have this column
        'agreement_title' => $agreementTitle,
        'agreement_body' => $agreementBody,
        'status' => 'signed',
        'signed_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_agreements', $data, 'id = ?', [$existing['id']]);
        $agreementId = (int)$existing['id'];
    } else {
        $agreementId = (int)$db->insert('course_enrollment_agreements', $data);
    }

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