<?php
/**
 * Action: Bulk-create parent accounts for students who don't have one yet.
 */

if (!defined('DB_HOST')) {
    require_once __DIR__ . '/../../config.php';
}

function action_create_parent_accounts_bulk(array $params): array
{
    $conn       = getDBConnection();
    $class_name = $params['class_name'] ?? null;
    $school_name = getSettingValue('school_name') ?: 'EduTrack School';

    // Find students with phone numbers but no linked parent account
    $sql = "SELECT s.id, s.first_name, s.last_name, s.class,
                   s.father_phone, s.mother_phone, s.father_name, s.mother_name
            FROM students s
            WHERE s.status = 'active'
            AND (s.father_phone IS NOT NULL AND s.father_phone != ''
                 OR s.mother_phone IS NOT NULL AND s.mother_phone != '')";

    $binds = [];
    $types = '';
    if (!empty($class_name)) {
        $sql   .= " AND s.class = ?";
        $types .= 's';
        $binds[] = $class_name;
    }

    $stmt = $conn->prepare($sql);
    if ($binds) {
        $stmt->bind_param($types, ...$binds);
    }
    $stmt->execute();
    $students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

    $accounts_created  = 0;
    $already_existed   = 0;
    $sms_sent          = 0;

    foreach ($students as $student) {
        // Collect unique phones for this student
        $phone_map = [];
        if (!empty($student['father_phone'])) {
            $phone_map[$student['father_phone']] = $student['father_name'] ?: 'Parent';
        }
        if (!empty($student['mother_phone'])) {
            $phone_map[$student['mother_phone']] = $student['mother_name'] ?: 'Parent';
        }

        foreach ($phone_map as $phone => $parent_name) {
            $phone = trim($phone);
            if (empty($phone)) continue;

            // Check if parent account already exists for this phone
            $chk_stmt = $conn->prepare(
                "SELECT id FROM parent_accounts WHERE phone = ? LIMIT 1"
            );
            $chk_stmt->bind_param('s', $phone);
            $chk_stmt->execute();
            $existing = $chk_stmt->get_result()->fetch_assoc();

            if ($existing) {
                // Ensure student link exists
                $link_chk = $conn->prepare(
                    "SELECT id FROM parent_student_link WHERE parent_id = ? AND student_id = ?"
                );
                $link_chk->bind_param('ii', $existing['id'], $student['id']);
                $link_chk->execute();
                if (!$link_chk->get_result()->fetch_assoc()) {
                    $link_ins = $conn->prepare(
                        "INSERT INTO parent_student_link (parent_id, student_id) VALUES (?,?)"
                    );
                    $link_ins->bind_param('ii', $existing['id'], $student['id']);
                    $link_ins->execute();
                }
                $already_existed++;
                continue;
            }

            // Generate random password
            $password    = substr(str_shuffle('ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'), 0, 8);
            $password_hash = password_hash($password, PASSWORD_DEFAULT);
            $username    = 'parent_' . preg_replace('/[^0-9]/', '', $phone);

            // Create parent account (full_name is NOT NULL so include it alongside parent_name)
            $ins_stmt = $conn->prepare(
                "INSERT INTO parent_accounts (full_name, parent_name, username, phone, password_hash, is_active, created_at)
                 VALUES (?, ?, ?, ?, ?, 1, NOW())"
            );
            $ins_stmt->bind_param('sssss', $parent_name, $parent_name, $username, $phone, $password_hash);
            if (!$ins_stmt->execute()) continue;

            $new_parent_id = (int) $conn->insert_id;
            $accounts_created++;

            // Link to student
            $link_ins = $conn->prepare(
                "INSERT INTO parent_student_link (parent_id, student_id) VALUES (?,?)"
            );
            $link_ins->bind_param('ii', $new_parent_id, $student['id']);
            $link_ins->execute();

            // Send welcome SMS
            $student_name = $student['first_name'] . ' ' . $student['last_name'];
            $sms = "Welcome to {$school_name} Parent Portal! Your login: {$username}, Password: {$password}. " .
                   "Student: {$student_name}. Visit " . (defined('BASE_URL') ? BASE_URL : '') . "parent-portal/";
            if (strlen($sms) > 160) {
                $sms = substr($sms, 0, 157) . '...';
            }
            if (sendSMS($phone, $sms)) {
                $sms_sent++;
            }
        }
    }

    return [
        'success'          => true,
        'accounts_created' => $accounts_created,
        'already_existed'  => $already_existed,
        'sms_sent'         => $sms_sent,
        'students_checked' => count($students),
    ];
}
