<?php
namespace App\Models;

use App\Core\Model;

class Biometrics extends Model {
    protected $table = 'biometrics';
    protected $primaryKey = 'id';
    protected $fillable = [
        'person_id', 'capture_date', 'capture_device_id', 
        'capture_location', 'created_by'
    ];
    
    /**
     * Get biometrics for a person
     */
    public function getByPerson($person_id) {
        $stmt = $this->db->prepare("
            SELECT * FROM {$this->table} 
            WHERE person_id = ? 
            ORDER BY capture_date DESC
        ");
        $stmt->execute([$person_id]);
        return $stmt->fetchAll();
    }
    
    /**
     * Get latest biometrics for a person
     */
    public function getLatestByPerson($person_id) {
        $stmt = $this->db->prepare("
            SELECT * FROM {$this->table} 
            WHERE person_id = ? 
            ORDER BY capture_date DESC 
            LIMIT 1
        ");
        $stmt->execute([$person_id]);
        return $stmt->fetch();
    }
    
    /**
     * Create biometrics record with fingerprints
     */
    public function createWithFingerprints($person_id, $data, $fingerprints) {
        try {
            $this->beginTransaction();
            
            // Create biometrics record
            $biometricsData = [
                'person_id' => $person_id,
                'capture_date' => $data['capture_date'] ?? date('Y-m-d H:i:s'),
                'capture_device_id' => $data['capture_device_id'] ?? null,
                'capture_location' => $data['capture_location'] ?? null,
                'created_by' => $_SESSION['user_id']
            ];
            
            $biometrics = $this->create($biometricsData);
            
            if (!$biometrics) {
                throw new \Exception("Failed to create biometrics record");
            }
            
            // Add fingerprints
            $fingerprintModel = new Fingerprint();
            foreach ($fingerprints as $fp) {
                $fp['biometrics_id'] = $biometrics['id'];
                $fingerprintModel->create($fp);
            }
            
            $this->commit();
            return $biometrics;
            
        } catch (\Exception $e) {
            $this->rollback();
            throw $e;
        }
    }
}