<?php

namespace App\Models;

use App\Core\Model;
use PDO;

class Teacher extends Model {
    public function search($params = []) {
        $sql = "SELECT * FROM teachers WHERE 1=1";
        $binds = [];

        if (!empty($params['search'])) {
            $sql .= " AND (name LIKE :search OR phone LIKE :search OR email LIKE :search OR subject LIKE :search)";
            $binds['search'] = '%' . $params['search'] . '%';
        }

        if (!empty($params['status_filter'])) {
            $sql .= " AND status = :status";
            $binds['status'] = $params['status_filter'];
        }

        $sql .= " ORDER BY id DESC";
        $stmt = $this->db->prepare($sql);
        if (!empty($binds)) {
            $stmt->execute($binds);
        } else {
            $stmt->execute();
        }
        return $stmt->fetchAll();
    }

    public function find($id) {
        $stmt = $this->db->prepare("SELECT * FROM teachers WHERE id = :id LIMIT 1");
        $stmt->execute(['id' => $id]);
        return $stmt->fetch();
    }

    public function save($data) {
        if (!empty($data['id'])) {
            $sql = "UPDATE teachers SET 
                    name = :name, 
                    phone = :phone, 
                    email = :email, 
                    subject = :subject, 
                    status = :status 
                    WHERE id = :id";
            $stmt = $this->db->prepare($sql);
            return $stmt->execute([
                'name' => $data['name'],
                'phone' => $data['phone'],
                'email' => $data['email'],
                'subject' => $data['subject'] ?? null,
                'status' => $data['status'] ?? 'Active',
                'id' => $data['id']
            ]);
        } else {
            $sql = "INSERT INTO teachers (name, phone, email, subject, status) 
                    VALUES (:name, :phone, :email, :subject, :status)";
            $stmt = $this->db->prepare($sql);
            return $stmt->execute([
                'name' => $data['name'],
                'phone' => $data['phone'],
                'email' => $data['email'],
                'subject' => $data['subject'] ?? null,
                'status' => $data['status'] ?? 'Active'
            ]);
        }
    }

    public function delete($id) {
        $stmt = $this->db->prepare("DELETE FROM teachers WHERE id = :id");
        return $stmt->execute(['id' => $id]);
    }
}
