<?php

class VerificationController {

    /**
     * POST /api/user/verify-id
     * Form data: id_type, document_number, full_name, dob
     * File: front_image
     */
    public static function submitVerification(): void {
        $user = AuthController::requireAuth();
        $userId = $user['id'];

        // Get POST data
        $idType         = trim($_POST['id_type'] ?? '');
        $documentNumber = trim($_POST['document_number'] ?? '');
        $fullName       = trim($_POST['full_name'] ?? '');
        $dob            = trim($_POST['dob'] ?? '');

        // Map id_type to proof_type ENUM
        // enum('aadhar','driving_license','passport','voter_id','pan_card')
        $proofTypeMap = [
            'Aadhaar Card'     => 'aadhar',
            'Driving License'  => 'driving_license',
            'Passport'         => 'passport',
            'Voter ID'         => 'voter_id',
            'PAN Card'         => 'pan_card'
        ];

        $proofType = $proofTypeMap[$idType] ?? 'aadhar'; // Default to aadhar or handle error

        // Validation
        $errors = [];
        if (!$idType)         $errors['id_type'] = 'ID type is required';
        if (!$documentNumber) $errors['document_number'] = 'Document number is required';
        if (!$fullName)       $errors['full_name'] = 'Full name is required';
        if (!$dob)            $errors['dob'] = 'Date of birth is required';

        if (!isset($_FILES['front_image']) || $_FILES['front_image']['error'] !== UPLOAD_ERR_OK) {
            $errors['front_image'] = 'Front image is required';
        }

        if ($errors) sendError('Validation failed', 422, $errors);

        // Handle file upload
        $ext = pathinfo($_FILES['front_image']['name'], PATHINFO_EXTENSION);
        $fileName = 'proof_' . $userId . '_' . time() . '.' . $ext;
        
        // Admin path is assets/images/id_proofs/
        $uploadDir = dirname(BASE_PATH) . '/assets/images/id_proofs/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
        
        $targetPath = $uploadDir . $fileName;

        if (!move_uploaded_file($_FILES['front_image']['tmp_name'], $targetPath)) {
            sendError('Failed to save uploaded file', 500);
        }

        $db = getDb();
        try {
            $stmt = $db->prepare("
                INSERT INTO user_id_proofs (user_id, proof_type, proof_number, full_name, date_of_birth, front_image, verification_status)
                VALUES (?, ?, ?, ?, ?, ?, 'pending')
            ");
            $stmt->bind_param('isssss', $userId, $proofType, $documentNumber, $fullName, $dob, $fileName);
            $stmt->execute();
            $stmt->close();

            sendSuccess(null, 'Verification request submitted successfully', 201);

        } catch (Exception $e) {
            if (file_exists($targetPath)) unlink($targetPath);
            sendError('Database error: ' . $e->getMessage(), 500);
        }
    }
}
