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

class VaultController extends \Core\Controller {

    private $lockTimeout = 300; // 5 minutes securely

    private function getVaultModel() {
        return $this->model('Vault/Models/VaultModel');
    }

    /**
     * Entry Point
     */
    public function index() {
        $this->protectVault(); // Blocks execution if locked

        $model = $this->getVaultModel();
        
        // Return encrypted items, decryption happens in JS
        $items = $model->getItems($this->userId);
        
        $this->view('Vault/Views/index', [
            'title' => 'Vault | الخزنة الذكية',
            'items' => $items
        ]);
    }

    /**
     * Strict Layer Validation
     */
    private function protectVault() {
        $model = $this->getVaultModel();
        
        // Setup Mode
        $sec = $model->getSecurityStatus($this->userId);
        if (!$sec) {
            $this->view('Vault/Views/lock_screen', ['setupMode' => true]);
            exit;
        }

        // Validation & Auto-Lock
        $unlockedAt = $_SESSION['vault_unlocked_at'] ?? 0;
        $isVerified = $_SESSION['vault_verified'] ?? false;
        
        if (!$isVerified || (time() - $unlockedAt) > $this->lockTimeout) {
            $this->lockSession();
            $this->view('Vault/Views/lock_screen', ['setupMode' => false]);
            exit;
        }

        // Keep session alive if active interaction
        $_SESSION['vault_unlocked_at'] = time();
    }

    private function lockSession() {
        unset($_SESSION['vault_unlocked_at']);
        unset($_SESSION['vault_verified']);
    }

    public function lock() {
        $this->lockSession();
        echo json_encode(['success' => true]);
        exit;
    }

    /**
     * Auth Methods
     */
    public function setupMaster() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
            $authPassword = trim($input['auth_password'] ?? '');
            $encSalt = trim($input['enc_salt'] ?? '');
            
            if (!$authPassword || !$encSalt) {
                echo json_encode(['success' => false, 'message' => 'بيانات التشفير غير مكتملة']);
                exit; 
            }

            $model = $this->getVaultModel();
            if ($model->getSecurityStatus($this->userId)) {
                echo json_encode(['success' => false, 'message' => 'مسجل مسبقاً']);
                exit; 
            }

            $model->setupMasterPassword($this->userId, $authPassword, $encSalt);
            
            // Auto open
            $_SESSION['vault_verified'] = true;
            $_SESSION['vault_unlocked_at'] = time();

            echo json_encode(['success' => true, 'redirect' => BASE_URL . '/vault', 'enc_salt' => $encSalt]);
            exit;
        }
    }

    public function unlock() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
            $authPassword = trim($input['auth_password'] ?? '');
            
            $model = $this->getVaultModel();
            
            if (!$model->verifyAuthPassword($this->userId, $authPassword)) {
                echo json_encode(['success' => false, 'message' => 'كلمة المرور الرئيسية غير صحيحة']);
                exit; 
            }

            $sec = $model->getSecurityStatus($this->userId);
            
            // Unlocked
            $_SESSION['vault_verified'] = true;
            $_SESSION['vault_unlocked_at'] = time();
            echo json_encode([
                'success' => true, 
                'redirect' => BASE_URL . '/vault',
                'enc_salt' => $sec->enc_salt
            ]);
            exit;
        }
    }

    /**
     * Vault Items CRUD
     */
    public function addItem() {
        $this->protectVault();
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
            $this->getVaultModel()->addItem(
                $this->userId, 
                $input['cipher_data'], 
                $input['iv']
            );
            echo json_encode(['success' => true]);
        }
    }

    public function editItem() {
        $this->protectVault();
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
            $this->getVaultModel()->updateItem(
                $this->userId, 
                $input['id'],
                $input['cipher_data'], 
                $input['iv']
            );
            echo json_encode(['success' => true]);
        }
    }

    public function deleteItem() {
        $this->protectVault();
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
            $this->getVaultModel()->deleteItem($this->userId, $input['id']);
            echo json_encode(['success' => true]);
        }
    }

    public function hardReset() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
            $authPassword = trim($input['auth_password'] ?? '');
            $text = trim($input['reset_text'] ?? '');
            
            if ($text !== 'RESET VAULT') {
                echo json_encode(['success' => false, 'message' => 'كلمة التأكيد خاطئة']);
                exit;
            }

            $model = $this->getVaultModel();
            if (!$model->verifyAuthPassword($this->userId, $authPassword)) {
                echo json_encode(['success' => false, 'message' => 'كلمة المرور خاطئة']);
                exit;
            }

            $model->hardReset($this->userId);
            
            unset($_SESSION['vault_verified']);
            unset($_SESSION['vault_unlocked_at']);
            
            echo json_encode(['success' => true, 'redirect' => BASE_URL . '/vault']);
            exit;
        }
    }
}

