<?php

namespace App\Models\Base;

use Wibiesana\Padi\Core\ActiveRecord;
use Wibiesana\Padi\Core\Query;

class Internship extends ActiveRecord
{
    protected string $table = 'internships';
    protected string|array $primaryKey = 'id';
    
    protected array $fillable = [
        'company_id', 'student_id', 'advisor_teacher_id', 'start_date', 'end_date', 'report_file_path', 'advisor_score', 'attachments', 'status'
    ];
    
    protected array $hidden = [];

    /**
     * Audit fields detected: created_at, updated_at, created_by, updated_by
     * These will be auto-populated by ActiveRecord
     */
    protected bool $useAudit = true;
    
    /**
     * Timestamp format: 'datetime'
     * 'datetime' = Y-m-d H:i:s (DATETIME/TIMESTAMP columns)
     * 'unix' = integer timestamp (INT/BIGINT columns)
     */
    protected string $timestampFormat = 'datetime';


    public function company()
    {
        return $this->belongsTo(\App\Models\Company::class, 'company_id');
    }

    public function student()
    {
        return $this->belongsTo(\App\Models\Student::class, 'student_id');
    }

    public function advisorTeacher()
    {
        return $this->belongsTo(\App\Models\Teacher::class, 'advisor_teacher_id');
    }

    /**
     * Build global search conditions
     * Searches all fillable fields + related table display columns
     */
    protected function buildSearchConditions(string $keyword): array
    {
        $conditions = ['OR'];

        // Search all fillable fields from this table
        foreach ($this->fillable as $field) {
            $conditions[] = ["{$this->table}.{$field}", 'LIKE', $keyword];
        }

            // Search in related tables
            $conditions[] = ['companies.name', 'LIKE', $keyword];
            $conditions[] = ['student.name', 'LIKE', $keyword];
            $conditions[] = ['teacher.name', 'LIKE', $keyword];

        return $conditions;
    }

    /**
     * Search with pagination and joins
     */
    public function searchPaginate(string $keyword, int $page = 1, int $perPage = 25, ?string $orderBy = null): array
    {
        $keyword = "%{$keyword}%";
        $conditions = $this->buildSearchConditions($keyword);

        $query = Query::find()
            ->select("{$this->table}.*")
            ->from($this->table)
            ->leftJoin('companies AS companies', 'internships.company_id = companies.id')
            ->leftJoin('student AS student', 'internships.student_id = student.id')
            ->leftJoin('teacher AS teacher', 'internships.advisor_teacher_id = teacher.id')
            ->where($conditions);

        if ($orderBy) {
            $query->orderBy($orderBy);
        } else {
            $query->orderBy("{$this->table}.id DESC");
        }

        $result = $query->paginate($perPage, $page);

        if (!empty($result['data'])) {
            $this->loadRelations($result['data']);
            $result['data'] = $this->hideFields($result['data']);
        }

        return [
            'data' => $result['data'],
            'meta' => [
                'total' => (int)$result['total'],
                'per_page' => $result['per_page'],
                'current_page' => $result['current_page'],
                'last_page' => $result['last_page'],
                'from' => ($result['current_page'] - 1) * $result['per_page'] + 1,
                'to' => min($result['current_page'] * $result['per_page'], $result['total'])
            ]
        ];
    }

    /**
     * Search internships (simple limit)
     */
    public function search(string $keyword, ?string $orderBy = null): array
    {
        $keyword = "%{$keyword}%";
        $conditions = $this->buildSearchConditions($keyword);

        $query = Query::find()
            ->select("{$this->table}.*")
            ->from($this->table)
            ->leftJoin('companies AS companies', 'internships.company_id = companies.id')
            ->leftJoin('student AS student', 'internships.student_id = student.id')
            ->leftJoin('teacher AS teacher', 'internships.advisor_teacher_id = teacher.id')
            ->where($conditions)
            ->limit(100);

        if ($orderBy) {
            $query->orderBy($orderBy);
        } else {
            $query->orderBy("{$this->table}.id DESC");
        }

        $results = $query->all();

        if (!empty($results)) {
            $this->loadRelations($results);
            $results = $this->hideFields($results);
        }

        return $results;
    }
}