<?php
namespace App\Services;

class StudentService {
    public function __construct(private \PDO $pdo) {}

    public function createStudentAccount(array $data): array {
        $roleId = (int)($this->pdo->query("SELECT id FROM roles WHERE slug = 'student' LIMIT 1")->fetchColumn() ?: 6);
        $hash = $data['password_hash'] ?? password_hash($data['password'] ?? bin2hex(random_bytes(8)), PASSWORD_DEFAULT);
        $this->pdo->prepare("INSERT INTO users (role_id, first_name, last_name, email, phone, whatsapp, password_hash, is_active, email_verified_at) VALUES (?, ?, ?, ?, ?, ?, ?, 1, NOW())")
            ->execute([$roleId, $data['first_name'], $data['last_name'], $data['email'], $data['phone'] ?? null, $data['whatsapp'] ?? null, $hash]);
        $userId = (int)$this->pdo->lastInsertId();
        $studentNumber = generate_student_number($this->pdo);
        $this->pdo->prepare("INSERT INTO students (user_id, student_number, id_passport, province, town, highest_education, application_status, enrollment_status, current_package_id, payment_status) VALUES (?, ?, ?, ?, ?, ?, ?, 'not_enrolled', ?, 'awaiting_proof')")
            ->execute([$userId, $studentNumber, $data['id_passport'] ?? null, $data['province'] ?? null, $data['town'] ?? null, $data['highest_education'] ?? null, $data['application_status'] ?? 'accepted', $data['package_id'] ?? null]);
        return ['user_id' => $userId, 'student_id' => (int)$this->pdo->lastInsertId(), 'student_number' => $studentNumber];
    }

    public function findByUserId(int $userId): ?array {
        $stmt = $this->pdo->prepare("SELECT s.*, u.first_name, u.last_name, u.email FROM students s JOIN users u ON s.user_id = u.id WHERE s.user_id = ? LIMIT 1");
        $stmt->execute([$userId]);
        return $stmt->fetch() ?: null;
    }
}
