<?php

require_once '../../../config.php';

header('Content-Type: application/json');



if (!isset($_SESSION['user_id'])) {

    echo json_encode(['success' => false, 'message' => 'Unauthorised']); exit;

}

if (!in_array($_SESSION['role'] ?? '', ['admin', 'headteacher', 'director', 'tutor', 'registrar', 'supervisor'])) {

    echo json_encode(['success' => false, 'message' => 'Access denied']); exit;

}



$conn  = getDBConnection();

$input = json_decode(file_get_contents('php://input'), true);



$studentId    = (int) ($input['student_id'] ?? 0);

$term         = trim((string) ($input['term'] ?? ''));

$academicYear = trim((string) ($input['academic_year'] ?? ''));

$publish      = (bool) ($input['publish'] ?? true);



if (!$studentId || !$term || !$academicYear) {

    echo json_encode(['success' => false, 'message' => 'Missing required fields']); exit;

}



// Ensure columns exist

$conn->query("ALTER TABLE report_details ADD COLUMN IF NOT EXISTS is_published TINYINT(1) NOT NULL DEFAULT 0");

$conn->query("ALTER TABLE report_details ADD COLUMN IF NOT EXISTS published_at DATETIME NULL DEFAULT NULL");



$isPublished = $publish ? 1 : 0;

$publishedAt = $publish ? date('Y-m-d H:i:s') : null;



// Check if row exists

$chk = $conn->prepare("SELECT id FROM report_details WHERE student_id = ? AND term = ? AND academic_year = ? LIMIT 1");

$chk->bind_param('iss', $studentId, $term, $academicYear);

$chk->execute();

$exists = $chk->get_result()->num_rows > 0;

$chk->close();



if (!$exists && $publish) {

    $ins = $conn->prepare("INSERT INTO report_details (student_id, term, academic_year, is_published, published_at) VALUES (?, ?, ?, ?, ?)");

    $ins->bind_param('issis', $studentId, $term, $academicYear, $isPublished, $publishedAt);

    $ok = $ins->execute();

    $ins->close();

} elseif ($exists) {

    $upd = $conn->prepare("UPDATE report_details SET is_published = ?, published_at = ? WHERE student_id = ? AND term = ? AND academic_year = ?");

    $upd->bind_param('isiss', $isPublished, $publishedAt, $studentId, $term, $academicYear);

    $ok = $upd->execute();

    $upd->close();

} else {

    echo json_encode(['success' => false, 'message' => 'No report details found. Save the report first before publishing.']); exit;

}



if (empty($ok)) {

    echo json_encode(['success' => false, 'message' => 'Database update failed: ' . $conn->error]); exit;

}



$smsSent      = false;

$parentHasPhone = false;

if ($publish) {

    // Get student info

    $stStmt = $conn->prepare("SELECT first_name, last_name, class FROM students WHERE id = ? LIMIT 1");

    $stStmt->bind_param('i', $studentId);

    $stStmt->execute();

    $student = $stStmt->get_result()->fetch_assoc();

    $stStmt->close();



    if ($student) {

        // Get parent phone number

        $phStmt = $conn->prepare("

            SELECT pa.phone FROM parent_accounts pa

            JOIN parent_student_link psl ON psl.parent_id = pa.id

            WHERE psl.student_id = ?

              AND pa.phone IS NOT NULL AND pa.phone != ''

            LIMIT 1

        ");

        $phStmt->bind_param('i', $studentId);

        $phStmt->execute();

        $parentRow = $phStmt->get_result()->fetch_assoc();

        $phStmt->close();



        if ($parentRow) {

            $parentHasPhone = true;

            $studentName = trim($student['first_name'] . ' ' . $student['last_name']);

            $schoolName  = getSettingValue('school_name') ?: 'School';

            $message     = "Dear Parent, the {$term} ({$academicYear}) Report Card for {$studentName} "

                         . "({$student['class']}) is now available. Log in to the Parent Portal to view and download it. – {$schoolName}";

            $smsSent = sendSMS($parentRow['phone'], $message);

        }

    }

}



if (!$publish) {

    // Unpublish SMS notification

    $stStmt = $conn->prepare("SELECT first_name, last_name FROM students WHERE id = ? LIMIT 1");

    $stStmt->bind_param('i', $studentId);

    $stStmt->execute();

    $student = $stStmt->get_result()->fetch_assoc();

    $stStmt->close();

}



logActivity(

    $conn,

    $_SESSION['user_id'],

    $publish ? 'publish_report' : 'unpublish_report',

    ($publish ? 'Published' : 'Unpublished') . " report: student_id={$studentId}, {$term}, {$academicYear}"

);

$conn->close();



if ($publish) {

    if ($smsSent) {

        $msg = 'Report published — SMS notification sent to parent';

    } elseif ($parentHasPhone) {

        $msg = 'Report published — SMS delivery failed (check Arkesel configuration)';

    } else {

        $msg = 'Report published — no parent phone number on file, SMS skipped';

    }

} else {

    $msg = 'Report unpublished — parents can no longer download it';

}



echo json_encode(['success' => true, 'message' => $msg]);

