<?php
namespace App\Modules\Vault\Models;

class VaultModel extends \Core\Model {
    protected $useSoftDeletes = false;
    protected $logActions = false; 

    // ── 1. Security Context ──────────────────────────────────────────

    public function getSecurityStatus($userId) {
        return $this->db->query("SELECT * FROM vault_security WHERE user_id = ?", [$userId])->fetch(\PDO::FETCH_OBJ);
    }

    public function setupMasterPassword($userId, $authPassword, $encSalt) {
        $hash = password_hash($authPassword, PASSWORD_DEFAULT);
        return $this->db->query("INSERT INTO vault_security (user_id, master_hash, enc_salt) VALUES (?, ?, ?)", [$userId, $hash, $encSalt]);
    }

    public function verifyAuthPassword($userId, $authPassword) {
        $sec = $this->getSecurityStatus($userId);
        if (!$sec) return false;
        return password_verify($authPassword, $sec->master_hash);
    }

    // ── 2. Vault Items (Zero-Knowledge AES-256-GCM) ──────────────────

    public function getItems($userId) {
        return $this->db->query("SELECT id, cipher_data, iv, created_at, updated_at FROM vault_items WHERE user_id = ? ORDER BY id DESC", [$userId])->fetchAll(\PDO::FETCH_OBJ);
    }

    public function addItem($userId, $cipherData, $iv) {
        return $this->db->query(
            "INSERT INTO vault_items (user_id, cipher_data, iv) VALUES (?, ?, ?)",
            [$userId, $cipherData, $iv]
        );
    }

    public function updateItem($userId, $id, $cipherData, $iv) {
        return $this->db->query(
            "UPDATE vault_items SET cipher_data=?, iv=? WHERE id=? AND user_id=?",
            [$cipherData, $iv, $id, $userId]
        );
    }

    public function deleteItem($userId, $id) {
        return $this->db->query("DELETE FROM vault_items WHERE id=? AND user_id=?", [$id, $userId]);
    }

    public function hardReset($userId) {
        $this->db->query("DELETE FROM vault_items WHERE user_id = ?", [$userId]);
        $this->db->query("DELETE FROM vault_security WHERE user_id = ?", [$userId]);
        return true;
    }
}
